diff --git a/librarian.yaml b/librarian.yaml index ba829e9d37ed..eed01ce32d45 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.51.0 repo: googleapis/google-cloud-python sources: googleapis: - commit: 968d491eddafaf61da6b8bd0a6a2710ec9e2fdbc - sha256: f61663b244a2907b2cce73cb16589f103d203cace88ed5a79228e27dc415bfe2 + commit: 856bc831c52e81258768bba07eea278b78681924 + sha256: 56ff0144615a042ae3f9e367f37f5e862a1afa0e5f6ce710e62fb18038a793ca tools: pip: - name: black diff --git a/packages/google-apps-chat/google/apps/chat/__init__.py b/packages/google-apps-chat/google/apps/chat/__init__.py index 34a2a997629d..62b742a0970d 100644 --- a/packages/google-apps-chat/google/apps/chat/__init__.py +++ b/packages/google-apps-chat/google/apps/chat/__init__.py @@ -55,8 +55,12 @@ MarkAsDoNotDisturbRequest, UpdateAvailabilityRequest, ) +from google.apps.chat_v1.types.citation import Citation +from google.apps.chat_v1.types.cited_source import CitedSource from google.apps.chat_v1.types.contextual_addon import ContextualAddOnMarkup from google.apps.chat_v1.types.deletion_metadata import DeletionMetadata +from google.apps.chat_v1.types.elements import Elements +from google.apps.chat_v1.types.elements_common import ElementsImage from google.apps.chat_v1.types.event_payload import ( MembershipBatchCreatedEventData, MembershipBatchDeletedEventData, @@ -224,8 +228,12 @@ "MarkAsAwayRequest", "MarkAsDoNotDisturbRequest", "UpdateAvailabilityRequest", + "Citation", + "CitedSource", "ContextualAddOnMarkup", "DeletionMetadata", + "Elements", + "ElementsImage", "MembershipBatchCreatedEventData", "MembershipBatchDeletedEventData", "MembershipBatchUpdatedEventData", 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 86b3ab050dec..311ffd690d0b 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/__init__.py +++ b/packages/google-apps-chat/google/apps/chat_v1/__init__.py @@ -34,8 +34,12 @@ "google.apps.chat_v1.types.audience", "google.apps.chat_v1.types.availability", "google.apps.chat_v1.types.chat_service", + "google.apps.chat_v1.types.citation", + "google.apps.chat_v1.types.cited_source", "google.apps.chat_v1.types.contextual_addon", "google.apps.chat_v1.types.deletion_metadata", + "google.apps.chat_v1.types.elements", + "google.apps.chat_v1.types.elements_common", "google.apps.chat_v1.types.event_payload", "google.apps.chat_v1.types.group", "google.apps.chat_v1.types.history_state", @@ -92,8 +96,12 @@ MarkAsDoNotDisturbRequest, UpdateAvailabilityRequest, ) +from .types.citation import Citation +from .types.cited_source import CitedSource from .types.contextual_addon import ContextualAddOnMarkup from .types.deletion_metadata import DeletionMetadata +from .types.elements import Elements +from .types.elements_common import ElementsImage from .types.event_payload import ( MembershipBatchCreatedEventData, MembershipBatchDeletedEventData, @@ -245,6 +253,8 @@ "CardWithId", "ChatServiceClient", "ChatSpaceLinkData", + "Citation", + "CitedSource", "CompleteImportSpaceRequest", "CompleteImportSpaceResponse", "ContextualAddOnMarkup", @@ -272,6 +282,8 @@ "DoNotDisturbMetadata", "DriveDataRef", "DriveLinkData", + "Elements", + "ElementsImage", "Emoji", "EmojiReactionSummary", "FindDirectMessageRequest", 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 51cc3d64468f..5038b7bcefa4 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 @@ -54,6 +54,7 @@ availability, contextual_addon, deletion_metadata, + elements, event_payload, group, history_state, 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 9b7744cdf1bc..c374abbb59f1 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 @@ -78,6 +78,7 @@ availability, contextual_addon, deletion_metadata, + elements, event_payload, group, history_state, 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 1d636cc8edc4..4465f47dafba 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 @@ -52,12 +52,24 @@ MarkAsDoNotDisturbRequest, UpdateAvailabilityRequest, ) +from .citation import ( + Citation, +) +from .cited_source import ( + CitedSource, +) from .contextual_addon import ( ContextualAddOnMarkup, ) from .deletion_metadata import ( DeletionMetadata, ) +from .elements import ( + Elements, +) +from .elements_common import ( + ElementsImage, +) from .event_payload import ( MembershipBatchCreatedEventData, MembershipBatchDeletedEventData, @@ -239,8 +251,12 @@ "MarkAsAwayRequest", "MarkAsDoNotDisturbRequest", "UpdateAvailabilityRequest", + "Citation", + "CitedSource", "ContextualAddOnMarkup", "DeletionMetadata", + "Elements", + "ElementsImage", "MembershipBatchCreatedEventData", "MembershipBatchDeletedEventData", "MembershipBatchUpdatedEventData", diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/citation.py b/packages/google-apps-chat/google/apps/chat_v1/types/citation.py new file mode 100644 index 000000000000..d44806cc497d --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/citation.py @@ -0,0 +1,68 @@ +# -*- 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 + +from google.apps.chat_v1.types import cited_source + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "Citation", + }, +) + + +class Citation(proto.Message): + r"""Citations are inline references that can provide users more detailed + information about the inline reference. Corresponding inline + citations should be present in the message text in a markup format + of ``{text}``. + Citations are only supported when the message's ``markup_syntax`` is + set to ``MARKDOWN``. + + Unreferenced citations in ``Elements.citations`` (those without a + matching ```` tag in the message text) are ignored + and do not cause the message to be rejected. + + Attributes: + id (str): + Required. The ID of the citation. This ID is defined by the + app creating the citation and must match the ``data-id`` + attribute of the ```` tag in the message + text. Must contain only ASCII letters and numbers, and less + than 63 characters. + cited_sources (MutableSequence[google.apps.chat_v1.types.CitedSource]): + Optional. A list of sources that are relevant + to the citation. Sources are displayed in the + citation hover card. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + cited_sources: MutableSequence[cited_source.CitedSource] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=cited_source.CitedSource, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/cited_source.py b/packages/google-apps-chat/google/apps/chat_v1/types/cited_source.py new file mode 100644 index 000000000000..42d277baf0ab --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/cited_source.py @@ -0,0 +1,112 @@ +# -*- 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 + +from google.apps.chat_v1.types import elements_common + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "CitedSource", + }, +) + + +class CitedSource(proto.Message): + r"""A reference to a source of information. + + Attributes: + title (str): + Required. The plaintext title of the ``CitedSource``. Does + not support markdown format. + uri (str): + Required. The URI pointing to the resource referenced by + this ``CitedSource``. + snippet (google.apps.chat_v1.types.CitedSource.Snippet): + Optional. Snippet containing information + directly from the source. + footer (google.apps.chat_v1.types.CitedSource.Footer): + Optional. Additional information to show + alongside the snippet in the form of a footer. + """ + + class Snippet(proto.Message): + r"""A snippet object representing an excerpt from a larger + corpus. + + Attributes: + text (str): + Optional. A short plaintext excerpt directly from the corpus + that is rendered in the citation hover card or source + preview. When footer sources are automatically populated + from inline ``citations`` (because + ``Elements.cited_sources`` is not set), snippets are omitted + from the deduplicated footer sources. Does not support + markdown format, and must not exceed 1,000 characters. + image_preview (google.apps.chat_v1.types.ElementsImage): + Optional. Image preview of the snippet + provided as an input when creating the citation. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + image_preview: elements_common.ElementsImage = proto.Field( + proto.MESSAGE, + number=2, + message=elements_common.ElementsImage, + ) + + class Footer(proto.Message): + r"""A footer for a source, used for attribution. + + Attributes: + text (str): + Optional. The plaintext to display in the + footer. Does not support markdown format. + """ + + text: str = proto.Field( + proto.STRING, + number=1, + ) + + title: str = proto.Field( + proto.STRING, + number=1, + ) + uri: str = proto.Field( + proto.STRING, + number=2, + ) + snippet: Snippet = proto.Field( + proto.MESSAGE, + number=3, + message=Snippet, + ) + footer: Footer = proto.Field( + proto.MESSAGE, + number=5, + message=Footer, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/elements.py b/packages/google-apps-chat/google/apps/chat_v1/types/elements.py new file mode 100644 index 000000000000..14aa4b29074c --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/elements.py @@ -0,0 +1,65 @@ +# -*- 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 + +from google.apps.chat_v1.types import citation, cited_source + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "Elements", + }, +) + + +class Elements(proto.Message): + r"""Elements are additional message components, including inline + ``citations`` (where each citation is associated with a specific + portion of the message text) and ``cited_sources`` (which are + general references used to generate the response and are not + directly linked to specific segments of the text). Both + ``citations`` and ``cited_sources`` can be provided as input when + creating or updating a message and are populated on output when + reading a message. + + Attributes: + cited_sources (MutableSequence[google.apps.chat_v1.types.CitedSource]): + Optional. A list of sources to be displayed under the + message as footer links. These are not referenced inline. + For inline references, use ``citations``. + citations (MutableSequence[google.apps.chat_v1.types.Citation]): + Optional. A list of inline citations referenced within the + message text (via ```` tags) that render as + interactive hover cards. + """ + + cited_sources: MutableSequence[cited_source.CitedSource] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=cited_source.CitedSource, + ) + citations: MutableSequence[citation.Citation] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=citation.Citation, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/elements_common.py b/packages/google-apps-chat/google/apps/chat_v1/types/elements_common.py new file mode 100644 index 000000000000..e6afd9d6574e --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/elements_common.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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "ElementsImage", + }, +) + + +class ElementsImage(proto.Message): + r"""An object encapsulating different ways of representing an image. + Currently supported representations: + + - An image fetched from a URI. + + Additional representations might be supported in the future. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + image_uri (str): + Required. The URI of the image. Must be a + publicly accessible URI so that Chat can fetch + and display it. + + This field is a member of `oneof`_ ``image``. + """ + + image_uri: str = proto.Field( + proto.STRING, + number=1, + oneof="image", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/message.py b/packages/google-apps-chat/google/apps/chat_v1/types/message.py index 336c0f09d2c1..8ee2931b6749 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/message.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/message.py @@ -32,6 +32,7 @@ ) from google.apps.chat_v1.types import attachment as gc_attachment from google.apps.chat_v1.types import deletion_metadata as gc_deletion_metadata +from google.apps.chat_v1.types import elements as gc_elements from google.apps.chat_v1.types import markup_syntax as gc_markup_syntax from google.apps.chat_v1.types import matched_url as gc_matched_url from google.apps.chat_v1.types import slash_command as gc_slash_command @@ -285,6 +286,25 @@ class Message(proto.Message): Creating a message with accessory widgets requires [app authentication] (https://developers.google.com/workspace/chat/authenticate-authorize-chat-app). + elements (google.apps.chat_v1.types.Elements): + Optional. Additional message components, including inline + ``citations`` (where each citation is associated with a + specific portion of the message text) and ``cited_sources`` + (which are general references used to generate the response + and are not directly linked to specific segments of the + text). + + On input, provide ``elements`` when creating or updating a + message. On output, both ``citations`` and ``cited_sources`` + are populated when reading a message that contains them. + Callers can read structured citation metadata from + ``elements``, while ``formatted_text`` also includes inline + citation tags or source links depending on + ``markup_syntax``. + + These differ from ``annotations``, which are output-only and + offer supplementary information tied to message fragments or + the entire message text. markup_syntax (google.apps.chat_v1.types.MarkupSyntax): Optional. Specifies how the server interprets the message ``text`` field content. @@ -421,6 +441,11 @@ class Message(proto.Message): number=44, message="AccessoryWidget", ) + elements: gc_elements.Elements = proto.Field( + proto.MESSAGE, + number=45, + message=gc_elements.Elements, + ) markup_syntax: gc_markup_syntax.MarkupSyntax = proto.Field( proto.ENUM, number=47, 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 7a6bdfdaae64..09ed75fe600c 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 @@ -354,7 +354,7 @@ class SpaceDetails(proto.Message): example, describe the space's discussion topic, functional purpose, or participants. - Supports up to 150 characters. + Supports up to 4,096 characters. guidelines (str): Optional. The space's rules, expectations, and etiquette. 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 617ef25b0c2e..1a1cfeee03e3 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 @@ -71,8 +71,12 @@ attachment, audience, availability, + citation, + cited_source, contextual_addon, deletion_metadata, + elements, + elements_common, event_payload, group, history_state, @@ -32354,6 +32358,20 @@ def test_create_message_rest_call_success(request_type): }, "attached_gifs": [{"uri": "uri_value"}], "accessory_widgets": [{"button_list": {}}], + "elements": { + "cited_sources": [ + { + "title": "title_value", + "uri": "uri_value", + "snippet": { + "text": "text_value", + "image_preview": {"image_uri": "image_uri_value"}, + }, + "footer": {"text": "text_value"}, + } + ], + "citations": [{"id": "id_value", "cited_sources": {}}], + }, "markup_syntax": 1, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -33598,6 +33616,20 @@ def test_update_message_rest_call_success(request_type): }, "attached_gifs": [{"uri": "uri_value"}], "accessory_widgets": [{"button_list": {}}], + "elements": { + "cited_sources": [ + { + "title": "title_value", + "uri": "uri_value", + "snippet": { + "text": "text_value", + "image_preview": {"image_uri": "image_uri_value"}, + }, + "footer": {"text": "text_value"}, + } + ], + "citations": [{"id": "id_value", "cited_sources": {}}], + }, "markup_syntax": 1, } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager/__init__.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager/__init__.py index 3115f3307815..35a0d80fd50f 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager/__init__.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager/__init__.py @@ -58,6 +58,14 @@ ScheduleState, UpdateAuditScheduleRequest, ) +from google.cloud.auditmanager_v1.types.parameters import ( + CloudControlParameterStates, + Parameter, + ParameterOverrides, + ParameterState, + ParamValue, + StringList, +) __all__ = ( "AuditManagerClient", @@ -94,4 +102,10 @@ "ComplianceState", "OperationState", "ScheduleState", + "CloudControlParameterStates", + "Parameter", + "ParameterOverrides", + "ParameterState", + "ParamValue", + "StringList", ) diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/__init__.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/__init__.py index 6ee06ad86de4..5e9cc5084dba 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/__init__.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/__init__.py @@ -28,6 +28,7 @@ __lazy_modules__ = { "google.cloud.auditmanager_v1.services.audit_manager", "google.cloud.auditmanager_v1.types.auditmanager", + "google.cloud.auditmanager_v1.types.parameters", } @@ -66,6 +67,14 @@ ScheduleState, UpdateAuditScheduleRequest, ) +from .types.parameters import ( + CloudControlParameterStates, + Parameter, + ParameterOverrides, + ParameterState, + ParamValue, + StringList, +) __all__ = ( "AuditManagerAsyncClient", @@ -73,6 +82,7 @@ "AuditReport", "AuditSchedule", "AuditScopeReport", + "CloudControlParameterStates", "ComplianceState", "Control", "ControlDetails", @@ -96,11 +106,16 @@ "ListResourceEnrollmentStatusesResponse", "OperationMetadata", "OperationState", + "ParamValue", + "Parameter", + "ParameterOverrides", + "ParameterState", "ReportGenerationProgress", "ReportSummary", "ResourceEnrollmentStatus", "ScheduleConfig", "ScheduleState", + "StringList", "UpdateAuditScheduleRequest", ) diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/base.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/base.py index 303811f4c353..c573dfa8294a 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/base.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/base.py @@ -157,7 +157,16 @@ def _prep_wrapped_messages(self, client_info): ), self.get_audit_schedule: gapic_v1.method.wrap_method( self.get_audit_schedule, - default_timeout=None, + default_retry=retries.Retry( + initial=0.1, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_audit_schedules: gapic_v1.method.wrap_method( diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc_asyncio.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc_asyncio.py index 58e6f92a78df..a0bdcf39517f 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc_asyncio.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/services/audit_manager/transports/grpc_asyncio.py @@ -735,7 +735,16 @@ def _prep_wrapped_messages(self, client_info): ), self.get_audit_schedule: self._wrap_method( self.get_audit_schedule, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=0.1, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_audit_schedules: self._wrap_method( diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/__init__.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/__init__.py index 4cefc35aa0b6..ff182cf66527 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/__init__.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/__init__.py @@ -47,6 +47,14 @@ ScheduleState, UpdateAuditScheduleRequest, ) +from .parameters import ( + CloudControlParameterStates, + Parameter, + ParameterOverrides, + ParameterState, + ParamValue, + StringList, +) __all__ = ( "AuditReport", @@ -81,4 +89,10 @@ "ComplianceState", "OperationState", "ScheduleState", + "CloudControlParameterStates", + "Parameter", + "ParameterOverrides", + "ParameterState", + "ParamValue", + "StringList", ) diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/auditmanager.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/auditmanager.py index 295b443ec193..0647be7d241c 100644 --- a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/auditmanager.py +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/auditmanager.py @@ -21,6 +21,8 @@ import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore +from google.cloud.auditmanager_v1.types import parameters + __protobuf__ = proto.module( package="google.cloud.auditmanager.v1", manifest={ @@ -277,6 +279,10 @@ class GenerateAuditScopeReportRequest(proto.Message): requests. - **CI/CD & Automation**: Test your scripts, permissions, and parameters safely without consuming resource quotas. + parameter_overrides (MutableMapping[str, google.cloud.auditmanager_v1.types.ParameterOverrides]): + Optional. Maps dynamic parameter overrides by Cloud Control + resource name at execution time. For example, + ``{"organizations/123/locations/global/cloudControls/control-1": {parameters: [...]}}`` """ class AuditScopeReportFormat(proto.Enum): @@ -313,6 +319,14 @@ class AuditScopeReportFormat(proto.Enum): proto.BOOL, number=6, ) + parameter_overrides: MutableMapping[str, parameters.ParameterOverrides] = ( + proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=parameters.ParameterOverrides, + ) + ) class GenerateAuditReportRequest(proto.Message): @@ -347,6 +361,10 @@ class GenerateAuditReportRequest(proto.Message): compliance_framework (str): Required. The framework that's used for the audit report. For example, ``NIST_800_53``. + parameter_overrides (MutableMapping[str, google.cloud.auditmanager_v1.types.ParameterOverrides]): + Optional. Maps dynamic parameter overrides by Cloud Control + resource name at execution time. For example, + ``{"organizations/123/locations/global/cloudControls/control-1": {parameters: [...]}}`` validate_only (bool): Optional. If ``true``, only validates the request and does not generate the audit report. This executes standard @@ -403,6 +421,14 @@ class AuditReportFormat(proto.Enum): proto.STRING, number=5, ) + parameter_overrides: MutableMapping[str, parameters.ParameterOverrides] = ( + proto.MapField( + proto.STRING, + proto.MESSAGE, + number=7, + message=parameters.ParameterOverrides, + ) + ) validate_only: bool = proto.Field( proto.BOOL, number=8, @@ -955,6 +981,10 @@ class AuditReport(proto.Message): Output only. Project number, folder ID, or organization ID that the audit report was generated for. + cloud_control_parameter_states (MutableMapping[str, google.cloud.auditmanager_v1.types.CloudControlParameterStates]): + Output only. Parameter values provided by the + user and values for tunable parameters, stored + in the DB, keyed by control name. """ class ReportGenerationState(proto.Enum): @@ -1034,6 +1064,14 @@ class ReportGenerationState(proto.Enum): proto.STRING, number=11, ) + cloud_control_parameter_states: MutableMapping[ + str, parameters.CloudControlParameterStates + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=16, + message=parameters.CloudControlParameterStates, + ) class ControlFamily(proto.Message): @@ -1541,6 +1579,10 @@ class AuditSchedule(proto.Message): error_message (str): Output only. Describes the error if the schedule is in an error state. + parameter_overrides (MutableMapping[str, google.cloud.auditmanager_v1.types.ParameterOverrides]): + Optional. Maps dynamic parameter overrides by Cloud Control + resource name at execution time. For example, + ``{"organizations/123/locations/global/cloudControls/control-1": {parameters: [...]}}`` """ class AuditReportFormat(proto.Enum): @@ -1611,6 +1653,14 @@ class AuditReportFormat(proto.Enum): proto.STRING, number=13, ) + parameter_overrides: MutableMapping[str, parameters.ParameterOverrides] = ( + proto.MapField( + proto.STRING, + proto.MESSAGE, + number=14, + message=parameters.ParameterOverrides, + ) + ) class ScheduleConfig(proto.Message): diff --git a/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/parameters.py b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/parameters.py new file mode 100644 index 000000000000..2b6634891938 --- /dev/null +++ b/packages/google-cloud-auditmanager/google/cloud/auditmanager_v1/types/parameters.py @@ -0,0 +1,188 @@ +# -*- 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.auditmanager.v1", + manifest={ + "Parameter", + "StringList", + "ParamValue", + "ParameterOverrides", + "ParameterState", + "CloudControlParameterStates", + }, +) + + +class Parameter(proto.Message): + r"""Parameters are key-value pairs that let you provide your + custom location requirements, environment requirements, or other + settings that are relevant to the cloud control. + + Attributes: + name (str): + Required. The name or key of the parameter. + parameter_value (google.cloud.auditmanager_v1.types.ParamValue): + Required. The value of the parameter. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + parameter_value: "ParamValue" = proto.Field( + proto.MESSAGE, + number=2, + message="ParamValue", + ) + + +class StringList(proto.Message): + r"""A list of strings for the parameter value. + + Attributes: + values (MutableSequence[str]): + Required. The strings in the list. + """ + + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + +class ParamValue(proto.Message): + r"""The possible parameter value types. + + 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: + string_value (str): + Optional. A string value. + + This field is a member of `oneof`_ ``kind``. + bool_value (bool): + Optional. A boolean value. + + This field is a member of `oneof`_ ``kind``. + string_list_value (google.cloud.auditmanager_v1.types.StringList): + Optional. A repeated string. + + This field is a member of `oneof`_ ``kind``. + number_value (float): + Optional. A double value. + + This field is a member of `oneof`_ ``kind``. + oneof_value (google.cloud.auditmanager_v1.types.Parameter): + Optional. Sub-parameter values. + + This field is a member of `oneof`_ ``kind``. + """ + + string_value: str = proto.Field( + proto.STRING, + number=3, + oneof="kind", + ) + bool_value: bool = proto.Field( + proto.BOOL, + number=4, + oneof="kind", + ) + string_list_value: "StringList" = proto.Field( + proto.MESSAGE, + number=5, + oneof="kind", + message="StringList", + ) + number_value: float = proto.Field( + proto.DOUBLE, + number=6, + oneof="kind", + ) + oneof_value: "Parameter" = proto.Field( + proto.MESSAGE, + number=7, + oneof="kind", + message="Parameter", + ) + + +class ParameterOverrides(proto.Message): + r"""Wrapper message to associate a list of CSC internal parameter + overrides with a control name. + + Attributes: + parameters (MutableSequence[google.cloud.auditmanager_v1.types.Parameter]): + The list of parameter overrides. + """ + + parameters: MutableSequence["Parameter"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Parameter", + ) + + +class ParameterState(proto.Message): + r"""State of a parameter for a cloud control. + + Attributes: + parameter (google.cloud.auditmanager_v1.types.Parameter): + Output only. The parameter key and value. + is_overridden (bool): + Output only. Whether this parameter was + overridden by the user. + """ + + parameter: "Parameter" = proto.Field( + proto.MESSAGE, + number=1, + message="Parameter", + ) + is_overridden: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class CloudControlParameterStates(proto.Message): + r"""Collection of parameter states for a cloud control. + + Attributes: + parameter_states (MutableSequence[google.cloud.auditmanager_v1.types.ParameterState]): + Output only. The parameter states for the + cloud control. + """ + + parameter_states: MutableSequence["ParameterState"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ParameterState", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-auditmanager/tests/unit/gapic/auditmanager_v1/test_audit_manager.py b/packages/google-cloud-auditmanager/tests/unit/gapic/auditmanager_v1/test_audit_manager.py index 4eac856e58a6..e6c9e0a547fc 100644 --- a/packages/google-cloud-auditmanager/tests/unit/gapic/auditmanager_v1/test_audit_manager.py +++ b/packages/google-cloud-auditmanager/tests/unit/gapic/auditmanager_v1/test_audit_manager.py @@ -66,7 +66,7 @@ pagers, transports, ) -from google.cloud.auditmanager_v1.types import auditmanager +from google.cloud.auditmanager_v1.types import auditmanager, parameters CRED_INFO_JSON = { "credential_source": "/path/to/file", @@ -9467,6 +9467,7 @@ def test_create_audit_schedule_rest_call_success(request_type): "next_run_time": {}, "last_trigger_time": {}, "error_message": "error_message_value", + "parameter_overrides": {}, } # 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 @@ -9707,6 +9708,7 @@ def test_update_audit_schedule_rest_call_success(request_type): "next_run_time": {}, "last_trigger_time": {}, "error_message": "error_message_value", + "parameter_overrides": {}, } # 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-backupdr/google/cloud/backupdr/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr/__init__.py index 069abf096d1f..1cb3c12aef8a 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr/__init__.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr/__init__.py @@ -26,6 +26,35 @@ from google.cloud.backupdr_v1.services.backup_dr_protection_summary.client import ( BackupDrProtectionSummaryClient, ) +from google.cloud.backupdr_v1.types.appliedautoprotectionpolicy import ( + AppliedAutoProtectionPolicy, + ListAppliedAutoProtectionPoliciesRequest, + ListAppliedAutoProtectionPoliciesResponse, +) +from google.cloud.backupdr_v1.types.autoprotectionpolicy import ( + AutoProtectionPolicy, + BackupPlanDetail, + BindingSummary, + CreateAutoProtectionPolicyRequest, + Criteria, + DeleteAutoProtectionPolicyRequest, + GetAutoProtectionPolicyRequest, + KeyValuePair, + ListAutoProtectionPoliciesRequest, + ListAutoProtectionPoliciesResponse, + MatchingCondition, + PolicyEvaluationSummary, + UpdateAutoProtectionPolicyRequest, +) +from google.cloud.backupdr_v1.types.autoprotectionpolicybinding import ( + AutoProtectionPolicyBinding, + BindingEvaluationSummary, + CreateAutoProtectionPolicyBindingRequest, + GetAutoProtectionPolicyBindingRequest, + InitiateDeleteAutoProtectionPolicyBindingRequest, + ListAutoProtectionPolicyBindingsRequest, + ListAutoProtectionPolicyBindingsResponse, +) from google.cloud.backupdr_v1.types.backupdr import ( CreateManagementServerRequest, DeleteManagementServerRequest, @@ -110,6 +139,7 @@ UpdateBackupRequest, UpdateBackupVaultRequest, UpdateDataSourceRequest, + VerificationSummary, ) from google.cloud.backupdr_v1.types.backupvault_alloydb import ( AlloyDBClusterBackupPlanAssociationProperties, @@ -159,6 +189,12 @@ ServiceAccount, Tags, ) +from google.cloud.backupdr_v1.types.bindingmatchingresource import ( + AutoProtectionDetails, + BindingMatchingResource, + ListBindingMatchingResourcesRequest, + ListBindingMatchingResourcesResponse, +) from google.cloud.backupdr_v1.types.datasourcereference import ( DataSourceBackupConfigInfo, DataSourceGcpResourceInfo, @@ -180,12 +216,87 @@ PitrSettings, ResourceBackupConfig, ) +from google.cloud.backupdr_v1.types.restore_template import ( + CreateRestoreTemplateRequest, + DeleteRestoreTemplateRequest, + ExecutionSummary, + GetRestoreTemplateRequest, + ListRestoreTemplatesRequest, + ListRestoreTemplatesResponse, + RestoreTemplate, + RunRestoreTemplateRequest, + RunRestoreTemplateResponse, + UpdateRestoreTemplateRequest, +) +from google.cloud.backupdr_v1.types.restore_template_common import ( + BackupSelectionConfig, + PostRestoreConfig, + PreRestoreConfig, + VerificationConfig, +) +from google.cloud.backupdr_v1.types.restore_template_execution import ( + CleanupPhaseInfo, + GetRestoreTemplateExecutionRequest, + ListRestoreTemplateExecutionsRequest, + ListRestoreTemplateExecutionsResponse, + PhaseState, + PostRestorePhaseInfo, + PreparePhaseInfo, + PreRestorePhaseInfo, + RestorePhaseInfo, + RestoreTemplateExecution, + TriggerRestoreCleanupRequest, + VerificationPhaseInfo, +) +from google.cloud.backupdr_v1.types.restore_verification_plan import ( + CreateRestoreVerificationPlanRequest, + DeleteRestoreVerificationPlanRequest, + GetRestoreVerificationPlanRequest, + ListRestoreVerificationPlansRequest, + ListRestoreVerificationPlansResponse, + RestoreVerificationCleanupRule, + RestoreVerificationPlan, +) +from google.cloud.backupdr_v1.types.restore_verification_plan_association import ( + CreateRestoreVerificationPlanAssociationRequest, + DeleteRestoreVerificationPlanAssociationRequest, + GetRestoreVerificationPlanAssociationRequest, + ListRestoreVerificationPlanAssociationsRequest, + ListRestoreVerificationPlanAssociationsResponse, + RestoreVerificationPlanAssociation, + TriggerRestoreVerificationRequest, + TriggerRestoreVerificationResponse, + TriggerSummary, +) __all__ = ( "BackupDRClient", "BackupDRAsyncClient", "BackupDrProtectionSummaryClient", "BackupDrProtectionSummaryAsyncClient", + "AppliedAutoProtectionPolicy", + "ListAppliedAutoProtectionPoliciesRequest", + "ListAppliedAutoProtectionPoliciesResponse", + "AutoProtectionPolicy", + "BackupPlanDetail", + "BindingSummary", + "CreateAutoProtectionPolicyRequest", + "Criteria", + "DeleteAutoProtectionPolicyRequest", + "GetAutoProtectionPolicyRequest", + "KeyValuePair", + "ListAutoProtectionPoliciesRequest", + "ListAutoProtectionPoliciesResponse", + "MatchingCondition", + "PolicyEvaluationSummary", + "UpdateAutoProtectionPolicyRequest", + "AutoProtectionPolicyBinding", + "BindingEvaluationSummary", + "CreateAutoProtectionPolicyBindingRequest", + "GetAutoProtectionPolicyBindingRequest", + "InitiateDeleteAutoProtectionPolicyBindingRequest", + "ListAutoProtectionPolicyBindingsRequest", + "ListAutoProtectionPolicyBindingsResponse", "CreateManagementServerRequest", "DeleteManagementServerRequest", "GetManagementServerRequest", @@ -260,6 +371,7 @@ "UpdateBackupRequest", "UpdateBackupVaultRequest", "UpdateDataSourceRequest", + "VerificationSummary", "BackupConfigState", "BackupVaultView", "BackupView", @@ -301,6 +413,10 @@ "ServiceAccount", "Tags", "KeyRevocationActionType", + "AutoProtectionDetails", + "BindingMatchingResource", + "ListBindingMatchingResourcesRequest", + "ListBindingMatchingResourcesResponse", "DataSourceBackupConfigInfo", "DataSourceGcpResourceInfo", "DataSourceReference", @@ -318,4 +434,46 @@ "ListResourceBackupConfigsResponse", "PitrSettings", "ResourceBackupConfig", + "CreateRestoreTemplateRequest", + "DeleteRestoreTemplateRequest", + "ExecutionSummary", + "GetRestoreTemplateRequest", + "ListRestoreTemplatesRequest", + "ListRestoreTemplatesResponse", + "RestoreTemplate", + "RunRestoreTemplateRequest", + "RunRestoreTemplateResponse", + "UpdateRestoreTemplateRequest", + "BackupSelectionConfig", + "PostRestoreConfig", + "PreRestoreConfig", + "VerificationConfig", + "CleanupPhaseInfo", + "GetRestoreTemplateExecutionRequest", + "ListRestoreTemplateExecutionsRequest", + "ListRestoreTemplateExecutionsResponse", + "PostRestorePhaseInfo", + "PreparePhaseInfo", + "PreRestorePhaseInfo", + "RestorePhaseInfo", + "RestoreTemplateExecution", + "TriggerRestoreCleanupRequest", + "VerificationPhaseInfo", + "PhaseState", + "CreateRestoreVerificationPlanRequest", + "DeleteRestoreVerificationPlanRequest", + "GetRestoreVerificationPlanRequest", + "ListRestoreVerificationPlansRequest", + "ListRestoreVerificationPlansResponse", + "RestoreVerificationCleanupRule", + "RestoreVerificationPlan", + "CreateRestoreVerificationPlanAssociationRequest", + "DeleteRestoreVerificationPlanAssociationRequest", + "GetRestoreVerificationPlanAssociationRequest", + "ListRestoreVerificationPlanAssociationsRequest", + "ListRestoreVerificationPlanAssociationsResponse", + "RestoreVerificationPlanAssociation", + "TriggerRestoreVerificationRequest", + "TriggerRestoreVerificationResponse", + "TriggerSummary", ) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/__init__.py index f60c23645cc7..1db603ecd01d 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/__init__.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/__init__.py @@ -28,6 +28,9 @@ __lazy_modules__ = { "google.cloud.backupdr_v1.services.backup_dr", "google.cloud.backupdr_v1.services.backup_dr_protection_summary", + "google.cloud.backupdr_v1.types.appliedautoprotectionpolicy", + "google.cloud.backupdr_v1.types.autoprotectionpolicy", + "google.cloud.backupdr_v1.types.autoprotectionpolicybinding", "google.cloud.backupdr_v1.types.backupdr", "google.cloud.backupdr_v1.types.backupplan", "google.cloud.backupdr_v1.types.backupplanassociation", @@ -37,8 +40,14 @@ "google.cloud.backupdr_v1.types.backupvault_cloudsql", "google.cloud.backupdr_v1.types.backupvault_disk", "google.cloud.backupdr_v1.types.backupvault_gce", + "google.cloud.backupdr_v1.types.bindingmatchingresource", "google.cloud.backupdr_v1.types.datasourcereference", "google.cloud.backupdr_v1.types.protection_summary", + "google.cloud.backupdr_v1.types.restore_template", + "google.cloud.backupdr_v1.types.restore_template_common", + "google.cloud.backupdr_v1.types.restore_template_execution", + "google.cloud.backupdr_v1.types.restore_verification_plan", + "google.cloud.backupdr_v1.types.restore_verification_plan_association", } @@ -47,6 +56,35 @@ BackupDrProtectionSummaryAsyncClient, BackupDrProtectionSummaryClient, ) +from .types.appliedautoprotectionpolicy import ( + AppliedAutoProtectionPolicy, + ListAppliedAutoProtectionPoliciesRequest, + ListAppliedAutoProtectionPoliciesResponse, +) +from .types.autoprotectionpolicy import ( + AutoProtectionPolicy, + BackupPlanDetail, + BindingSummary, + CreateAutoProtectionPolicyRequest, + Criteria, + DeleteAutoProtectionPolicyRequest, + GetAutoProtectionPolicyRequest, + KeyValuePair, + ListAutoProtectionPoliciesRequest, + ListAutoProtectionPoliciesResponse, + MatchingCondition, + PolicyEvaluationSummary, + UpdateAutoProtectionPolicyRequest, +) +from .types.autoprotectionpolicybinding import ( + AutoProtectionPolicyBinding, + BindingEvaluationSummary, + CreateAutoProtectionPolicyBindingRequest, + GetAutoProtectionPolicyBindingRequest, + InitiateDeleteAutoProtectionPolicyBindingRequest, + ListAutoProtectionPolicyBindingsRequest, + ListAutoProtectionPolicyBindingsResponse, +) from .types.backupdr import ( CreateManagementServerRequest, DeleteManagementServerRequest, @@ -131,6 +169,7 @@ UpdateBackupRequest, UpdateBackupVaultRequest, UpdateDataSourceRequest, + VerificationSummary, ) from .types.backupvault_alloydb import ( AlloyDBClusterBackupPlanAssociationProperties, @@ -178,6 +217,12 @@ ServiceAccount, Tags, ) +from .types.bindingmatchingresource import ( + AutoProtectionDetails, + BindingMatchingResource, + ListBindingMatchingResourcesRequest, + ListBindingMatchingResourcesResponse, +) from .types.datasourcereference import ( DataSourceBackupConfigInfo, DataSourceGcpResourceInfo, @@ -199,6 +244,58 @@ PitrSettings, ResourceBackupConfig, ) +from .types.restore_template import ( + CreateRestoreTemplateRequest, + DeleteRestoreTemplateRequest, + ExecutionSummary, + GetRestoreTemplateRequest, + ListRestoreTemplatesRequest, + ListRestoreTemplatesResponse, + RestoreTemplate, + RunRestoreTemplateRequest, + RunRestoreTemplateResponse, + UpdateRestoreTemplateRequest, +) +from .types.restore_template_common import ( + BackupSelectionConfig, + PostRestoreConfig, + PreRestoreConfig, + VerificationConfig, +) +from .types.restore_template_execution import ( + CleanupPhaseInfo, + GetRestoreTemplateExecutionRequest, + ListRestoreTemplateExecutionsRequest, + ListRestoreTemplateExecutionsResponse, + PhaseState, + PostRestorePhaseInfo, + PreparePhaseInfo, + PreRestorePhaseInfo, + RestorePhaseInfo, + RestoreTemplateExecution, + TriggerRestoreCleanupRequest, + VerificationPhaseInfo, +) +from .types.restore_verification_plan import ( + CreateRestoreVerificationPlanRequest, + DeleteRestoreVerificationPlanRequest, + GetRestoreVerificationPlanRequest, + ListRestoreVerificationPlansRequest, + ListRestoreVerificationPlansResponse, + RestoreVerificationCleanupRule, + RestoreVerificationPlan, +) +from .types.restore_verification_plan_association import ( + CreateRestoreVerificationPlanAssociationRequest, + DeleteRestoreVerificationPlanAssociationRequest, + GetRestoreVerificationPlanAssociationRequest, + ListRestoreVerificationPlanAssociationsRequest, + ListRestoreVerificationPlanAssociationsResponse, + RestoreVerificationPlanAssociation, + TriggerRestoreVerificationRequest, + TriggerRestoreVerificationResponse, + TriggerSummary, +) __all__ = ( "BackupDRAsyncClient", @@ -211,7 +308,11 @@ "AlloyDBClusterBackupPlanAssociationProperties", "AlloyDBClusterDataSourceProperties", "AlloyDbClusterBackupProperties", + "AppliedAutoProtectionPolicy", "AttachedDisk", + "AutoProtectionDetails", + "AutoProtectionPolicy", + "AutoProtectionPolicyBinding", "Backup", "BackupApplianceBackupConfig", "BackupApplianceBackupProperties", @@ -229,12 +330,18 @@ "BackupLock", "BackupPlan", "BackupPlanAssociation", + "BackupPlanDetail", "BackupPlanRevision", "BackupRule", + "BackupSelectionConfig", "BackupVault", "BackupVaultView", "BackupView", "BackupWindow", + "BindingEvaluationSummary", + "BindingMatchingResource", + "BindingSummary", + "CleanupPhaseInfo", "CloudSqlInstanceBackupPlanAssociationProperties", "CloudSqlInstanceBackupProperties", "CloudSqlInstanceDataSourceProperties", @@ -245,10 +352,16 @@ "ComputeInstanceRestoreProperties", "ComputeInstanceTargetEnvironment", "ConfidentialInstanceConfig", + "CreateAutoProtectionPolicyBindingRequest", + "CreateAutoProtectionPolicyRequest", "CreateBackupPlanAssociationRequest", "CreateBackupPlanRequest", "CreateBackupVaultRequest", "CreateManagementServerRequest", + "CreateRestoreTemplateRequest", + "CreateRestoreVerificationPlanAssociationRequest", + "CreateRestoreVerificationPlanRequest", + "Criteria", "CustomerEncryptionKey", "DataSource", "DataSourceBackupApplianceApplication", @@ -256,17 +369,22 @@ "DataSourceGcpResource", "DataSourceGcpResourceInfo", "DataSourceReference", + "DeleteAutoProtectionPolicyRequest", "DeleteBackupPlanAssociationRequest", "DeleteBackupPlanRequest", "DeleteBackupRequest", "DeleteBackupVaultRequest", "DeleteManagementServerRequest", + "DeleteRestoreTemplateRequest", + "DeleteRestoreVerificationPlanAssociationRequest", + "DeleteRestoreVerificationPlanRequest", "DiskBackupProperties", "DiskDataSourceProperties", "DiskRestoreProperties", "DiskTargetEnvironment", "DisplayDevice", "Entry", + "ExecutionSummary", "FetchBackupPlanAssociationsForResourceTypeRequest", "FetchBackupPlanAssociationsForResourceTypeResponse", "FetchBackupsForResourceTypeRequest", @@ -277,6 +395,8 @@ "FetchUsableBackupVaultsResponse", "GcpBackupConfig", "GcpResource", + "GetAutoProtectionPolicyBindingRequest", + "GetAutoProtectionPolicyRequest", "GetBackupPlanAssociationRequest", "GetBackupPlanRequest", "GetBackupPlanRevisionRequest", @@ -285,11 +405,23 @@ "GetDataSourceReferenceRequest", "GetDataSourceRequest", "GetManagementServerRequest", + "GetRestoreTemplateExecutionRequest", + "GetRestoreTemplateRequest", + "GetRestoreVerificationPlanAssociationRequest", + "GetRestoreVerificationPlanRequest", "GuestOsFeature", "InitializeServiceRequest", "InitializeServiceResponse", + "InitiateDeleteAutoProtectionPolicyBindingRequest", "InstanceParams", "KeyRevocationActionType", + "KeyValuePair", + "ListAppliedAutoProtectionPoliciesRequest", + "ListAppliedAutoProtectionPoliciesResponse", + "ListAutoProtectionPoliciesRequest", + "ListAutoProtectionPoliciesResponse", + "ListAutoProtectionPolicyBindingsRequest", + "ListAutoProtectionPolicyBindingsResponse", "ListBackupPlanAssociationsRequest", "ListBackupPlanAssociationsResponse", "ListBackupPlanRevisionsRequest", @@ -300,6 +432,8 @@ "ListBackupVaultsResponse", "ListBackupsRequest", "ListBackupsResponse", + "ListBindingMatchingResourcesRequest", + "ListBindingMatchingResourcesResponse", "ListDataSourceReferencesRequest", "ListDataSourceReferencesResponse", "ListDataSourcesRequest", @@ -308,19 +442,43 @@ "ListManagementServersResponse", "ListResourceBackupConfigsRequest", "ListResourceBackupConfigsResponse", + "ListRestoreTemplateExecutionsRequest", + "ListRestoreTemplateExecutionsResponse", + "ListRestoreTemplatesRequest", + "ListRestoreTemplatesResponse", + "ListRestoreVerificationPlanAssociationsRequest", + "ListRestoreVerificationPlanAssociationsResponse", + "ListRestoreVerificationPlansRequest", + "ListRestoreVerificationPlansResponse", "ManagementServer", "ManagementURI", + "MatchingCondition", "Metadata", "NetworkConfig", "NetworkInterface", "NetworkPerformanceConfig", "OperationMetadata", + "PhaseState", "PitrSettings", + "PolicyEvaluationSummary", + "PostRestoreConfig", + "PostRestorePhaseInfo", + "PreRestoreConfig", + "PreRestorePhaseInfo", + "PreparePhaseInfo", "RegionDiskTargetEnvironment", "ResourceBackupConfig", "RestoreBackupRequest", "RestoreBackupResponse", + "RestorePhaseInfo", + "RestoreTemplate", + "RestoreTemplateExecution", + "RestoreVerificationCleanupRule", + "RestoreVerificationPlan", + "RestoreVerificationPlanAssociation", "RuleConfigInfo", + "RunRestoreTemplateRequest", + "RunRestoreTemplateResponse", "Scheduling", "SchedulingDuration", "ServiceAccount", @@ -329,11 +487,20 @@ "Tags", "TargetResource", "TriggerBackupRequest", + "TriggerRestoreCleanupRequest", + "TriggerRestoreVerificationRequest", + "TriggerRestoreVerificationResponse", + "TriggerSummary", + "UpdateAutoProtectionPolicyRequest", "UpdateBackupPlanAssociationRequest", "UpdateBackupPlanRequest", "UpdateBackupRequest", "UpdateBackupVaultRequest", "UpdateDataSourceRequest", + "UpdateRestoreTemplateRequest", + "VerificationConfig", + "VerificationPhaseInfo", + "VerificationSummary", "WeekDayOfMonth", "WorkforceIdentityBasedManagementURI", "WorkforceIdentityBasedOAuth2ClientID", diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_metadata.json b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_metadata.json index 83a163f22b26..8f5987261b26 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_metadata.json +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/gapic_metadata.json @@ -10,6 +10,16 @@ "grpc": { "libraryClient": "BackupDRClient", "rpcs": { + "CreateAutoProtectionPolicy": { + "methods": [ + "create_auto_protection_policy" + ] + }, + "CreateAutoProtectionPolicyBinding": { + "methods": [ + "create_auto_protection_policy_binding" + ] + }, "CreateBackupPlan": { "methods": [ "create_backup_plan" @@ -30,6 +40,26 @@ "create_management_server" ] }, + "CreateRestoreTemplate": { + "methods": [ + "create_restore_template" + ] + }, + "CreateRestoreVerificationPlan": { + "methods": [ + "create_restore_verification_plan" + ] + }, + "CreateRestoreVerificationPlanAssociation": { + "methods": [ + "create_restore_verification_plan_association" + ] + }, + "DeleteAutoProtectionPolicy": { + "methods": [ + "delete_auto_protection_policy" + ] + }, "DeleteBackup": { "methods": [ "delete_backup" @@ -55,6 +85,21 @@ "delete_management_server" ] }, + "DeleteRestoreTemplate": { + "methods": [ + "delete_restore_template" + ] + }, + "DeleteRestoreVerificationPlan": { + "methods": [ + "delete_restore_verification_plan" + ] + }, + "DeleteRestoreVerificationPlanAssociation": { + "methods": [ + "delete_restore_verification_plan_association" + ] + }, "FetchBackupPlanAssociationsForResourceType": { "methods": [ "fetch_backup_plan_associations_for_resource_type" @@ -75,6 +120,16 @@ "fetch_usable_backup_vaults" ] }, + "GetAutoProtectionPolicy": { + "methods": [ + "get_auto_protection_policy" + ] + }, + "GetAutoProtectionPolicyBinding": { + "methods": [ + "get_auto_protection_policy_binding" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -115,11 +170,51 @@ "get_management_server" ] }, + "GetRestoreTemplate": { + "methods": [ + "get_restore_template" + ] + }, + "GetRestoreTemplateExecution": { + "methods": [ + "get_restore_template_execution" + ] + }, + "GetRestoreVerificationPlan": { + "methods": [ + "get_restore_verification_plan" + ] + }, + "GetRestoreVerificationPlanAssociation": { + "methods": [ + "get_restore_verification_plan_association" + ] + }, "InitializeService": { "methods": [ "initialize_service" ] }, + "InitiateDeleteAutoProtectionPolicyBinding": { + "methods": [ + "initiate_delete_auto_protection_policy_binding" + ] + }, + "ListAppliedAutoProtectionPolicies": { + "methods": [ + "list_applied_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicies": { + "methods": [ + "list_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicyBindings": { + "methods": [ + "list_auto_protection_policy_bindings" + ] + }, "ListBackupPlanAssociations": { "methods": [ "list_backup_plan_associations" @@ -145,6 +240,11 @@ "list_backups" ] }, + "ListBindingMatchingResources": { + "methods": [ + "list_binding_matching_resources" + ] + }, "ListDataSourceReferences": { "methods": [ "list_data_source_references" @@ -160,16 +260,56 @@ "list_management_servers" ] }, + "ListRestoreTemplateExecutions": { + "methods": [ + "list_restore_template_executions" + ] + }, + "ListRestoreTemplates": { + "methods": [ + "list_restore_templates" + ] + }, + "ListRestoreVerificationPlanAssociations": { + "methods": [ + "list_restore_verification_plan_associations" + ] + }, + "ListRestoreVerificationPlans": { + "methods": [ + "list_restore_verification_plans" + ] + }, "RestoreBackup": { "methods": [ "restore_backup" ] }, + "RunRestoreTemplate": { + "methods": [ + "run_restore_template" + ] + }, "TriggerBackup": { "methods": [ "trigger_backup" ] }, + "TriggerRestoreCleanup": { + "methods": [ + "trigger_restore_cleanup" + ] + }, + "TriggerRestoreVerification": { + "methods": [ + "trigger_restore_verification" + ] + }, + "UpdateAutoProtectionPolicy": { + "methods": [ + "update_auto_protection_policy" + ] + }, "UpdateBackup": { "methods": [ "update_backup" @@ -194,12 +334,27 @@ "methods": [ "update_data_source" ] + }, + "UpdateRestoreTemplate": { + "methods": [ + "update_restore_template" + ] } } }, "grpc-async": { "libraryClient": "BackupDRAsyncClient", "rpcs": { + "CreateAutoProtectionPolicy": { + "methods": [ + "create_auto_protection_policy" + ] + }, + "CreateAutoProtectionPolicyBinding": { + "methods": [ + "create_auto_protection_policy_binding" + ] + }, "CreateBackupPlan": { "methods": [ "create_backup_plan" @@ -220,6 +375,26 @@ "create_management_server" ] }, + "CreateRestoreTemplate": { + "methods": [ + "create_restore_template" + ] + }, + "CreateRestoreVerificationPlan": { + "methods": [ + "create_restore_verification_plan" + ] + }, + "CreateRestoreVerificationPlanAssociation": { + "methods": [ + "create_restore_verification_plan_association" + ] + }, + "DeleteAutoProtectionPolicy": { + "methods": [ + "delete_auto_protection_policy" + ] + }, "DeleteBackup": { "methods": [ "delete_backup" @@ -245,6 +420,21 @@ "delete_management_server" ] }, + "DeleteRestoreTemplate": { + "methods": [ + "delete_restore_template" + ] + }, + "DeleteRestoreVerificationPlan": { + "methods": [ + "delete_restore_verification_plan" + ] + }, + "DeleteRestoreVerificationPlanAssociation": { + "methods": [ + "delete_restore_verification_plan_association" + ] + }, "FetchBackupPlanAssociationsForResourceType": { "methods": [ "fetch_backup_plan_associations_for_resource_type" @@ -265,6 +455,16 @@ "fetch_usable_backup_vaults" ] }, + "GetAutoProtectionPolicy": { + "methods": [ + "get_auto_protection_policy" + ] + }, + "GetAutoProtectionPolicyBinding": { + "methods": [ + "get_auto_protection_policy_binding" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -305,11 +505,51 @@ "get_management_server" ] }, + "GetRestoreTemplate": { + "methods": [ + "get_restore_template" + ] + }, + "GetRestoreTemplateExecution": { + "methods": [ + "get_restore_template_execution" + ] + }, + "GetRestoreVerificationPlan": { + "methods": [ + "get_restore_verification_plan" + ] + }, + "GetRestoreVerificationPlanAssociation": { + "methods": [ + "get_restore_verification_plan_association" + ] + }, "InitializeService": { "methods": [ "initialize_service" ] }, + "InitiateDeleteAutoProtectionPolicyBinding": { + "methods": [ + "initiate_delete_auto_protection_policy_binding" + ] + }, + "ListAppliedAutoProtectionPolicies": { + "methods": [ + "list_applied_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicies": { + "methods": [ + "list_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicyBindings": { + "methods": [ + "list_auto_protection_policy_bindings" + ] + }, "ListBackupPlanAssociations": { "methods": [ "list_backup_plan_associations" @@ -335,6 +575,11 @@ "list_backups" ] }, + "ListBindingMatchingResources": { + "methods": [ + "list_binding_matching_resources" + ] + }, "ListDataSourceReferences": { "methods": [ "list_data_source_references" @@ -350,16 +595,56 @@ "list_management_servers" ] }, + "ListRestoreTemplateExecutions": { + "methods": [ + "list_restore_template_executions" + ] + }, + "ListRestoreTemplates": { + "methods": [ + "list_restore_templates" + ] + }, + "ListRestoreVerificationPlanAssociations": { + "methods": [ + "list_restore_verification_plan_associations" + ] + }, + "ListRestoreVerificationPlans": { + "methods": [ + "list_restore_verification_plans" + ] + }, "RestoreBackup": { "methods": [ "restore_backup" ] }, + "RunRestoreTemplate": { + "methods": [ + "run_restore_template" + ] + }, "TriggerBackup": { "methods": [ "trigger_backup" ] }, + "TriggerRestoreCleanup": { + "methods": [ + "trigger_restore_cleanup" + ] + }, + "TriggerRestoreVerification": { + "methods": [ + "trigger_restore_verification" + ] + }, + "UpdateAutoProtectionPolicy": { + "methods": [ + "update_auto_protection_policy" + ] + }, "UpdateBackup": { "methods": [ "update_backup" @@ -384,12 +669,27 @@ "methods": [ "update_data_source" ] + }, + "UpdateRestoreTemplate": { + "methods": [ + "update_restore_template" + ] } } }, "rest": { "libraryClient": "BackupDRClient", "rpcs": { + "CreateAutoProtectionPolicy": { + "methods": [ + "create_auto_protection_policy" + ] + }, + "CreateAutoProtectionPolicyBinding": { + "methods": [ + "create_auto_protection_policy_binding" + ] + }, "CreateBackupPlan": { "methods": [ "create_backup_plan" @@ -410,6 +710,26 @@ "create_management_server" ] }, + "CreateRestoreTemplate": { + "methods": [ + "create_restore_template" + ] + }, + "CreateRestoreVerificationPlan": { + "methods": [ + "create_restore_verification_plan" + ] + }, + "CreateRestoreVerificationPlanAssociation": { + "methods": [ + "create_restore_verification_plan_association" + ] + }, + "DeleteAutoProtectionPolicy": { + "methods": [ + "delete_auto_protection_policy" + ] + }, "DeleteBackup": { "methods": [ "delete_backup" @@ -435,6 +755,21 @@ "delete_management_server" ] }, + "DeleteRestoreTemplate": { + "methods": [ + "delete_restore_template" + ] + }, + "DeleteRestoreVerificationPlan": { + "methods": [ + "delete_restore_verification_plan" + ] + }, + "DeleteRestoreVerificationPlanAssociation": { + "methods": [ + "delete_restore_verification_plan_association" + ] + }, "FetchBackupPlanAssociationsForResourceType": { "methods": [ "fetch_backup_plan_associations_for_resource_type" @@ -455,6 +790,16 @@ "fetch_usable_backup_vaults" ] }, + "GetAutoProtectionPolicy": { + "methods": [ + "get_auto_protection_policy" + ] + }, + "GetAutoProtectionPolicyBinding": { + "methods": [ + "get_auto_protection_policy_binding" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -495,11 +840,51 @@ "get_management_server" ] }, + "GetRestoreTemplate": { + "methods": [ + "get_restore_template" + ] + }, + "GetRestoreTemplateExecution": { + "methods": [ + "get_restore_template_execution" + ] + }, + "GetRestoreVerificationPlan": { + "methods": [ + "get_restore_verification_plan" + ] + }, + "GetRestoreVerificationPlanAssociation": { + "methods": [ + "get_restore_verification_plan_association" + ] + }, "InitializeService": { "methods": [ "initialize_service" ] }, + "InitiateDeleteAutoProtectionPolicyBinding": { + "methods": [ + "initiate_delete_auto_protection_policy_binding" + ] + }, + "ListAppliedAutoProtectionPolicies": { + "methods": [ + "list_applied_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicies": { + "methods": [ + "list_auto_protection_policies" + ] + }, + "ListAutoProtectionPolicyBindings": { + "methods": [ + "list_auto_protection_policy_bindings" + ] + }, "ListBackupPlanAssociations": { "methods": [ "list_backup_plan_associations" @@ -525,6 +910,11 @@ "list_backups" ] }, + "ListBindingMatchingResources": { + "methods": [ + "list_binding_matching_resources" + ] + }, "ListDataSourceReferences": { "methods": [ "list_data_source_references" @@ -540,16 +930,56 @@ "list_management_servers" ] }, + "ListRestoreTemplateExecutions": { + "methods": [ + "list_restore_template_executions" + ] + }, + "ListRestoreTemplates": { + "methods": [ + "list_restore_templates" + ] + }, + "ListRestoreVerificationPlanAssociations": { + "methods": [ + "list_restore_verification_plan_associations" + ] + }, + "ListRestoreVerificationPlans": { + "methods": [ + "list_restore_verification_plans" + ] + }, "RestoreBackup": { "methods": [ "restore_backup" ] }, + "RunRestoreTemplate": { + "methods": [ + "run_restore_template" + ] + }, "TriggerBackup": { "methods": [ "trigger_backup" ] }, + "TriggerRestoreCleanup": { + "methods": [ + "trigger_restore_cleanup" + ] + }, + "TriggerRestoreVerification": { + "methods": [ + "trigger_restore_verification" + ] + }, + "UpdateAutoProtectionPolicy": { + "methods": [ + "update_auto_protection_policy" + ] + }, "UpdateBackup": { "methods": [ "update_backup" @@ -574,6 +1004,11 @@ "methods": [ "update_data_source" ] + }, + "UpdateRestoreTemplate": { + "methods": [ + "update_restore_template" + ] } } } diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/async_client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/async_client.py index 15be56d4a57e..fe47234dc474 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/async_client.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/async_client.py @@ -49,6 +49,7 @@ 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.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -60,6 +61,9 @@ from google.cloud.backupdr_v1.services.backup_dr import pagers from google.cloud.backupdr_v1.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, backupdr, backupplan, backupplanassociation, @@ -69,7 +73,20 @@ backupvault_cloudsql, backupvault_disk, backupvault_gce, + bindingmatchingresource, datasourcereference, + restore_template, + restore_template_common, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .client import BackupDRClient @@ -98,6 +115,24 @@ class BackupDRAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = BackupDRClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = BackupDRClient._DEFAULT_UNIVERSE + applied_auto_protection_policy_path = staticmethod( + BackupDRClient.applied_auto_protection_policy_path + ) + parse_applied_auto_protection_policy_path = staticmethod( + BackupDRClient.parse_applied_auto_protection_policy_path + ) + auto_protection_policy_path = staticmethod( + BackupDRClient.auto_protection_policy_path + ) + parse_auto_protection_policy_path = staticmethod( + BackupDRClient.parse_auto_protection_policy_path + ) + auto_protection_policy_binding_path = staticmethod( + BackupDRClient.auto_protection_policy_binding_path + ) + parse_auto_protection_policy_binding_path = staticmethod( + BackupDRClient.parse_auto_protection_policy_binding_path + ) backup_path = staticmethod(BackupDRClient.backup_path) parse_backup_path = staticmethod(BackupDRClient.parse_backup_path) backup_plan_path = staticmethod(BackupDRClient.backup_plan_path) @@ -114,6 +149,12 @@ class BackupDRAsyncClient: ) backup_vault_path = staticmethod(BackupDRClient.backup_vault_path) parse_backup_vault_path = staticmethod(BackupDRClient.parse_backup_vault_path) + binding_matching_resource_path = staticmethod( + BackupDRClient.binding_matching_resource_path + ) + parse_binding_matching_resource_path = staticmethod( + BackupDRClient.parse_binding_matching_resource_path + ) cluster_path = staticmethod(BackupDRClient.cluster_path) parse_cluster_path = staticmethod(BackupDRClient.parse_cluster_path) crypto_key_path = staticmethod(BackupDRClient.crypto_key_path) @@ -128,12 +169,38 @@ class BackupDRAsyncClient: parse_data_source_reference_path = staticmethod( BackupDRClient.parse_data_source_reference_path ) + execution_path = staticmethod(BackupDRClient.execution_path) + parse_execution_path = staticmethod(BackupDRClient.parse_execution_path) instance_path = staticmethod(BackupDRClient.instance_path) parse_instance_path = staticmethod(BackupDRClient.parse_instance_path) + job_path = staticmethod(BackupDRClient.job_path) + parse_job_path = staticmethod(BackupDRClient.parse_job_path) management_server_path = staticmethod(BackupDRClient.management_server_path) parse_management_server_path = staticmethod( BackupDRClient.parse_management_server_path ) + restore_template_path = staticmethod(BackupDRClient.restore_template_path) + parse_restore_template_path = staticmethod( + BackupDRClient.parse_restore_template_path + ) + restore_template_execution_path = staticmethod( + BackupDRClient.restore_template_execution_path + ) + parse_restore_template_execution_path = staticmethod( + BackupDRClient.parse_restore_template_execution_path + ) + restore_verification_plan_path = staticmethod( + BackupDRClient.restore_verification_plan_path + ) + parse_restore_verification_plan_path = staticmethod( + BackupDRClient.parse_restore_verification_plan_path + ) + restore_verification_plan_association_path = staticmethod( + BackupDRClient.restore_verification_plan_association_path + ) + parse_restore_verification_plan_association_path = staticmethod( + BackupDRClient.parse_restore_verification_plan_association_path + ) storage_pool_path = staticmethod(BackupDRClient.storage_pool_path) parse_storage_pool_path = staticmethod(BackupDRClient.parse_storage_pool_path) common_billing_account_path = staticmethod( @@ -5264,6 +5331,4083 @@ async def sample_initialize_service(): # Done; return the response. return response + async def create_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.CreateAutoProtectionPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + auto_protection_policy: Optional[ + autoprotectionpolicy.AutoProtectionPolicy + ] = None, + auto_protection_policy_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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new AutoProtectionPolicy in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + async def sample_create_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = "key_value" + auto_protection_policy.criteria.matching_conditions.label_condition.values = ['values_value1', 'values_value2'] + + request = backupdr_v1.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = await client.create_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.CreateAutoProtectionPolicyRequest, dict]]): + The request object. Request message for creating an + AutoProtectionPolicy. + parent (:class:`str`): + Required. The parent resource where + this policy will be created. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy (:class:`google.cloud.backupdr_v1.types.AutoProtectionPolicy`): + Required. The AutoProtectionPolicy + resource to create. + + This corresponds to the ``auto_protection_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_id (:class:`str`): + Required. The ID to use for the + policy. This will become the final + component of the policy's resource name. + + This value must start with a lowercase + letter followed by up to 62 lowercase + letters, numbers, or hyphens, and cannot + end with a hyphen. + + This corresponds to the ``auto_protection_policy_id`` 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.backupdr_v1.types.AutoProtectionPolicy` An AutoprotectionPolicy is a policy resource designed to automate backup + management, moving from manual per-resource + protection to a bulk approach. The policy dynamically + discovers and applies a specified backup plan to all + eligible resources that match its defined scope and + criteria. + + """ + # 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, auto_protection_policy, auto_protection_policy_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, autoprotectionpolicy.CreateAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if auto_protection_policy is not None: + request.auto_protection_policy = auto_protection_policy + if auto_protection_policy_id is not None: + request.auto_protection_policy_id = auto_protection_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + autoprotectionpolicy.AutoProtectionPolicy, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_auto_protection_policies( + self, + request: Optional[ + Union[autoprotectionpolicy.ListAutoProtectionPoliciesRequest, 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.ListAutoProtectionPoliciesAsyncPager: + r"""Lists AutoProtectionPolicies for a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + async def sample_list_auto_protection_policies(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesRequest, dict]]): + The request object. Request message for + ListAutoProtectionPolicies. + parent (:class:`str`): + Required. The project and location + for which to retrieve the list of + policies. Format: + projects/{project}/locations/{location} + + 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.backupdr_v1.services.backup_dr.pagers.ListAutoProtectionPoliciesAsyncPager: + Response message for + ListAutoProtectionPolicies. + 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, autoprotectionpolicy.ListAutoProtectionPoliciesRequest + ): + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest(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_auto_protection_policies + ] + + # 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.ListAutoProtectionPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.GetAutoProtectionPolicyRequest, 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]]] = (), + ) -> autoprotectionpolicy.AutoProtectionPolicy: + r"""Gets details of a single AutoProtectionPolicy. + + .. 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 backupdr_v1 + + async def sample_get_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auto_protection_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.GetAutoProtectionPolicyRequest, dict]]): + The request object. Request message for getting an + AutoProtectionPolicy. + name (:class:`str`): + Required. The name of the policy to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + 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.backupdr_v1.types.AutoProtectionPolicy: + An AutoprotectionPolicy is a policy + resource designed to automate backup + management, moving from manual + per-resource protection to a bulk + approach. The policy dynamically + discovers and applies a specified backup + plan to all eligible resources that + match its defined scope and criteria. + + """ + # 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, autoprotectionpolicy.GetAutoProtectionPolicyRequest): + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest(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_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, dict] + ] = None, + *, + auto_protection_policy: Optional[ + autoprotectionpolicy.AutoProtectionPolicy + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates the parameters of a single + AutoProtectionPolicy. + + .. 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 backupdr_v1 + + async def sample_update_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = "key_value" + auto_protection_policy.criteria.matching_conditions.label_condition.values = ['values_value1', 'values_value2'] + + request = backupdr_v1.UpdateAutoProtectionPolicyRequest( + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = await client.update_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.UpdateAutoProtectionPolicyRequest, dict]]): + The request object. Request message for updating an + AutoProtectionPolicy. + auto_protection_policy (:class:`google.cloud.backupdr_v1.types.AutoProtectionPolicy`): + Required. The policy to update. + This corresponds to the ``auto_protection_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. Field mask is used to specify the fields to be + overwritten in the AutoProtectionPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` 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.backupdr_v1.types.AutoProtectionPolicy` An AutoprotectionPolicy is a policy resource designed to automate backup + management, moving from manual per-resource + protection to a bulk approach. The policy dynamically + discovers and applies a specified backup plan to all + eligible resources that match its defined scope and + criteria. + + """ + # 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 = [auto_protection_policy, update_mask] + 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, autoprotectionpolicy.UpdateAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if auto_protection_policy is not None: + request.auto_protection_policy = auto_protection_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("auto_protection_policy.name", request.auto_protection_policy.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, + autoprotectionpolicy.AutoProtectionPolicy, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, 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 single AutoProtectionPolicy. + + .. 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 backupdr_v1 + + async def sample_delete_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.DeleteAutoProtectionPolicyRequest, dict]]): + The request object. Request message for deleting an + AutoProtectionPolicy. + name (:class:`str`): + Required. The name of the policy to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + 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, autoprotectionpolicy.DeleteAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(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_auto_protection_policy + ] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + auto_protection_policy_binding: Optional[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding + ] = None, + auto_protection_policy_binding_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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new AutoProtectionPolicyBinding in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + async def sample_create_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy_binding = backupdr_v1.AutoProtectionPolicyBinding() + auto_protection_policy_binding.scope = "scope_value" + + request = backupdr_v1.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + auto_protection_policy_binding=auto_protection_policy_binding, + ) + + # Make the request + operation = await client.create_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.CreateAutoProtectionPolicyBindingRequest, dict]]): + The request object. Request message for creating an + AutoProtectionPolicyBinding. + parent (:class:`str`): + Required. The parent resource where this binding will be + created. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_binding (:class:`google.cloud.backupdr_v1.types.AutoProtectionPolicyBinding`): + Required. The + AutoProtectionPolicyBinding resource to + create. + + This corresponds to the ``auto_protection_policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_binding_id (:class:`str`): + Required. The ID to use for the + binding. This will become the final + component of the binding's resource + name. + + This value must start with a lowercase + letter followed by up to 62 lowercase + letters, numbers, or hyphens, and cannot + end with a hyphen. + + This corresponds to the ``auto_protection_policy_binding_id`` 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.backupdr_v1.types.AutoProtectionPolicyBinding` An AutoProtectionPolicyBinding (APPA) acts as the bridge between an + AutoProtectionPolicy and the scope (Project) where + the policy should be applied. + + """ + # 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, + auto_protection_policy_binding, + auto_protection_policy_binding_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, + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + ): + request = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if auto_protection_policy_binding is not None: + request.auto_protection_policy_binding = auto_protection_policy_binding + if auto_protection_policy_binding_id is not None: + request.auto_protection_policy_binding_id = ( + auto_protection_policy_binding_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_auto_protection_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, 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]]] = (), + ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: + r"""Returns the auto protection policy binding read from + the CCFE tables. + + .. 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 backupdr_v1 + + async def sample_get_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auto_protection_policy_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.GetAutoProtectionPolicyBindingRequest, dict]]): + The request object. Request message for getting an + AutoProtectionPolicyBinding. + name (:class:`str`): + Required. The name of the binding to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + + 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.backupdr_v1.types.AutoProtectionPolicyBinding: + An AutoProtectionPolicyBinding (APPA) + acts as the bridge between an + AutoProtectionPolicy and the scope + (Project) where the policy should be + applied. + + """ + # 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, autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest + ): + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( + 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_auto_protection_policy_binding + ] + + # 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_auto_protection_policy_bindings( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + 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.ListAutoProtectionPolicyBindingsAsyncPager: + r"""Returns the auto protection policy bindings read from + the CCFE tables. + + .. 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 backupdr_v1 + + async def sample_list_auto_protection_policy_bindings(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsRequest, dict]]): + The request object. Request message for + ListAutoProtectionPolicyBindings. + parent (:class:`str`): + Required. The project and location + for which to retrieve the list of + policies. Format: + projects/{project}/locations/{location} + + 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.backupdr_v1.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsAsyncPager: + Response message for + ListAutoProtectionPolicyBindings. + 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, autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest + ): + request = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + 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_auto_protection_policy_bindings + ] + + # 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.ListAutoProtectionPolicyBindingsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_applied_auto_protection_policies( + self, + request: Optional[ + Union[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + 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.ListAppliedAutoProtectionPoliciesAsyncPager: + r"""Lists AppliedAutoProtectionPolicies in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + async def sample_list_applied_auto_protection_policies(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applied_auto_protection_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesRequest, dict]]): + The request object. Request message for listing + AppliedAutoProtectionPolicies. + parent (:class:`str`): + Required. The project and location + for which to retrieve the list of + applied policies. Format: + projects/{project}/locations/{location} + + 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.backupdr_v1.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesAsyncPager: + Response message for + ListAppliedAutoProtectionPolicies. + 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, + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + ): + request = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + 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_applied_auto_protection_policies + ] + + # 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.ListAppliedAutoProtectionPoliciesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def initiate_delete_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + 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"""InitiateDeleteAutoProtectionPolicyBinding initiates + delete for AutoProtectionPolicy Binding + + .. 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 backupdr_v1 + + async def sample_initiate_delete_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = await client.initiate_delete_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.InitiateDeleteAutoProtectionPolicyBindingRequest, dict]]): + The request object. Request message for initiating delete + of an AutoProtectionPolicyBinding. + name (:class:`str`): + Required. The name of the binding to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + + 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.backupdr_v1.types.AutoProtectionPolicyBinding` An AutoProtectionPolicyBinding (APPA) acts as the bridge between an + AutoProtectionPolicy and the scope (Project) where + the policy should be applied. + + """ + # 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, + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + ): + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( + 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.initiate_delete_auto_protection_policy_binding + ] + + # 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, + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_binding_matching_resources( + self, + request: Optional[ + Union[bindingmatchingresource.ListBindingMatchingResourcesRequest, 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.ListBindingMatchingResourcesAsyncPager: + r"""Lists Binding Matching Resources for a given + AutoProtectionPolicyBinding. + + .. 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 backupdr_v1 + + async def sample_list_binding_matching_resources(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListBindingMatchingResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_binding_matching_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.ListBindingMatchingResourcesRequest, dict]]): + The request object. Request message for List + BindingMatchingResources. + parent (:class:`str`): + Required. The project, location, auto protection policy + and binding for which to retrieve + ``BindingMatchingResources`` information. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}``. + In Google Cloud Backup and DR, locations map to Google + Cloud regions, for example **us-central1**. + + 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.backupdr_v1.services.backup_dr.pagers.ListBindingMatchingResourcesAsyncPager: + The response message for getting a list of + BindingMatchingResources. + + 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, bindingmatchingresource.ListBindingMatchingResourcesRequest + ): + request = bindingmatchingresource.ListBindingMatchingResourcesRequest( + 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_binding_matching_resources + ] + + # 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.ListBindingMatchingResourcesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_restore_template( + self, + request: Optional[ + Union[gcb_restore_template.CreateRestoreTemplateRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + restore_template: Optional[gcb_restore_template.RestoreTemplate] = None, + restore_template_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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new RestoreTemplate in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + async def sample_create_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_template = backupdr_v1.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + restore_template=restore_template, + ) + + # Make the request + operation = await client.create_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.CreateRestoreTemplateRequest, dict]]): + The request object. Request message for creating a + RestoreTemplate instance. + parent (:class:`str`): + Required. The restore template project and location in + the format 'projects/{project_id}/locations/{location}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_template (:class:`google.cloud.backupdr_v1.types.RestoreTemplate`): + Required. A RestoreTemplate resource. + This corresponds to the ``restore_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_template_id (:class:`str`): + Required. The ID of the restore + template to create. The ID must be + unique for the specified project and + location. + + This corresponds to the ``restore_template_id`` 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.backupdr_v1.types.RestoreTemplate` A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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, restore_template, restore_template_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, gcb_restore_template.CreateRestoreTemplateRequest): + request = gcb_restore_template.CreateRestoreTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_template is not None: + request.restore_template = restore_template + if restore_template_id is not None: + request.restore_template_id = restore_template_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_restore_template + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcb_restore_template.RestoreTemplate, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_restore_template( + self, + request: Optional[ + Union[restore_template.GetRestoreTemplateRequest, 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]]] = (), + ) -> restore_template.RestoreTemplate: + r"""Gets details of a RestoreTemplate. + + .. 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 backupdr_v1 + + async def sample_get_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_template(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.GetRestoreTemplateRequest, dict]]): + The request object. Request message for getting a + RestoreTemplate instance. + name (:class:`str`): + Required. The name of the restore template to retrieve. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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.backupdr_v1.types.RestoreTemplate: + A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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, restore_template.GetRestoreTemplateRequest): + request = restore_template.GetRestoreTemplateRequest(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_restore_template + ] + + # 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_restore_templates( + self, + request: Optional[ + Union[restore_template.ListRestoreTemplatesRequest, 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.ListRestoreTemplatesAsyncPager: + r"""Lists RestoreTemplates in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + async def sample_list_restore_templates(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreTemplatesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_templates(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.ListRestoreTemplatesRequest, dict]]): + The request object. Request message for listing + RestoreTemplates. + parent (:class:`str`): + Required. The project and location from which to list + the restore templates. Format: + ``projects/{project}/locations/{location}``. + + 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.backupdr_v1.services.backup_dr.pagers.ListRestoreTemplatesAsyncPager: + Response message for listing + RestoreTemplates. + 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, restore_template.ListRestoreTemplatesRequest): + request = restore_template.ListRestoreTemplatesRequest(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_restore_templates + ] + + # 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.ListRestoreTemplatesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_restore_template( + self, + request: Optional[ + Union[gcb_restore_template.UpdateRestoreTemplateRequest, dict] + ] = None, + *, + restore_template: Optional[gcb_restore_template.RestoreTemplate] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates the settings of a RestoreTemplate. + + .. 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 backupdr_v1 + + async def sample_update_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_template = backupdr_v1.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1.UpdateRestoreTemplateRequest( + restore_template=restore_template, + ) + + # Make the request + operation = await client.update_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.UpdateRestoreTemplateRequest, dict]]): + The request object. Request message for updating a + RestoreTemplate instance. + restore_template (:class:`google.cloud.backupdr_v1.types.RestoreTemplate`): + Required. The restore template to + update. + + This corresponds to the ``restore_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to update. Field mask is + used to specify the fields to be overwritten in the + RestoreTemplate resource by the update. The fields + specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. + + This corresponds to the ``update_mask`` 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.backupdr_v1.types.RestoreTemplate` A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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 = [restore_template, update_mask] + 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, gcb_restore_template.UpdateRestoreTemplateRequest): + request = gcb_restore_template.UpdateRestoreTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if restore_template is not None: + request.restore_template = restore_template + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_restore_template + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("restore_template.name", request.restore_template.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, + gcb_restore_template.RestoreTemplate, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_restore_template( + self, + request: Optional[ + Union[restore_template.DeleteRestoreTemplateRequest, 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 RestoreTemplate. + + .. 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 backupdr_v1 + + async def sample_delete_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.DeleteRestoreTemplateRequest, dict]]): + The request object. Request message for deleting a + RestoreTemplate instance. + name (:class:`str`): + Required. The name of the restore template to delete. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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, restore_template.DeleteRestoreTemplateRequest): + request = restore_template.DeleteRestoreTemplateRequest(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_restore_template + ] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def run_restore_template( + self, + request: Optional[ + Union[restore_template.RunRestoreTemplateRequest, 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"""Runs a RestoreTemplate. + + .. 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 backupdr_v1 + + async def sample_run_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.RunRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = await client.run_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.RunRestoreTemplateRequest, dict]]): + The request object. Request message for running a + RestoreTemplate. + name (:class:`str`): + Required. The name of the restore template to run. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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.cloud.backupdr_v1.types.RunRestoreTemplateResponse` + Response message for RunRestoreTemplate. + + """ + # 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, restore_template.RunRestoreTemplateRequest): + request = restore_template.RunRestoreTemplateRequest(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.run_restore_template + ] + + # 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, + restore_template.RunRestoreTemplateResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_restore_template_execution( + self, + request: Optional[ + Union[restore_template_execution.GetRestoreTemplateExecutionRequest, 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]]] = (), + ) -> restore_template_execution.RestoreTemplateExecution: + r"""Gets details of a RestoreTemplateExecution. + + .. 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 backupdr_v1 + + async def sample_get_restore_template_execution(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_template_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.GetRestoreTemplateExecutionRequest, dict]]): + The request object. Request message for getting a + RestoreTemplateExecution instance. + name (:class:`str`): + Required. The name of the restore template execution to + retrieve. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_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.backupdr_v1.types.RestoreTemplateExecution: + A RestoreTemplateExecution represents a single historical or active + execution run. + + """ + # 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, restore_template_execution.GetRestoreTemplateExecutionRequest + ): + request = restore_template_execution.GetRestoreTemplateExecutionRequest( + 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_restore_template_execution + ] + + # 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_restore_template_executions( + self, + request: Optional[ + Union[restore_template_execution.ListRestoreTemplateExecutionsRequest, 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.ListRestoreTemplateExecutionsAsyncPager: + r"""Lists RestoreTemplateExecutions in a given project, + location and restore template. + + .. 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 backupdr_v1 + + async def sample_list_restore_template_executions(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_template_executions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsRequest, dict]]): + The request object. Request message for listing + RestoreTemplateExecutions. + parent (:class:`str`): + Required. The project, location, and restore template + for which to retrieve executions information. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}``. + + 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.backupdr_v1.services.backup_dr.pagers.ListRestoreTemplateExecutionsAsyncPager: + Response message for listing + RestoreTemplateExecutions. + 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, restore_template_execution.ListRestoreTemplateExecutionsRequest + ): + request = restore_template_execution.ListRestoreTemplateExecutionsRequest( + 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_restore_template_executions + ] + + # 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.ListRestoreTemplateExecutionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def trigger_restore_cleanup( + self, + request: Optional[ + Union[restore_template_execution.TriggerRestoreCleanupRequest, 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"""Triggers cleanup of restored resources created during + execution. + + .. 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 backupdr_v1 + + async def sample_trigger_restore_cleanup(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.TriggerRestoreCleanupRequest( + name="name_value", + ) + + # Make the request + operation = await client.trigger_restore_cleanup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.TriggerRestoreCleanupRequest, dict]]): + The request object. Request message for triggering a + restore cleanup. + name (:class:`str`): + Required. Name of the restore template execution. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_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.cloud.backupdr_v1.types.RestoreTemplateExecution` A RestoreTemplateExecution represents a single historical or active + execution run. + + """ + # 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, restore_template_execution.TriggerRestoreCleanupRequest + ): + request = restore_template_execution.TriggerRestoreCleanupRequest(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.trigger_restore_cleanup + ] + + # 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, + restore_template_execution.RestoreTemplateExecution, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_restore_verification_plan( + self, + request: Optional[ + Union[ + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, dict + ] + ] = None, + *, + parent: Optional[str] = None, + restore_verification_plan: Optional[ + gcb_restore_verification_plan.RestoreVerificationPlan + ] = None, + restore_verification_plan_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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new RestoreVerificationPlan in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + async def sample_create_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_verification_plan = backupdr_v1.RestoreVerificationPlan() + restore_verification_plan.schedule = "schedule_value" + + request = backupdr_v1.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + restore_verification_plan=restore_verification_plan, + ) + + # Make the request + operation = await client.create_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.CreateRestoreVerificationPlanRequest, dict]]): + The request object. The request message for creating a + ``RestoreVerificationPlan``. + parent (:class:`str`): + Required. The ``RestoreVerificationPlan`` project and + location in the format + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR locations map to Google Cloud + regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan (:class:`google.cloud.backupdr_v1.types.RestoreVerificationPlan`): + Required. The ``RestoreVerificationPlan`` resource + object to create. + + This corresponds to the ``restore_verification_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_id (:class:`str`): + Required. The name of the ``RestoreVerificationPlan`` to + create. The name must be unique for the specified + project and location. The name must start with a + lowercase letter followed by up to 62 lowercase letters, + numbers, or hyphens. Pattern, + ``^[a-z]([-a-z0-9]*[a-z0-9])?$``. + + This corresponds to the ``restore_verification_plan_id`` 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.backupdr_v1.types.RestoreVerificationPlan` A RestoreVerificationPlan specifies the scheduling and clean-up template + for automated restore verification. It contains a + schedule to dictate when the verifications should + run, and a RestoreVerificationCleanupRule for + post-verification resource deletion. + + """ + # 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, + restore_verification_plan, + restore_verification_plan_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, gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest + ): + request = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_verification_plan is not None: + request.restore_verification_plan = restore_verification_plan + if restore_verification_plan_id is not None: + request.restore_verification_plan_id = restore_verification_plan_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_restore_verification_plan + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcb_restore_verification_plan.RestoreVerificationPlan, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_restore_verification_plan_association( + self, + request: Optional[ + Union[ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + restore_verification_plan_association: Optional[ + gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation + ] = None, + restore_verification_plan_association_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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new RestoreVerificationPlanAssociation in a + given RestoreVerificationPlan. + + .. 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 backupdr_v1 + + async def sample_create_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_verification_plan_association = backupdr_v1.RestoreVerificationPlanAssociation() + restore_verification_plan_association.restore_template = "restore_template_value" + restore_verification_plan_association.resource_type = "resource_type_value" + + request = backupdr_v1.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + restore_verification_plan_association=restore_verification_plan_association, + ) + + # Make the request + operation = await client.create_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.CreateRestoreVerificationPlanAssociationRequest, dict]]): + The request object. Request message for + CreateRestoreVerificationPlanAssociation. + parent (:class:`str`): + Required. The parent resource where this association + will be created. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_association (:class:`google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation`): + Required. The + RestoreVerificationPlanAssociation + resource to create. + + This corresponds to the ``restore_verification_plan_association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_association_id (:class:`str`): + Required. The ID to use for the association, which will + become the final component of the association's resource + name. + + This value should be 1-63 characters, and valid + characters are /[a-z0-9\_-]/. + + This corresponds to the ``restore_verification_plan_association_id`` 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.backupdr_v1.types.RestoreVerificationPlanAssociation` A RestoreVerificationPlanAssociation binds a specific workload to a + RestoreVerificationPlan. + + """ + # 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, + restore_verification_plan_association, + restore_verification_plan_association_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, + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + ): + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_verification_plan_association is not None: + request.restore_verification_plan_association = ( + restore_verification_plan_association + ) + if restore_verification_plan_association_id is not None: + request.restore_verification_plan_association_id = ( + restore_verification_plan_association_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_restore_verification_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_restore_verification_plan_association( + self, + request: Optional[ + Union[ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + 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]]] = (), + ) -> restore_verification_plan_association.RestoreVerificationPlanAssociation: + r"""Gets details of a single + RestoreVerificationPlanAssociation in a given + RestoreVerificationPlan. + + .. 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 backupdr_v1 + + async def sample_get_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_verification_plan_association(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.GetRestoreVerificationPlanAssociationRequest, dict]]): + The request object. Request message for + GetRestoreVerificationPlanAssociation. + name (:class:`str`): + Required. The resource name of the + RestoreVerificationPlanAssociation to retrieve. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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.backupdr_v1.types.RestoreVerificationPlanAssociation: + A RestoreVerificationPlanAssociation binds a specific workload to a + RestoreVerificationPlan. + + """ + # 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, + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + ): + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest( + 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_restore_verification_plan_association + ] + + # 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_restore_verification_plan_associations( + self, + request: Optional[ + Union[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + 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.ListRestoreVerificationPlanAssociationsAsyncPager: + r"""Lists RestoreVerificationPlanAssociations in a given + RestoreVerificationPlan. + + .. 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 backupdr_v1 + + async def sample_list_restore_verification_plan_associations(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plan_associations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsRequest, dict]]): + The request object. Request message for + ListRestoreVerificationPlanAssociations. + parent (:class:`str`): + Required. The parent RestoreVerificationPlan name. + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + + 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.backupdr_v1.services.backup_dr.pagers.ListRestoreVerificationPlanAssociationsAsyncPager: + Response message for + ListRestoreVerificationPlanAssociations. + 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, + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + ): + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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_restore_verification_plan_associations + ] + + # 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.ListRestoreVerificationPlanAssociationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_restore_verification_plan_association( + self, + request: Optional[ + Union[ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + 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 single RestoreVerificationPlanAssociation + in a given RestoreVerificationPlan. + + .. 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 backupdr_v1 + + async def sample_delete_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.DeleteRestoreVerificationPlanAssociationRequest, dict]]): + The request object. Request message for + DeleteRestoreVerificationPlanAssociation. + name (:class:`str`): + Required. The resource name of the + RestoreVerificationPlanAssociation to delete. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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, + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + ): + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest( + 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_restore_verification_plan_association + ] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def trigger_restore_verification( + self, + request: Optional[ + Union[ + restore_verification_plan_association.TriggerRestoreVerificationRequest, + 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"""Triggers a new Restore Verification for the + association in a given RestoreVerificationPlan. + + .. 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 backupdr_v1 + + async def sample_trigger_restore_verification(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.TriggerRestoreVerificationRequest( + name="name_value", + ) + + # Make the request + operation = await client.trigger_restore_verification(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.TriggerRestoreVerificationRequest, dict]]): + The request object. Request message for + TriggerRestoreVerification. + name (:class:`str`): + Required. The resource name of the + RestoreVerificationPlanAssociation to trigger. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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.backupdr_v1.types.TriggerRestoreVerificationResponse` + Response message for TriggerRestoreVerification. + + """ + # 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, + restore_verification_plan_association.TriggerRestoreVerificationRequest, + ): + request = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest( + 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.trigger_restore_verification + ] + + # 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, + restore_verification_plan_association.TriggerRestoreVerificationResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_restore_verification_plan( + self, + request: Optional[ + Union[restore_verification_plan.GetRestoreVerificationPlanRequest, 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]]] = (), + ) -> restore_verification_plan.RestoreVerificationPlan: + r"""Gets details of a single RestoreVerificationPlan. + Returns the requested RestoreVerificationPlan. + + .. 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 backupdr_v1 + + async def sample_get_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_verification_plan(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.GetRestoreVerificationPlanRequest, dict]]): + The request object. The request message for getting a + ``RestoreVerificationPlan``. + name (:class:`str`): + Required. The resource name of the + ``RestoreVerificationPlan`` to retrieve. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + + 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.backupdr_v1.types.RestoreVerificationPlan: + A RestoreVerificationPlan specifies the scheduling and clean-up template + for automated restore verification. It contains a + schedule to dictate when the verifications should + run, and a RestoreVerificationCleanupRule for + post-verification resource deletion. + + """ + # 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, restore_verification_plan.GetRestoreVerificationPlanRequest + ): + request = restore_verification_plan.GetRestoreVerificationPlanRequest( + 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_restore_verification_plan + ] + + # 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_restore_verification_plans( + self, + request: Optional[ + Union[restore_verification_plan.ListRestoreVerificationPlansRequest, 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.ListRestoreVerificationPlansAsyncPager: + r"""Lists RestoreVerificationPlans in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + async def sample_list_restore_verification_plans(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreVerificationPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plans(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.ListRestoreVerificationPlansRequest, dict]]): + The request object. The request message for getting a list of + ``RestoreVerificationPlans``. + parent (:class:`str`): + Required. The project and location for which to retrieve + ``RestoreVerificationPlans`` information. Format: + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + restore verification plans for all locations, use "-" + for the ``{location}`` value. + + 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.backupdr_v1.services.backup_dr.pagers.ListRestoreVerificationPlansAsyncPager: + The response message for getting a list of + RestoreVerificationPlans. + + 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, restore_verification_plan.ListRestoreVerificationPlansRequest + ): + request = restore_verification_plan.ListRestoreVerificationPlansRequest( + 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_restore_verification_plans + ] + + # 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.ListRestoreVerificationPlansAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_restore_verification_plan( + self, + request: Optional[ + Union[restore_verification_plan.DeleteRestoreVerificationPlanRequest, 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 single RestoreVerificationPlan. If the ``force`` flag + is set to ``true``, any RestoreVerificationPlanAssociations + linked to this RestoreVerificationPlan will also be deleted. + + .. 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 backupdr_v1 + + async def sample_delete_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1.types.DeleteRestoreVerificationPlanRequest, dict]]): + The request object. The request message for deleting a + ``RestoreVerificationPlan``. + name (:class:`str`): + Required. The resource name of the + ``RestoreVerificationPlan`` to delete. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + + 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, restore_verification_plan.DeleteRestoreVerificationPlanRequest + ): + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest( + 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_restore_verification_plan + ] + + # 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=backupdr.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-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py index aa8ffc47b120..b3437f903d6b 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/client.py @@ -73,6 +73,7 @@ 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.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -84,6 +85,9 @@ from google.cloud.backupdr_v1.services.backup_dr import pagers from google.cloud.backupdr_v1.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, backupdr, backupplan, backupplanassociation, @@ -93,7 +97,20 @@ backupvault_cloudsql, backupvault_disk, backupvault_gce, + bindingmatchingresource, datasourcereference, + restore_template, + restore_template_common, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .transports.base import DEFAULT_CLIENT_INFO, BackupDRTransport @@ -194,6 +211,74 @@ def transport(self) -> BackupDRTransport: """ return self._transport + @staticmethod + def applied_auto_protection_policy_path( + project: str, + location: str, + applied_auto_protection_policy: str, + ) -> str: + """Returns a fully-qualified applied_auto_protection_policy string.""" + return "projects/{project}/locations/{location}/appliedAutoProtectionPolicies/{applied_auto_protection_policy}".format( + project=project, + location=location, + applied_auto_protection_policy=applied_auto_protection_policy, + ) + + @staticmethod + def parse_applied_auto_protection_policy_path(path: str) -> Dict[str, str]: + """Parses a applied_auto_protection_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/appliedAutoProtectionPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def auto_protection_policy_path( + project: str, + location: str, + auto_protection_policy: str, + ) -> str: + """Returns a fully-qualified auto_protection_policy string.""" + return "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + ) + + @staticmethod + def parse_auto_protection_policy_path(path: str) -> Dict[str, str]: + """Parses a auto_protection_policy path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/autoProtectionPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def auto_protection_policy_binding_path( + project: str, + location: str, + auto_protection_policy: str, + binding: str, + ) -> str: + """Returns a fully-qualified auto_protection_policy_binding string.""" + return "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + binding=binding, + ) + + @staticmethod + def parse_auto_protection_policy_binding_path(path: str) -> Dict[str, str]: + """Parses a auto_protection_policy_binding path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/autoProtectionPolicies/(?P.+?)/bindings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def backup_path( project: str, @@ -314,6 +399,32 @@ def parse_backup_vault_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def binding_matching_resource_path( + project: str, + location: str, + auto_protection_policy: str, + binding: str, + matching_resource: str, + ) -> str: + """Returns a fully-qualified binding_matching_resource string.""" + return "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + binding=binding, + matching_resource=matching_resource, + ) + + @staticmethod + def parse_binding_matching_resource_path(path: str) -> Dict[str, str]: + """Parses a binding_matching_resource path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/autoProtectionPolicies/(?P.+?)/bindings/(?P.+?)/matchingResources/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def cluster_path( project: str, @@ -432,6 +543,30 @@ def parse_data_source_reference_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def execution_path( + project: str, + location: str, + job: str, + execution: str, + ) -> str: + """Returns a fully-qualified execution string.""" + return "projects/{project}/locations/{location}/jobs/{job}/executions/{execution}".format( + project=project, + location=location, + job=job, + execution=execution, + ) + + @staticmethod + def parse_execution_path(path: str) -> Dict[str, str]: + """Parses a execution path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)/executions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def instance_path( project: str, @@ -449,6 +584,28 @@ def parse_instance_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/instances/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def job_path( + project: str, + location: str, + job: str, + ) -> str: + """Returns a fully-qualified job string.""" + return "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, + location=location, + job=job, + ) + + @staticmethod + def parse_job_path(path: str) -> Dict[str, str]: + """Parses a job path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def management_server_path( project: str, @@ -471,6 +628,98 @@ def parse_management_server_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def restore_template_path( + project: str, + location: str, + restore_template: str, + ) -> str: + """Returns a fully-qualified restore_template string.""" + return "projects/{project}/locations/{location}/restoreTemplates/{restore_template}".format( + project=project, + location=location, + restore_template=restore_template, + ) + + @staticmethod + def parse_restore_template_path(path: str) -> Dict[str, str]: + """Parses a restore_template path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/restoreTemplates/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def restore_template_execution_path( + project: str, + location: str, + restore_template: str, + execution: str, + ) -> str: + """Returns a fully-qualified restore_template_execution string.""" + return "projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}".format( + project=project, + location=location, + restore_template=restore_template, + execution=execution, + ) + + @staticmethod + def parse_restore_template_execution_path(path: str) -> Dict[str, str]: + """Parses a restore_template_execution path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/restoreTemplates/(?P.+?)/executions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def restore_verification_plan_path( + project: str, + location: str, + restoreVerificationPlan: str, + ) -> str: + """Returns a fully-qualified restore_verification_plan string.""" + return "projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}".format( + project=project, + location=location, + restoreVerificationPlan=restoreVerificationPlan, + ) + + @staticmethod + def parse_restore_verification_plan_path(path: str) -> Dict[str, str]: + """Parses a restore_verification_plan path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/restoreVerificationPlans/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def restore_verification_plan_association_path( + project: str, + location: str, + restore_verification_plan: str, + association: str, + ) -> str: + """Returns a fully-qualified restore_verification_plan_association string.""" + return "projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}".format( + project=project, + location=location, + restore_verification_plan=restore_verification_plan, + association=association, + ) + + @staticmethod + def parse_restore_verification_plan_association_path(path: str) -> Dict[str, str]: + """Parses a restore_verification_plan_association path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/restoreVerificationPlans/(?P.+?)/associations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def storage_pool_path( project: str, @@ -5724,6 +5973,4040 @@ def sample_initialize_service(): # Done; return the response. return response + def create_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.CreateAutoProtectionPolicyRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + auto_protection_policy: Optional[ + autoprotectionpolicy.AutoProtectionPolicy + ] = None, + auto_protection_policy_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]]] = (), + ) -> operation.Operation: + r"""Creates a new AutoProtectionPolicy in a given project + and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + def sample_create_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = "key_value" + auto_protection_policy.criteria.matching_conditions.label_condition.values = ['values_value1', 'values_value2'] + + request = backupdr_v1.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = client.create_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.CreateAutoProtectionPolicyRequest, dict]): + The request object. Request message for creating an + AutoProtectionPolicy. + parent (str): + Required. The parent resource where + this policy will be created. Format: + projects/{project}/locations/{location} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy (google.cloud.backupdr_v1.types.AutoProtectionPolicy): + Required. The AutoProtectionPolicy + resource to create. + + This corresponds to the ``auto_protection_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_id (str): + Required. The ID to use for the + policy. This will become the final + component of the policy's resource name. + + This value must start with a lowercase + letter followed by up to 62 lowercase + letters, numbers, or hyphens, and cannot + end with a hyphen. + + This corresponds to the ``auto_protection_policy_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1.types.AutoProtectionPolicy` An AutoprotectionPolicy is a policy resource designed to automate backup + management, moving from manual per-resource + protection to a bulk approach. The policy dynamically + discovers and applies a specified backup plan to all + eligible resources that match its defined scope and + criteria. + + """ + # 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, auto_protection_policy, auto_protection_policy_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, autoprotectionpolicy.CreateAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if auto_protection_policy is not None: + request.auto_protection_policy = auto_protection_policy + if auto_protection_policy_id is not None: + request.auto_protection_policy_id = auto_protection_policy_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + autoprotectionpolicy.AutoProtectionPolicy, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_auto_protection_policies( + self, + request: Optional[ + Union[autoprotectionpolicy.ListAutoProtectionPoliciesRequest, 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.ListAutoProtectionPoliciesPager: + r"""Lists AutoProtectionPolicies for a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + def sample_list_auto_protection_policies(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesRequest, dict]): + The request object. Request message for + ListAutoProtectionPolicies. + parent (str): + Required. The project and location + for which to retrieve the list of + policies. Format: + projects/{project}/locations/{location} + + 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.backupdr_v1.services.backup_dr.pagers.ListAutoProtectionPoliciesPager: + Response message for + ListAutoProtectionPolicies. + 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, autoprotectionpolicy.ListAutoProtectionPoliciesRequest + ): + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest(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_auto_protection_policies + ] + + # 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.ListAutoProtectionPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.GetAutoProtectionPolicyRequest, 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]]] = (), + ) -> autoprotectionpolicy.AutoProtectionPolicy: + r"""Gets details of a single AutoProtectionPolicy. + + .. 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 backupdr_v1 + + def sample_get_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_auto_protection_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.GetAutoProtectionPolicyRequest, dict]): + The request object. Request message for getting an + AutoProtectionPolicy. + name (str): + Required. The name of the policy to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + 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.backupdr_v1.types.AutoProtectionPolicy: + An AutoprotectionPolicy is a policy + resource designed to automate backup + management, moving from manual + per-resource protection to a bulk + approach. The policy dynamically + discovers and applies a specified backup + plan to all eligible resources that + match its defined scope and criteria. + + """ + # 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, autoprotectionpolicy.GetAutoProtectionPolicyRequest): + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest(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_auto_protection_policy + ] + + # 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 update_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, dict] + ] = None, + *, + auto_protection_policy: Optional[ + autoprotectionpolicy.AutoProtectionPolicy + ] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates the parameters of a single + AutoProtectionPolicy. + + .. 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 backupdr_v1 + + def sample_update_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = "key_value" + auto_protection_policy.criteria.matching_conditions.label_condition.values = ['values_value1', 'values_value2'] + + request = backupdr_v1.UpdateAutoProtectionPolicyRequest( + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = client.update_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.UpdateAutoProtectionPolicyRequest, dict]): + The request object. Request message for updating an + AutoProtectionPolicy. + auto_protection_policy (google.cloud.backupdr_v1.types.AutoProtectionPolicy): + Required. The policy to update. + This corresponds to the ``auto_protection_policy`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the AutoProtectionPolicy resource by the + update. The fields specified in the update_mask are + relative to the resource, not the full request. A field + will be overwritten if it is in the mask. If the user + does not provide a mask then all fields will be + overwritten. + + This corresponds to the ``update_mask`` 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.backupdr_v1.types.AutoProtectionPolicy` An AutoprotectionPolicy is a policy resource designed to automate backup + management, moving from manual per-resource + protection to a bulk approach. The policy dynamically + discovers and applies a specified backup plan to all + eligible resources that match its defined scope and + criteria. + + """ + # 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 = [auto_protection_policy, update_mask] + 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, autoprotectionpolicy.UpdateAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if auto_protection_policy is not None: + request.auto_protection_policy = auto_protection_policy + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.update_auto_protection_policy + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("auto_protection_policy.name", request.auto_protection_policy.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, + autoprotectionpolicy.AutoProtectionPolicy, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_auto_protection_policy( + self, + request: Optional[ + Union[autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, 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 single AutoProtectionPolicy. + + .. 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 backupdr_v1 + + def sample_delete_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.DeleteAutoProtectionPolicyRequest, dict]): + The request object. Request message for deleting an + AutoProtectionPolicy. + name (str): + Required. The name of the policy to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + 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, autoprotectionpolicy.DeleteAutoProtectionPolicyRequest + ): + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(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_auto_protection_policy + ] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + auto_protection_policy_binding: Optional[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding + ] = None, + auto_protection_policy_binding_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]]] = (), + ) -> operation.Operation: + r"""Creates a new AutoProtectionPolicyBinding in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + def sample_create_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy_binding = backupdr_v1.AutoProtectionPolicyBinding() + auto_protection_policy_binding.scope = "scope_value" + + request = backupdr_v1.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + auto_protection_policy_binding=auto_protection_policy_binding, + ) + + # Make the request + operation = client.create_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.CreateAutoProtectionPolicyBindingRequest, dict]): + The request object. Request message for creating an + AutoProtectionPolicyBinding. + parent (str): + Required. The parent resource where this binding will be + created. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_binding (google.cloud.backupdr_v1.types.AutoProtectionPolicyBinding): + Required. The + AutoProtectionPolicyBinding resource to + create. + + This corresponds to the ``auto_protection_policy_binding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auto_protection_policy_binding_id (str): + Required. The ID to use for the + binding. This will become the final + component of the binding's resource + name. + + This value must start with a lowercase + letter followed by up to 62 lowercase + letters, numbers, or hyphens, and cannot + end with a hyphen. + + This corresponds to the ``auto_protection_policy_binding_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1.types.AutoProtectionPolicyBinding` An AutoProtectionPolicyBinding (APPA) acts as the bridge between an + AutoProtectionPolicy and the scope (Project) where + the policy should be applied. + + """ + # 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, + auto_protection_policy_binding, + auto_protection_policy_binding_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, + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + ): + request = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if auto_protection_policy_binding is not None: + request.auto_protection_policy_binding = auto_protection_policy_binding + if auto_protection_policy_binding_id is not None: + request.auto_protection_policy_binding_id = ( + auto_protection_policy_binding_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_auto_protection_policy_binding + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, 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]]] = (), + ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: + r"""Returns the auto protection policy binding read from + the CCFE tables. + + .. 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 backupdr_v1 + + def sample_get_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_auto_protection_policy_binding(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.GetAutoProtectionPolicyBindingRequest, dict]): + The request object. Request message for getting an + AutoProtectionPolicyBinding. + name (str): + Required. The name of the binding to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + + 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.backupdr_v1.types.AutoProtectionPolicyBinding: + An AutoProtectionPolicyBinding (APPA) + acts as the bridge between an + AutoProtectionPolicy and the scope + (Project) where the policy should be + applied. + + """ + # 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, autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest + ): + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( + 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_auto_protection_policy_binding + ] + + # 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_auto_protection_policy_bindings( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + 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.ListAutoProtectionPolicyBindingsPager: + r"""Returns the auto protection policy bindings read from + the CCFE tables. + + .. 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 backupdr_v1 + + def sample_list_auto_protection_policy_bindings(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsRequest, dict]): + The request object. Request message for + ListAutoProtectionPolicyBindings. + parent (str): + Required. The project and location + for which to retrieve the list of + policies. Format: + projects/{project}/locations/{location} + + 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.backupdr_v1.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsPager: + Response message for + ListAutoProtectionPolicyBindings. + 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, autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest + ): + request = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + 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_auto_protection_policy_bindings + ] + + # 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.ListAutoProtectionPolicyBindingsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_applied_auto_protection_policies( + self, + request: Optional[ + Union[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + 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.ListAppliedAutoProtectionPoliciesPager: + r"""Lists AppliedAutoProtectionPolicies in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + def sample_list_applied_auto_protection_policies(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applied_auto_protection_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesRequest, dict]): + The request object. Request message for listing + AppliedAutoProtectionPolicies. + parent (str): + Required. The project and location + for which to retrieve the list of + applied policies. Format: + projects/{project}/locations/{location} + + 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.backupdr_v1.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesPager: + Response message for + ListAppliedAutoProtectionPolicies. + 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, + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + ): + request = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + 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_applied_auto_protection_policies + ] + + # 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.ListAppliedAutoProtectionPoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def initiate_delete_auto_protection_policy_binding( + self, + request: Optional[ + Union[ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + 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"""InitiateDeleteAutoProtectionPolicyBinding initiates + delete for AutoProtectionPolicy Binding + + .. 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 backupdr_v1 + + def sample_initiate_delete_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.initiate_delete_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.InitiateDeleteAutoProtectionPolicyBindingRequest, dict]): + The request object. Request message for initiating delete + of an AutoProtectionPolicyBinding. + name (str): + Required. The name of the binding to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + + 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.backupdr_v1.types.AutoProtectionPolicyBinding` An AutoProtectionPolicyBinding (APPA) acts as the bridge between an + AutoProtectionPolicy and the scope (Project) where + the policy should be applied. + + """ + # 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, + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + ): + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( + 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.initiate_delete_auto_protection_policy_binding + ] + + # 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, + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_binding_matching_resources( + self, + request: Optional[ + Union[bindingmatchingresource.ListBindingMatchingResourcesRequest, 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.ListBindingMatchingResourcesPager: + r"""Lists Binding Matching Resources for a given + AutoProtectionPolicyBinding. + + .. 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 backupdr_v1 + + def sample_list_binding_matching_resources(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListBindingMatchingResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_binding_matching_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.ListBindingMatchingResourcesRequest, dict]): + The request object. Request message for List + BindingMatchingResources. + parent (str): + Required. The project, location, auto protection policy + and binding for which to retrieve + ``BindingMatchingResources`` information. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}``. + In Google Cloud Backup and DR, locations map to Google + Cloud regions, for example **us-central1**. + + 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.backupdr_v1.services.backup_dr.pagers.ListBindingMatchingResourcesPager: + The response message for getting a list of + BindingMatchingResources. + + 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, bindingmatchingresource.ListBindingMatchingResourcesRequest + ): + request = bindingmatchingresource.ListBindingMatchingResourcesRequest( + 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_binding_matching_resources + ] + + # 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.ListBindingMatchingResourcesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_restore_template( + self, + request: Optional[ + Union[gcb_restore_template.CreateRestoreTemplateRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + restore_template: Optional[gcb_restore_template.RestoreTemplate] = None, + restore_template_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]]] = (), + ) -> operation.Operation: + r"""Creates a new RestoreTemplate in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + def sample_create_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + restore_template = backupdr_v1.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + restore_template=restore_template, + ) + + # Make the request + operation = client.create_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.CreateRestoreTemplateRequest, dict]): + The request object. Request message for creating a + RestoreTemplate instance. + parent (str): + Required. The restore template project and location in + the format 'projects/{project_id}/locations/{location}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_template (google.cloud.backupdr_v1.types.RestoreTemplate): + Required. A RestoreTemplate resource. + This corresponds to the ``restore_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_template_id (str): + Required. The ID of the restore + template to create. The ID must be + unique for the specified project and + location. + + This corresponds to the ``restore_template_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1.types.RestoreTemplate` A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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, restore_template, restore_template_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, gcb_restore_template.CreateRestoreTemplateRequest): + request = gcb_restore_template.CreateRestoreTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_template is not None: + request.restore_template = restore_template + if restore_template_id is not None: + request.restore_template_id = restore_template_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_restore_template] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcb_restore_template.RestoreTemplate, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_restore_template( + self, + request: Optional[ + Union[restore_template.GetRestoreTemplateRequest, 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]]] = (), + ) -> restore_template.RestoreTemplate: + r"""Gets details of a RestoreTemplate. + + .. 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 backupdr_v1 + + def sample_get_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_template(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.GetRestoreTemplateRequest, dict]): + The request object. Request message for getting a + RestoreTemplate instance. + name (str): + Required. The name of the restore template to retrieve. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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.backupdr_v1.types.RestoreTemplate: + A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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, restore_template.GetRestoreTemplateRequest): + request = restore_template.GetRestoreTemplateRequest(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_restore_template] + + # 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_restore_templates( + self, + request: Optional[ + Union[restore_template.ListRestoreTemplatesRequest, 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.ListRestoreTemplatesPager: + r"""Lists RestoreTemplates in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + def sample_list_restore_templates(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreTemplatesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_templates(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.ListRestoreTemplatesRequest, dict]): + The request object. Request message for listing + RestoreTemplates. + parent (str): + Required. The project and location from which to list + the restore templates. Format: + ``projects/{project}/locations/{location}``. + + 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.backupdr_v1.services.backup_dr.pagers.ListRestoreTemplatesPager: + Response message for listing + RestoreTemplates. + 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, restore_template.ListRestoreTemplatesRequest): + request = restore_template.ListRestoreTemplatesRequest(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_restore_templates] + + # 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.ListRestoreTemplatesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_restore_template( + self, + request: Optional[ + Union[gcb_restore_template.UpdateRestoreTemplateRequest, dict] + ] = None, + *, + restore_template: Optional[gcb_restore_template.RestoreTemplate] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates the settings of a RestoreTemplate. + + .. 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 backupdr_v1 + + def sample_update_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + restore_template = backupdr_v1.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1.UpdateRestoreTemplateRequest( + restore_template=restore_template, + ) + + # Make the request + operation = client.update_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.UpdateRestoreTemplateRequest, dict]): + The request object. Request message for updating a + RestoreTemplate instance. + restore_template (google.cloud.backupdr_v1.types.RestoreTemplate): + Required. The restore template to + update. + + This corresponds to the ``restore_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. Field mask is + used to specify the fields to be overwritten in the + RestoreTemplate resource by the update. The fields + specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. + + This corresponds to the ``update_mask`` 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.backupdr_v1.types.RestoreTemplate` A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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 = [restore_template, update_mask] + 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, gcb_restore_template.UpdateRestoreTemplateRequest): + request = gcb_restore_template.UpdateRestoreTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if restore_template is not None: + request.restore_template = restore_template + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_restore_template] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("restore_template.name", request.restore_template.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, + gcb_restore_template.RestoreTemplate, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_restore_template( + self, + request: Optional[ + Union[restore_template.DeleteRestoreTemplateRequest, 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 RestoreTemplate. + + .. 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 backupdr_v1 + + def sample_delete_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.DeleteRestoreTemplateRequest, dict]): + The request object. Request message for deleting a + RestoreTemplate instance. + name (str): + Required. The name of the restore template to delete. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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, restore_template.DeleteRestoreTemplateRequest): + request = restore_template.DeleteRestoreTemplateRequest(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_restore_template] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def run_restore_template( + self, + request: Optional[ + Union[restore_template.RunRestoreTemplateRequest, 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"""Runs a RestoreTemplate. + + .. 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 backupdr_v1 + + def sample_run_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.RunRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = client.run_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.RunRestoreTemplateRequest, dict]): + The request object. Request message for running a + RestoreTemplate. + name (str): + Required. The name of the restore template to run. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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.cloud.backupdr_v1.types.RunRestoreTemplateResponse` + Response message for RunRestoreTemplate. + + """ + # 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, restore_template.RunRestoreTemplateRequest): + request = restore_template.RunRestoreTemplateRequest(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.run_restore_template] + + # 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, + restore_template.RunRestoreTemplateResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_restore_template_execution( + self, + request: Optional[ + Union[restore_template_execution.GetRestoreTemplateExecutionRequest, 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]]] = (), + ) -> restore_template_execution.RestoreTemplateExecution: + r"""Gets details of a RestoreTemplateExecution. + + .. 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 backupdr_v1 + + def sample_get_restore_template_execution(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_template_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.GetRestoreTemplateExecutionRequest, dict]): + The request object. Request message for getting a + RestoreTemplateExecution instance. + name (str): + Required. The name of the restore template execution to + retrieve. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_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.backupdr_v1.types.RestoreTemplateExecution: + A RestoreTemplateExecution represents a single historical or active + execution run. + + """ + # 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, restore_template_execution.GetRestoreTemplateExecutionRequest + ): + request = restore_template_execution.GetRestoreTemplateExecutionRequest( + 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_restore_template_execution + ] + + # 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_restore_template_executions( + self, + request: Optional[ + Union[restore_template_execution.ListRestoreTemplateExecutionsRequest, 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.ListRestoreTemplateExecutionsPager: + r"""Lists RestoreTemplateExecutions in a given project, + location and restore template. + + .. 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 backupdr_v1 + + def sample_list_restore_template_executions(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_template_executions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsRequest, dict]): + The request object. Request message for listing + RestoreTemplateExecutions. + parent (str): + Required. The project, location, and restore template + for which to retrieve executions information. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}``. + + 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.backupdr_v1.services.backup_dr.pagers.ListRestoreTemplateExecutionsPager: + Response message for listing + RestoreTemplateExecutions. + 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, restore_template_execution.ListRestoreTemplateExecutionsRequest + ): + request = restore_template_execution.ListRestoreTemplateExecutionsRequest( + 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_restore_template_executions + ] + + # 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.ListRestoreTemplateExecutionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def trigger_restore_cleanup( + self, + request: Optional[ + Union[restore_template_execution.TriggerRestoreCleanupRequest, 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"""Triggers cleanup of restored resources created during + execution. + + .. 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 backupdr_v1 + + def sample_trigger_restore_cleanup(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.TriggerRestoreCleanupRequest( + name="name_value", + ) + + # Make the request + operation = client.trigger_restore_cleanup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.TriggerRestoreCleanupRequest, dict]): + The request object. Request message for triggering a + restore cleanup. + name (str): + Required. Name of the restore template execution. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_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.cloud.backupdr_v1.types.RestoreTemplateExecution` A RestoreTemplateExecution represents a single historical or active + execution run. + + """ + # 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, restore_template_execution.TriggerRestoreCleanupRequest + ): + request = restore_template_execution.TriggerRestoreCleanupRequest(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.trigger_restore_cleanup] + + # 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, + restore_template_execution.RestoreTemplateExecution, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_restore_verification_plan( + self, + request: Optional[ + Union[ + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, dict + ] + ] = None, + *, + parent: Optional[str] = None, + restore_verification_plan: Optional[ + gcb_restore_verification_plan.RestoreVerificationPlan + ] = None, + restore_verification_plan_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]]] = (), + ) -> operation.Operation: + r"""Creates a new RestoreVerificationPlan in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + def sample_create_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + restore_verification_plan = backupdr_v1.RestoreVerificationPlan() + restore_verification_plan.schedule = "schedule_value" + + request = backupdr_v1.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + restore_verification_plan=restore_verification_plan, + ) + + # Make the request + operation = client.create_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.CreateRestoreVerificationPlanRequest, dict]): + The request object. The request message for creating a + ``RestoreVerificationPlan``. + parent (str): + Required. The ``RestoreVerificationPlan`` project and + location in the format + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR locations map to Google Cloud + regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan (google.cloud.backupdr_v1.types.RestoreVerificationPlan): + Required. The ``RestoreVerificationPlan`` resource + object to create. + + This corresponds to the ``restore_verification_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_id (str): + Required. The name of the ``RestoreVerificationPlan`` to + create. The name must be unique for the specified + project and location. The name must start with a + lowercase letter followed by up to 62 lowercase letters, + numbers, or hyphens. Pattern, + ``^[a-z]([-a-z0-9]*[a-z0-9])?$``. + + This corresponds to the ``restore_verification_plan_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1.types.RestoreVerificationPlan` A RestoreVerificationPlan specifies the scheduling and clean-up template + for automated restore verification. It contains a + schedule to dictate when the verifications should + run, and a RestoreVerificationCleanupRule for + post-verification resource deletion. + + """ + # 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, + restore_verification_plan, + restore_verification_plan_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, gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest + ): + request = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_verification_plan is not None: + request.restore_verification_plan = restore_verification_plan + if restore_verification_plan_id is not None: + request.restore_verification_plan_id = restore_verification_plan_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_restore_verification_plan + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcb_restore_verification_plan.RestoreVerificationPlan, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_restore_verification_plan_association( + self, + request: Optional[ + Union[ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + restore_verification_plan_association: Optional[ + gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation + ] = None, + restore_verification_plan_association_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]]] = (), + ) -> operation.Operation: + r"""Creates a new RestoreVerificationPlanAssociation in a + given RestoreVerificationPlan. + + .. 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 backupdr_v1 + + def sample_create_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + restore_verification_plan_association = backupdr_v1.RestoreVerificationPlanAssociation() + restore_verification_plan_association.restore_template = "restore_template_value" + restore_verification_plan_association.resource_type = "resource_type_value" + + request = backupdr_v1.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + restore_verification_plan_association=restore_verification_plan_association, + ) + + # Make the request + operation = client.create_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.CreateRestoreVerificationPlanAssociationRequest, dict]): + The request object. Request message for + CreateRestoreVerificationPlanAssociation. + parent (str): + Required. The parent resource where this association + will be created. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_association (google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation): + Required. The + RestoreVerificationPlanAssociation + resource to create. + + This corresponds to the ``restore_verification_plan_association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_association_id (str): + Required. The ID to use for the association, which will + become the final component of the association's resource + name. + + This value should be 1-63 characters, and valid + characters are /[a-z0-9\_-]/. + + This corresponds to the ``restore_verification_plan_association_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation` A RestoreVerificationPlanAssociation binds a specific workload to a + RestoreVerificationPlan. + + """ + # 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, + restore_verification_plan_association, + restore_verification_plan_association_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, + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + ): + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_verification_plan_association is not None: + request.restore_verification_plan_association = ( + restore_verification_plan_association + ) + if restore_verification_plan_association_id is not None: + request.restore_verification_plan_association_id = ( + restore_verification_plan_association_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_restore_verification_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_restore_verification_plan_association( + self, + request: Optional[ + Union[ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + 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]]] = (), + ) -> restore_verification_plan_association.RestoreVerificationPlanAssociation: + r"""Gets details of a single + RestoreVerificationPlanAssociation in a given + RestoreVerificationPlan. + + .. 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 backupdr_v1 + + def sample_get_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_verification_plan_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.GetRestoreVerificationPlanAssociationRequest, dict]): + The request object. Request message for + GetRestoreVerificationPlanAssociation. + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to retrieve. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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.backupdr_v1.types.RestoreVerificationPlanAssociation: + A RestoreVerificationPlanAssociation binds a specific workload to a + RestoreVerificationPlan. + + """ + # 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, + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + ): + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest( + 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_restore_verification_plan_association + ] + + # 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_restore_verification_plan_associations( + self, + request: Optional[ + Union[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + 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.ListRestoreVerificationPlanAssociationsPager: + r"""Lists RestoreVerificationPlanAssociations in a given + RestoreVerificationPlan. + + .. 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 backupdr_v1 + + def sample_list_restore_verification_plan_associations(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plan_associations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsRequest, dict]): + The request object. Request message for + ListRestoreVerificationPlanAssociations. + parent (str): + Required. The parent RestoreVerificationPlan name. + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + + 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.backupdr_v1.services.backup_dr.pagers.ListRestoreVerificationPlanAssociationsPager: + Response message for + ListRestoreVerificationPlanAssociations. + 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, + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + ): + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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_restore_verification_plan_associations + ] + + # 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.ListRestoreVerificationPlanAssociationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_restore_verification_plan_association( + self, + request: Optional[ + Union[ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + 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 single RestoreVerificationPlanAssociation + in a given RestoreVerificationPlan. + + .. 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 backupdr_v1 + + def sample_delete_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.DeleteRestoreVerificationPlanAssociationRequest, dict]): + The request object. Request message for + DeleteRestoreVerificationPlanAssociation. + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to delete. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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, + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + ): + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest( + 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_restore_verification_plan_association + ] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def trigger_restore_verification( + self, + request: Optional[ + Union[ + restore_verification_plan_association.TriggerRestoreVerificationRequest, + 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"""Triggers a new Restore Verification for the + association in a given RestoreVerificationPlan. + + .. 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 backupdr_v1 + + def sample_trigger_restore_verification(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.TriggerRestoreVerificationRequest( + name="name_value", + ) + + # Make the request + operation = client.trigger_restore_verification(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.TriggerRestoreVerificationRequest, dict]): + The request object. Request message for + TriggerRestoreVerification. + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to trigger. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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.backupdr_v1.types.TriggerRestoreVerificationResponse` + Response message for TriggerRestoreVerification. + + """ + # 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, + restore_verification_plan_association.TriggerRestoreVerificationRequest, + ): + request = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest( + 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.trigger_restore_verification + ] + + # 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, + restore_verification_plan_association.TriggerRestoreVerificationResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_restore_verification_plan( + self, + request: Optional[ + Union[restore_verification_plan.GetRestoreVerificationPlanRequest, 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]]] = (), + ) -> restore_verification_plan.RestoreVerificationPlan: + r"""Gets details of a single RestoreVerificationPlan. + Returns the requested RestoreVerificationPlan. + + .. 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 backupdr_v1 + + def sample_get_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_verification_plan(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.GetRestoreVerificationPlanRequest, dict]): + The request object. The request message for getting a + ``RestoreVerificationPlan``. + name (str): + Required. The resource name of the + ``RestoreVerificationPlan`` to retrieve. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + + 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.backupdr_v1.types.RestoreVerificationPlan: + A RestoreVerificationPlan specifies the scheduling and clean-up template + for automated restore verification. It contains a + schedule to dictate when the verifications should + run, and a RestoreVerificationCleanupRule for + post-verification resource deletion. + + """ + # 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, restore_verification_plan.GetRestoreVerificationPlanRequest + ): + request = restore_verification_plan.GetRestoreVerificationPlanRequest( + 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_restore_verification_plan + ] + + # 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_restore_verification_plans( + self, + request: Optional[ + Union[restore_verification_plan.ListRestoreVerificationPlansRequest, 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.ListRestoreVerificationPlansPager: + r"""Lists RestoreVerificationPlans in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1 + + def sample_list_restore_verification_plans(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreVerificationPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plans(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.ListRestoreVerificationPlansRequest, dict]): + The request object. The request message for getting a list of + ``RestoreVerificationPlans``. + parent (str): + Required. The project and location for which to retrieve + ``RestoreVerificationPlans`` information. Format: + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + restore verification plans for all locations, use "-" + for the ``{location}`` value. + + 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.backupdr_v1.services.backup_dr.pagers.ListRestoreVerificationPlansPager: + The response message for getting a list of + RestoreVerificationPlans. + + 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, restore_verification_plan.ListRestoreVerificationPlansRequest + ): + request = restore_verification_plan.ListRestoreVerificationPlansRequest( + 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_restore_verification_plans + ] + + # 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.ListRestoreVerificationPlansPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_restore_verification_plan( + self, + request: Optional[ + Union[restore_verification_plan.DeleteRestoreVerificationPlanRequest, 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 single RestoreVerificationPlan. If the ``force`` flag + is set to ``true``, any RestoreVerificationPlanAssociations + linked to this RestoreVerificationPlan will also be deleted. + + .. 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 backupdr_v1 + + def sample_delete_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1.types.DeleteRestoreVerificationPlanRequest, dict]): + The request object. The request message for deleting a + ``RestoreVerificationPlan``. + name (str): + Required. The resource name of the + ``RestoreVerificationPlan`` to delete. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + + 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, restore_verification_plan.DeleteRestoreVerificationPlanRequest + ): + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest( + 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_restore_verification_plan + ] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "BackupDRClient": return self diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/pagers.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/pagers.py index 7ba8ebd8a80d..51569a4c187e 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/pagers.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/pagers.py @@ -39,11 +39,19 @@ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore from google.cloud.backupdr_v1.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, backupdr, backupplan, backupplanassociation, backupvault, + bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, ) @@ -1972,3 +1980,1381 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAutoProtectionPoliciesPager: + """A pager for iterating through ``list_auto_protection_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``auto_protection_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAutoProtectionPolicies`` requests and continue to iterate + through the ``auto_protection_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesResponse` + 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[..., autoprotectionpolicy.ListAutoProtectionPoliciesResponse], + request: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + response: autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + *, + 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.backupdr_v1.types.ListAutoProtectionPoliciesRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesResponse): + 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest(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[autoprotectionpolicy.ListAutoProtectionPoliciesResponse]: + 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[autoprotectionpolicy.AutoProtectionPolicy]: + for page in self.pages: + yield from page.auto_protection_policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAutoProtectionPoliciesAsyncPager: + """A pager for iterating through ``list_auto_protection_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``auto_protection_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAutoProtectionPolicies`` requests and continue to iterate + through the ``auto_protection_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesResponse` + 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[autoprotectionpolicy.ListAutoProtectionPoliciesResponse] + ], + request: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + response: autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + *, + 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.backupdr_v1.types.ListAutoProtectionPoliciesRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesResponse): + 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest(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[autoprotectionpolicy.ListAutoProtectionPoliciesResponse]: + 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[autoprotectionpolicy.AutoProtectionPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.auto_protection_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAutoProtectionPolicyBindingsPager: + """A pager for iterating through ``list_auto_protection_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``auto_protection_policy_bindings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAutoProtectionPolicyBindings`` requests and continue to iterate + through the ``auto_protection_policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsResponse` + 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[ + ..., autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse + ], + request: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + response: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + *, + 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.backupdr_v1.types.ListAutoProtectionPolicyBindingsRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsResponse): + 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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(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[autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse]: + 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[autoprotectionpolicybinding.AutoProtectionPolicyBinding]: + for page in self.pages: + yield from page.auto_protection_policy_bindings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAutoProtectionPolicyBindingsAsyncPager: + """A pager for iterating through ``list_auto_protection_policy_bindings`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``auto_protection_policy_bindings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAutoProtectionPolicyBindings`` requests and continue to iterate + through the ``auto_protection_policy_bindings`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsResponse` + 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[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse + ], + ], + request: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + response: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + *, + 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.backupdr_v1.types.ListAutoProtectionPolicyBindingsRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsResponse): + 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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(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[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse + ]: + 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[autoprotectionpolicybinding.AutoProtectionPolicyBinding]: + async def async_generator(): + async for page in self.pages: + for response in page.auto_protection_policy_bindings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAppliedAutoProtectionPoliciesPager: + """A pager for iterating through ``list_applied_auto_protection_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``applied_auto_protection_policies`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAppliedAutoProtectionPolicies`` requests and continue to iterate + through the ``applied_auto_protection_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesResponse` + 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[ + ..., appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ], + request: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + response: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + *, + 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.backupdr_v1.types.ListAppliedAutoProtectionPoliciesRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesResponse): + 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + 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[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ]: + 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[appliedautoprotectionpolicy.AppliedAutoProtectionPolicy]: + for page in self.pages: + yield from page.applied_auto_protection_policies + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAppliedAutoProtectionPoliciesAsyncPager: + """A pager for iterating through ``list_applied_auto_protection_policies`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``applied_auto_protection_policies`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAppliedAutoProtectionPolicies`` requests and continue to iterate + through the ``applied_auto_protection_policies`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesResponse` + 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[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ], + ], + request: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + response: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + *, + 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.backupdr_v1.types.ListAppliedAutoProtectionPoliciesRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesResponse): + 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + 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[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ]: + 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[appliedautoprotectionpolicy.AppliedAutoProtectionPolicy]: + async def async_generator(): + async for page in self.pages: + for response in page.applied_auto_protection_policies: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBindingMatchingResourcesPager: + """A pager for iterating through ``list_binding_matching_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListBindingMatchingResourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``matching_resources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBindingMatchingResources`` requests and continue to iterate + through the ``matching_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListBindingMatchingResourcesResponse` + 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[ + ..., bindingmatchingresource.ListBindingMatchingResourcesResponse + ], + request: bindingmatchingresource.ListBindingMatchingResourcesRequest, + response: bindingmatchingresource.ListBindingMatchingResourcesResponse, + *, + 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.backupdr_v1.types.ListBindingMatchingResourcesRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListBindingMatchingResourcesResponse): + 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest( + 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[bindingmatchingresource.ListBindingMatchingResourcesResponse]: + 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[bindingmatchingresource.BindingMatchingResource]: + for page in self.pages: + yield from page.matching_resources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBindingMatchingResourcesAsyncPager: + """A pager for iterating through ``list_binding_matching_resources`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListBindingMatchingResourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``matching_resources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBindingMatchingResources`` requests and continue to iterate + through the ``matching_resources`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListBindingMatchingResourcesResponse` + 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[bindingmatchingresource.ListBindingMatchingResourcesResponse] + ], + request: bindingmatchingresource.ListBindingMatchingResourcesRequest, + response: bindingmatchingresource.ListBindingMatchingResourcesResponse, + *, + 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.backupdr_v1.types.ListBindingMatchingResourcesRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListBindingMatchingResourcesResponse): + 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest( + 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[bindingmatchingresource.ListBindingMatchingResourcesResponse]: + 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[bindingmatchingresource.BindingMatchingResource]: + async def async_generator(): + async for page in self.pages: + for response in page.matching_resources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreTemplatesPager: + """A pager for iterating through ``list_restore_templates`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListRestoreTemplatesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``restore_templates`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRestoreTemplates`` requests and continue to iterate + through the ``restore_templates`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListRestoreTemplatesResponse` + 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[..., restore_template.ListRestoreTemplatesResponse], + request: restore_template.ListRestoreTemplatesRequest, + response: restore_template.ListRestoreTemplatesResponse, + *, + 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.backupdr_v1.types.ListRestoreTemplatesRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListRestoreTemplatesResponse): + 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 = restore_template.ListRestoreTemplatesRequest(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[restore_template.ListRestoreTemplatesResponse]: + 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[restore_template.RestoreTemplate]: + for page in self.pages: + yield from page.restore_templates + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreTemplatesAsyncPager: + """A pager for iterating through ``list_restore_templates`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListRestoreTemplatesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``restore_templates`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRestoreTemplates`` requests and continue to iterate + through the ``restore_templates`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListRestoreTemplatesResponse` + 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[restore_template.ListRestoreTemplatesResponse]], + request: restore_template.ListRestoreTemplatesRequest, + response: restore_template.ListRestoreTemplatesResponse, + *, + 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.backupdr_v1.types.ListRestoreTemplatesRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListRestoreTemplatesResponse): + 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 = restore_template.ListRestoreTemplatesRequest(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[restore_template.ListRestoreTemplatesResponse]: + 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[restore_template.RestoreTemplate]: + async def async_generator(): + async for page in self.pages: + for response in page.restore_templates: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreTemplateExecutionsPager: + """A pager for iterating through ``list_restore_template_executions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``restore_template_executions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRestoreTemplateExecutions`` requests and continue to iterate + through the ``restore_template_executions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsResponse` + 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[ + ..., restore_template_execution.ListRestoreTemplateExecutionsResponse + ], + request: restore_template_execution.ListRestoreTemplateExecutionsRequest, + response: restore_template_execution.ListRestoreTemplateExecutionsResponse, + *, + 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.backupdr_v1.types.ListRestoreTemplateExecutionsRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsResponse): + 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest( + 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[restore_template_execution.ListRestoreTemplateExecutionsResponse]: + 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[restore_template_execution.RestoreTemplateExecution]: + for page in self.pages: + yield from page.restore_template_executions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreTemplateExecutionsAsyncPager: + """A pager for iterating through ``list_restore_template_executions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``restore_template_executions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRestoreTemplateExecutions`` requests and continue to iterate + through the ``restore_template_executions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsResponse` + 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[restore_template_execution.ListRestoreTemplateExecutionsResponse], + ], + request: restore_template_execution.ListRestoreTemplateExecutionsRequest, + response: restore_template_execution.ListRestoreTemplateExecutionsResponse, + *, + 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.backupdr_v1.types.ListRestoreTemplateExecutionsRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsResponse): + 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest( + 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[ + restore_template_execution.ListRestoreTemplateExecutionsResponse + ]: + 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[restore_template_execution.RestoreTemplateExecution]: + async def async_generator(): + async for page in self.pages: + for response in page.restore_template_executions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreVerificationPlanAssociationsPager: + """A pager for iterating through ``list_restore_verification_plan_associations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``restore_verification_plan_associations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRestoreVerificationPlanAssociations`` requests and continue to iterate + through the ``restore_verification_plan_associations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsResponse` + 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[ + ..., + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + ], + request: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + response: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + *, + 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.backupdr_v1.types.ListRestoreVerificationPlanAssociationsRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsResponse): + 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ]: + 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[ + restore_verification_plan_association.RestoreVerificationPlanAssociation + ]: + for page in self.pages: + yield from page.restore_verification_plan_associations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreVerificationPlanAssociationsAsyncPager: + """A pager for iterating through ``list_restore_verification_plan_associations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``restore_verification_plan_associations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRestoreVerificationPlanAssociations`` requests and continue to iterate + through the ``restore_verification_plan_associations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsResponse` + 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[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ], + ], + request: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + response: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + *, + 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.backupdr_v1.types.ListRestoreVerificationPlanAssociationsRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsResponse): + 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ]: + 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[ + restore_verification_plan_association.RestoreVerificationPlanAssociation + ]: + async def async_generator(): + async for page in self.pages: + for response in page.restore_verification_plan_associations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreVerificationPlansPager: + """A pager for iterating through ``list_restore_verification_plans`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListRestoreVerificationPlansResponse` object, and + provides an ``__iter__`` method to iterate through its + ``restore_verification_plans`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRestoreVerificationPlans`` requests and continue to iterate + through the ``restore_verification_plans`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListRestoreVerificationPlansResponse` + 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[ + ..., restore_verification_plan.ListRestoreVerificationPlansResponse + ], + request: restore_verification_plan.ListRestoreVerificationPlansRequest, + response: restore_verification_plan.ListRestoreVerificationPlansResponse, + *, + 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.backupdr_v1.types.ListRestoreVerificationPlansRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListRestoreVerificationPlansResponse): + 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 = restore_verification_plan.ListRestoreVerificationPlansRequest( + 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[restore_verification_plan.ListRestoreVerificationPlansResponse]: + 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[restore_verification_plan.RestoreVerificationPlan]: + for page in self.pages: + yield from page.restore_verification_plans + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreVerificationPlansAsyncPager: + """A pager for iterating through ``list_restore_verification_plans`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1.types.ListRestoreVerificationPlansResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``restore_verification_plans`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRestoreVerificationPlans`` requests and continue to iterate + through the ``restore_verification_plans`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1.types.ListRestoreVerificationPlansResponse` + 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[restore_verification_plan.ListRestoreVerificationPlansResponse], + ], + request: restore_verification_plan.ListRestoreVerificationPlansRequest, + response: restore_verification_plan.ListRestoreVerificationPlansResponse, + *, + 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.backupdr_v1.types.ListRestoreVerificationPlansRequest): + The initial request object. + response (google.cloud.backupdr_v1.types.ListRestoreVerificationPlansResponse): + 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 = restore_verification_plan.ListRestoreVerificationPlansRequest( + 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[restore_verification_plan.ListRestoreVerificationPlansResponse]: + 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[restore_verification_plan.RestoreVerificationPlan]: + async def async_generator(): + async for page in self.pages: + for response in page.restore_verification_plans: + 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-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/base.py index 6e53ec353615..2eb8fbff0249 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/base.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/base.py @@ -33,11 +33,26 @@ from google.cloud.backupdr_v1 import gapic_version as package_version from google.cloud.backupdr_v1.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, backupdr, backupplan, backupplanassociation, backupvault, + bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -445,6 +460,277 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.create_auto_protection_policy: gapic_v1.method.wrap_method( + self.create_auto_protection_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.list_auto_protection_policies: gapic_v1.method.wrap_method( + self.list_auto_protection_policies, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_auto_protection_policy: gapic_v1.method.wrap_method( + self.get_auto_protection_policy, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_auto_protection_policy: gapic_v1.method.wrap_method( + self.update_auto_protection_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_auto_protection_policy: gapic_v1.method.wrap_method( + self.delete_auto_protection_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.create_auto_protection_policy_binding: gapic_v1.method.wrap_method( + self.create_auto_protection_policy_binding, + default_timeout=60.0, + client_info=client_info, + ), + self.get_auto_protection_policy_binding: gapic_v1.method.wrap_method( + self.get_auto_protection_policy_binding, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_auto_protection_policy_bindings: gapic_v1.method.wrap_method( + self.list_auto_protection_policy_bindings, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_applied_auto_protection_policies: gapic_v1.method.wrap_method( + self.list_applied_auto_protection_policies, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.initiate_delete_auto_protection_policy_binding: gapic_v1.method.wrap_method( + self.initiate_delete_auto_protection_policy_binding, + default_timeout=60.0, + client_info=client_info, + ), + self.list_binding_matching_resources: gapic_v1.method.wrap_method( + self.list_binding_matching_resources, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_template: gapic_v1.method.wrap_method( + self.create_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_template: gapic_v1.method.wrap_method( + self.get_restore_template, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_templates: gapic_v1.method.wrap_method( + self.list_restore_templates, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_restore_template: gapic_v1.method.wrap_method( + self.update_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_template: gapic_v1.method.wrap_method( + self.delete_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.run_restore_template: gapic_v1.method.wrap_method( + self.run_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_template_execution: gapic_v1.method.wrap_method( + self.get_restore_template_execution, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_template_executions: gapic_v1.method.wrap_method( + self.list_restore_template_executions, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.trigger_restore_cleanup: gapic_v1.method.wrap_method( + self.trigger_restore_cleanup, + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_verification_plan: gapic_v1.method.wrap_method( + self.create_restore_verification_plan, + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_verification_plan_association: gapic_v1.method.wrap_method( + self.create_restore_verification_plan_association, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_verification_plan_association: gapic_v1.method.wrap_method( + self.get_restore_verification_plan_association, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_verification_plan_associations: gapic_v1.method.wrap_method( + self.list_restore_verification_plan_associations, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_verification_plan_association: gapic_v1.method.wrap_method( + self.delete_restore_verification_plan_association, + default_timeout=60.0, + client_info=client_info, + ), + self.trigger_restore_verification: gapic_v1.method.wrap_method( + self.trigger_restore_verification, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_verification_plan: gapic_v1.method.wrap_method( + self.get_restore_verification_plan, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_verification_plans: gapic_v1.method.wrap_method( + self.list_restore_verification_plans, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_verification_plan: gapic_v1.method.wrap_method( + self.delete_restore_verification_plan, + default_timeout=60.0, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -884,6 +1170,325 @@ def initialize_service( ]: raise NotImplementedError() + @property + def create_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.CreateAutoProtectionPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_auto_protection_policies( + self, + ) -> Callable[ + [autoprotectionpolicy.ListAutoProtectionPoliciesRequest], + Union[ + autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + Awaitable[autoprotectionpolicy.ListAutoProtectionPoliciesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.GetAutoProtectionPolicyRequest], + Union[ + autoprotectionpolicy.AutoProtectionPolicy, + Awaitable[autoprotectionpolicy.AutoProtectionPolicy], + ], + ]: + raise NotImplementedError() + + @property + def update_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.UpdateAutoProtectionPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.DeleteAutoProtectionPolicyRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest], + Union[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + Awaitable[autoprotectionpolicybinding.AutoProtectionPolicyBinding], + ], + ]: + raise NotImplementedError() + + @property + def list_auto_protection_policy_bindings( + self, + ) -> Callable[ + [autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest], + Union[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + Awaitable[ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def list_applied_auto_protection_policies( + self, + ) -> Callable[ + [appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest], + Union[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + Awaitable[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def initiate_delete_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_binding_matching_resources( + self, + ) -> Callable[ + [bindingmatchingresource.ListBindingMatchingResourcesRequest], + Union[ + bindingmatchingresource.ListBindingMatchingResourcesResponse, + Awaitable[bindingmatchingresource.ListBindingMatchingResourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def create_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.CreateRestoreTemplateRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_restore_template( + self, + ) -> Callable[ + [restore_template.GetRestoreTemplateRequest], + Union[ + restore_template.RestoreTemplate, + Awaitable[restore_template.RestoreTemplate], + ], + ]: + raise NotImplementedError() + + @property + def list_restore_templates( + self, + ) -> Callable[ + [restore_template.ListRestoreTemplatesRequest], + Union[ + restore_template.ListRestoreTemplatesResponse, + Awaitable[restore_template.ListRestoreTemplatesResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.UpdateRestoreTemplateRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_restore_template( + self, + ) -> Callable[ + [restore_template.DeleteRestoreTemplateRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def run_restore_template( + self, + ) -> Callable[ + [restore_template.RunRestoreTemplateRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_restore_template_execution( + self, + ) -> Callable[ + [restore_template_execution.GetRestoreTemplateExecutionRequest], + Union[ + restore_template_execution.RestoreTemplateExecution, + Awaitable[restore_template_execution.RestoreTemplateExecution], + ], + ]: + raise NotImplementedError() + + @property + def list_restore_template_executions( + self, + ) -> Callable[ + [restore_template_execution.ListRestoreTemplateExecutionsRequest], + Union[ + restore_template_execution.ListRestoreTemplateExecutionsResponse, + Awaitable[restore_template_execution.ListRestoreTemplateExecutionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def trigger_restore_cleanup( + self, + ) -> Callable[ + [restore_template_execution.TriggerRestoreCleanupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_restore_verification_plan( + self, + ) -> Callable[ + [gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_restore_verification_plan_association( + self, + ) -> Callable[ + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest + ], + Union[ + restore_verification_plan_association.RestoreVerificationPlanAssociation, + Awaitable[ + restore_verification_plan_association.RestoreVerificationPlanAssociation + ], + ], + ]: + raise NotImplementedError() + + @property + def list_restore_verification_plan_associations( + self, + ) -> Callable[ + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest + ], + Union[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + Awaitable[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def delete_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def trigger_restore_verification( + self, + ) -> Callable[ + [restore_verification_plan_association.TriggerRestoreVerificationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.GetRestoreVerificationPlanRequest], + Union[ + restore_verification_plan.RestoreVerificationPlan, + Awaitable[restore_verification_plan.RestoreVerificationPlan], + ], + ]: + raise NotImplementedError() + + @property + def list_restore_verification_plans( + self, + ) -> Callable[ + [restore_verification_plan.ListRestoreVerificationPlansRequest], + Union[ + restore_verification_plan.ListRestoreVerificationPlansResponse, + Awaitable[restore_verification_plan.ListRestoreVerificationPlansResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.DeleteRestoreVerificationPlanRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc.py index 648a16beb132..9c827241bb58 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc.py @@ -35,11 +35,26 @@ from google.protobuf.json_format import MessageToJson from google.cloud.backupdr_v1.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, backupdr, backupplan, backupplanassociation, backupvault, + bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .base import DEFAULT_CLIENT_INFO, BackupDRTransport @@ -1399,6 +1414,932 @@ def initialize_service( ) return self._stubs["initialize_service"] + @property + def create_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.CreateAutoProtectionPolicyRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create auto protection policy method over gRPC. + + Creates a new AutoProtectionPolicy in a given project + and location. + + Returns: + Callable[[~.CreateAutoProtectionPolicyRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_auto_protection_policy" not in self._stubs: + self._stubs["create_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.CreateAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_auto_protection_policy"] + + @property + def list_auto_protection_policies( + self, + ) -> Callable[ + [autoprotectionpolicy.ListAutoProtectionPoliciesRequest], + autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + ]: + r"""Return a callable for the list auto protection policies method over gRPC. + + Lists AutoProtectionPolicies for a given project and + location. + + Returns: + Callable[[~.ListAutoProtectionPoliciesRequest], + ~.ListAutoProtectionPoliciesResponse]: + 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_auto_protection_policies" not in self._stubs: + self._stubs["list_auto_protection_policies"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListAutoProtectionPolicies", + request_serializer=autoprotectionpolicy.ListAutoProtectionPoliciesRequest.serialize, + response_deserializer=autoprotectionpolicy.ListAutoProtectionPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_auto_protection_policies"] + + @property + def get_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.GetAutoProtectionPolicyRequest], + autoprotectionpolicy.AutoProtectionPolicy, + ]: + r"""Return a callable for the get auto protection policy method over gRPC. + + Gets details of a single AutoProtectionPolicy. + + Returns: + Callable[[~.GetAutoProtectionPolicyRequest], + ~.AutoProtectionPolicy]: + 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_auto_protection_policy" not in self._stubs: + self._stubs["get_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.GetAutoProtectionPolicyRequest.serialize, + response_deserializer=autoprotectionpolicy.AutoProtectionPolicy.deserialize, + ) + ) + return self._stubs["get_auto_protection_policy"] + + @property + def update_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.UpdateAutoProtectionPolicyRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the update auto protection policy method over gRPC. + + Updates the parameters of a single + AutoProtectionPolicy. + + Returns: + Callable[[~.UpdateAutoProtectionPolicyRequest], + ~.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 "update_auto_protection_policy" not in self._stubs: + self._stubs["update_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/UpdateAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_auto_protection_policy"] + + @property + def delete_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.DeleteAutoProtectionPolicyRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete auto protection policy method over gRPC. + + Deletes a single AutoProtectionPolicy. + + Returns: + Callable[[~.DeleteAutoProtectionPolicyRequest], + ~.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_auto_protection_policy" not in self._stubs: + self._stubs["delete_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/DeleteAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_auto_protection_policy"] + + @property + def create_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create auto protection policy + binding method over gRPC. + + Creates a new AutoProtectionPolicyBinding in a given + project and location. + + Returns: + Callable[[~.CreateAutoProtectionPolicyBindingRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_auto_protection_policy_binding" not in self._stubs: + self._stubs["create_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_auto_protection_policy_binding"] + + @property + def get_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest], + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + ]: + r"""Return a callable for the get auto protection policy + binding method over gRPC. + + Returns the auto protection policy binding read from + the CCFE tables. + + Returns: + Callable[[~.GetAutoProtectionPolicyBindingRequest], + ~.AutoProtectionPolicyBinding]: + 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_auto_protection_policy_binding" not in self._stubs: + self._stubs["get_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=autoprotectionpolicybinding.AutoProtectionPolicyBinding.deserialize, + ) + ) + return self._stubs["get_auto_protection_policy_binding"] + + @property + def list_auto_protection_policy_bindings( + self, + ) -> Callable[ + [autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest], + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + ]: + r"""Return a callable for the list auto protection policy + bindings method over gRPC. + + Returns the auto protection policy bindings read from + the CCFE tables. + + Returns: + Callable[[~.ListAutoProtectionPolicyBindingsRequest], + ~.ListAutoProtectionPolicyBindingsResponse]: + 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_auto_protection_policy_bindings" not in self._stubs: + self._stubs["list_auto_protection_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListAutoProtectionPolicyBindings", + request_serializer=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest.serialize, + response_deserializer=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["list_auto_protection_policy_bindings"] + + @property + def list_applied_auto_protection_policies( + self, + ) -> Callable[ + [appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest], + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + ]: + r"""Return a callable for the list applied auto protection + policies method over gRPC. + + Lists AppliedAutoProtectionPolicies in a given + project and location. + + Returns: + Callable[[~.ListAppliedAutoProtectionPoliciesRequest], + ~.ListAppliedAutoProtectionPoliciesResponse]: + 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_applied_auto_protection_policies" not in self._stubs: + self._stubs["list_applied_auto_protection_policies"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListAppliedAutoProtectionPolicies", + request_serializer=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest.serialize, + response_deserializer=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_applied_auto_protection_policies"] + + @property + def initiate_delete_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the initiate delete auto + protection policy binding method over gRPC. + + InitiateDeleteAutoProtectionPolicyBinding initiates + delete for AutoProtectionPolicy Binding + + Returns: + Callable[[~.InitiateDeleteAutoProtectionPolicyBindingRequest], + ~.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 "initiate_delete_auto_protection_policy_binding" not in self._stubs: + self._stubs["initiate_delete_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/InitiateDeleteAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["initiate_delete_auto_protection_policy_binding"] + + @property + def list_binding_matching_resources( + self, + ) -> Callable[ + [bindingmatchingresource.ListBindingMatchingResourcesRequest], + bindingmatchingresource.ListBindingMatchingResourcesResponse, + ]: + r"""Return a callable for the list binding matching + resources method over gRPC. + + Lists Binding Matching Resources for a given + AutoProtectionPolicyBinding. + + Returns: + Callable[[~.ListBindingMatchingResourcesRequest], + ~.ListBindingMatchingResourcesResponse]: + 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_binding_matching_resources" not in self._stubs: + self._stubs["list_binding_matching_resources"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListBindingMatchingResources", + request_serializer=bindingmatchingresource.ListBindingMatchingResourcesRequest.serialize, + response_deserializer=bindingmatchingresource.ListBindingMatchingResourcesResponse.deserialize, + ) + ) + return self._stubs["list_binding_matching_resources"] + + @property + def create_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.CreateRestoreTemplateRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create restore template method over gRPC. + + Creates a new RestoreTemplate in a given project and + location. + + Returns: + Callable[[~.CreateRestoreTemplateRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_template" not in self._stubs: + self._stubs["create_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateRestoreTemplate", + request_serializer=gcb_restore_template.CreateRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_restore_template"] + + @property + def get_restore_template( + self, + ) -> Callable[ + [restore_template.GetRestoreTemplateRequest], restore_template.RestoreTemplate + ]: + r"""Return a callable for the get restore template method over gRPC. + + Gets details of a RestoreTemplate. + + Returns: + Callable[[~.GetRestoreTemplateRequest], + ~.RestoreTemplate]: + 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_restore_template" not in self._stubs: + self._stubs["get_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetRestoreTemplate", + request_serializer=restore_template.GetRestoreTemplateRequest.serialize, + response_deserializer=restore_template.RestoreTemplate.deserialize, + ) + return self._stubs["get_restore_template"] + + @property + def list_restore_templates( + self, + ) -> Callable[ + [restore_template.ListRestoreTemplatesRequest], + restore_template.ListRestoreTemplatesResponse, + ]: + r"""Return a callable for the list restore templates method over gRPC. + + Lists RestoreTemplates in a given project and + location. + + Returns: + Callable[[~.ListRestoreTemplatesRequest], + ~.ListRestoreTemplatesResponse]: + 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_restore_templates" not in self._stubs: + self._stubs["list_restore_templates"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListRestoreTemplates", + request_serializer=restore_template.ListRestoreTemplatesRequest.serialize, + response_deserializer=restore_template.ListRestoreTemplatesResponse.deserialize, + ) + return self._stubs["list_restore_templates"] + + @property + def update_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.UpdateRestoreTemplateRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update restore template method over gRPC. + + Updates the settings of a RestoreTemplate. + + Returns: + Callable[[~.UpdateRestoreTemplateRequest], + ~.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 "update_restore_template" not in self._stubs: + self._stubs["update_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/UpdateRestoreTemplate", + request_serializer=gcb_restore_template.UpdateRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_restore_template"] + + @property + def delete_restore_template( + self, + ) -> Callable[ + [restore_template.DeleteRestoreTemplateRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete restore template method over gRPC. + + Deletes a RestoreTemplate. + + Returns: + Callable[[~.DeleteRestoreTemplateRequest], + ~.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_restore_template" not in self._stubs: + self._stubs["delete_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/DeleteRestoreTemplate", + request_serializer=restore_template.DeleteRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_restore_template"] + + @property + def run_restore_template( + self, + ) -> Callable[ + [restore_template.RunRestoreTemplateRequest], operations_pb2.Operation + ]: + r"""Return a callable for the run restore template method over gRPC. + + Runs a RestoreTemplate. + + Returns: + Callable[[~.RunRestoreTemplateRequest], + ~.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 "run_restore_template" not in self._stubs: + self._stubs["run_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/RunRestoreTemplate", + request_serializer=restore_template.RunRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_restore_template"] + + @property + def get_restore_template_execution( + self, + ) -> Callable[ + [restore_template_execution.GetRestoreTemplateExecutionRequest], + restore_template_execution.RestoreTemplateExecution, + ]: + r"""Return a callable for the get restore template execution method over gRPC. + + Gets details of a RestoreTemplateExecution. + + Returns: + Callable[[~.GetRestoreTemplateExecutionRequest], + ~.RestoreTemplateExecution]: + 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_restore_template_execution" not in self._stubs: + self._stubs["get_restore_template_execution"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetRestoreTemplateExecution", + request_serializer=restore_template_execution.GetRestoreTemplateExecutionRequest.serialize, + response_deserializer=restore_template_execution.RestoreTemplateExecution.deserialize, + ) + ) + return self._stubs["get_restore_template_execution"] + + @property + def list_restore_template_executions( + self, + ) -> Callable[ + [restore_template_execution.ListRestoreTemplateExecutionsRequest], + restore_template_execution.ListRestoreTemplateExecutionsResponse, + ]: + r"""Return a callable for the list restore template + executions method over gRPC. + + Lists RestoreTemplateExecutions in a given project, + location and restore template. + + Returns: + Callable[[~.ListRestoreTemplateExecutionsRequest], + ~.ListRestoreTemplateExecutionsResponse]: + 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_restore_template_executions" not in self._stubs: + self._stubs["list_restore_template_executions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListRestoreTemplateExecutions", + request_serializer=restore_template_execution.ListRestoreTemplateExecutionsRequest.serialize, + response_deserializer=restore_template_execution.ListRestoreTemplateExecutionsResponse.deserialize, + ) + ) + return self._stubs["list_restore_template_executions"] + + @property + def trigger_restore_cleanup( + self, + ) -> Callable[ + [restore_template_execution.TriggerRestoreCleanupRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the trigger restore cleanup method over gRPC. + + Triggers cleanup of restored resources created during + execution. + + Returns: + Callable[[~.TriggerRestoreCleanupRequest], + ~.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 "trigger_restore_cleanup" not in self._stubs: + self._stubs["trigger_restore_cleanup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/TriggerRestoreCleanup", + request_serializer=restore_template_execution.TriggerRestoreCleanupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["trigger_restore_cleanup"] + + @property + def create_restore_verification_plan( + self, + ) -> Callable[ + [gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create restore verification + plan method over gRPC. + + Creates a new RestoreVerificationPlan in a given + project and location. + + Returns: + Callable[[~.CreateRestoreVerificationPlanRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_verification_plan" not in self._stubs: + self._stubs["create_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateRestoreVerificationPlan", + request_serializer=gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_restore_verification_plan"] + + @property + def create_restore_verification_plan_association( + self, + ) -> Callable[ + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the create restore verification + plan association method over gRPC. + + Creates a new RestoreVerificationPlanAssociation in a + given RestoreVerificationPlan. + + Returns: + Callable[[~.CreateRestoreVerificationPlanAssociationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_verification_plan_association" not in self._stubs: + self._stubs["create_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateRestoreVerificationPlanAssociation", + request_serializer=gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_restore_verification_plan_association"] + + @property + def get_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest + ], + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ]: + r"""Return a callable for the get restore verification plan + association method over gRPC. + + Gets details of a single + RestoreVerificationPlanAssociation in a given + RestoreVerificationPlan. + + Returns: + Callable[[~.GetRestoreVerificationPlanAssociationRequest], + ~.RestoreVerificationPlanAssociation]: + 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_restore_verification_plan_association" not in self._stubs: + self._stubs["get_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetRestoreVerificationPlanAssociation", + request_serializer=restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=restore_verification_plan_association.RestoreVerificationPlanAssociation.deserialize, + ) + ) + return self._stubs["get_restore_verification_plan_association"] + + @property + def list_restore_verification_plan_associations( + self, + ) -> Callable[ + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest + ], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + ]: + r"""Return a callable for the list restore verification plan + associations method over gRPC. + + Lists RestoreVerificationPlanAssociations in a given + RestoreVerificationPlan. + + Returns: + Callable[[~.ListRestoreVerificationPlanAssociationsRequest], + ~.ListRestoreVerificationPlanAssociationsResponse]: + 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_restore_verification_plan_associations" not in self._stubs: + self._stubs["list_restore_verification_plan_associations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListRestoreVerificationPlanAssociations", + request_serializer=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest.serialize, + response_deserializer=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.deserialize, + ) + ) + return self._stubs["list_restore_verification_plan_associations"] + + @property + def delete_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete restore verification + plan association method over gRPC. + + Deletes a single RestoreVerificationPlanAssociation + in a given RestoreVerificationPlan. + + Returns: + Callable[[~.DeleteRestoreVerificationPlanAssociationRequest], + ~.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_restore_verification_plan_association" not in self._stubs: + self._stubs["delete_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/DeleteRestoreVerificationPlanAssociation", + request_serializer=restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_restore_verification_plan_association"] + + @property + def trigger_restore_verification( + self, + ) -> Callable[ + [restore_verification_plan_association.TriggerRestoreVerificationRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the trigger restore verification method over gRPC. + + Triggers a new Restore Verification for the + association in a given RestoreVerificationPlan. + + Returns: + Callable[[~.TriggerRestoreVerificationRequest], + ~.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 "trigger_restore_verification" not in self._stubs: + self._stubs["trigger_restore_verification"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/TriggerRestoreVerification", + request_serializer=restore_verification_plan_association.TriggerRestoreVerificationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["trigger_restore_verification"] + + @property + def get_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.GetRestoreVerificationPlanRequest], + restore_verification_plan.RestoreVerificationPlan, + ]: + r"""Return a callable for the get restore verification plan method over gRPC. + + Gets details of a single RestoreVerificationPlan. + Returns the requested RestoreVerificationPlan. + + Returns: + Callable[[~.GetRestoreVerificationPlanRequest], + ~.RestoreVerificationPlan]: + 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_restore_verification_plan" not in self._stubs: + self._stubs["get_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetRestoreVerificationPlan", + request_serializer=restore_verification_plan.GetRestoreVerificationPlanRequest.serialize, + response_deserializer=restore_verification_plan.RestoreVerificationPlan.deserialize, + ) + ) + return self._stubs["get_restore_verification_plan"] + + @property + def list_restore_verification_plans( + self, + ) -> Callable[ + [restore_verification_plan.ListRestoreVerificationPlansRequest], + restore_verification_plan.ListRestoreVerificationPlansResponse, + ]: + r"""Return a callable for the list restore verification + plans method over gRPC. + + Lists RestoreVerificationPlans in a given project and + location. + + Returns: + Callable[[~.ListRestoreVerificationPlansRequest], + ~.ListRestoreVerificationPlansResponse]: + 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_restore_verification_plans" not in self._stubs: + self._stubs["list_restore_verification_plans"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListRestoreVerificationPlans", + request_serializer=restore_verification_plan.ListRestoreVerificationPlansRequest.serialize, + response_deserializer=restore_verification_plan.ListRestoreVerificationPlansResponse.deserialize, + ) + ) + return self._stubs["list_restore_verification_plans"] + + @property + def delete_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.DeleteRestoreVerificationPlanRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete restore verification + plan method over gRPC. + + Deletes a single RestoreVerificationPlan. If the ``force`` flag + is set to ``true``, any RestoreVerificationPlanAssociations + linked to this RestoreVerificationPlan will also be deleted. + + Returns: + Callable[[~.DeleteRestoreVerificationPlanRequest], + ~.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_restore_verification_plan" not in self._stubs: + self._stubs["delete_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/DeleteRestoreVerificationPlan", + request_serializer=restore_verification_plan.DeleteRestoreVerificationPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_restore_verification_plan"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc_asyncio.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc_asyncio.py index 1a98d9f14338..22b7498889b1 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc_asyncio.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/grpc_asyncio.py @@ -38,11 +38,26 @@ from grpc.experimental import aio # type: ignore from google.cloud.backupdr_v1.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, backupdr, backupplan, backupplanassociation, backupvault, + bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .base import DEFAULT_CLIENT_INFO, BackupDRTransport @@ -1449,258 +1464,1195 @@ def initialize_service( ) return self._stubs["initialize_service"] - def _prep_wrapped_messages(self, client_info): - """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" - self._wrapped_methods = { - self.list_management_servers: self._wrap_method( - self.list_management_servers, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_management_server: self._wrap_method( - self.get_management_server, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.create_management_server: self._wrap_method( - self.create_management_server, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_management_server: self._wrap_method( - self.delete_management_server, - default_timeout=60.0, - client_info=client_info, - ), - self.create_backup_vault: self._wrap_method( - self.create_backup_vault, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_backup_vaults: self._wrap_method( - self.list_backup_vaults, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.fetch_usable_backup_vaults: self._wrap_method( - self.fetch_usable_backup_vaults, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_backup_vault: self._wrap_method( - self.get_backup_vault, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_backup_vault: self._wrap_method( - self.update_backup_vault, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_backup_vault: self._wrap_method( - self.delete_backup_vault, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.list_data_sources: self._wrap_method( - self.list_data_sources, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.get_data_source: self._wrap_method( - self.get_data_source, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_data_source: self._wrap_method( - self.update_data_source, - default_timeout=60.0, - client_info=client_info, - ), - self.list_backups: self._wrap_method( - self.list_backups, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.fetch_backups_for_resource_type: self._wrap_method( - self.fetch_backups_for_resource_type, - default_timeout=None, - client_info=client_info, - ), - self.get_backup: self._wrap_method( - self.get_backup, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), - self.update_backup: self._wrap_method( - self.update_backup, - default_timeout=60.0, - client_info=client_info, - ), - self.delete_backup: self._wrap_method( - self.delete_backup, - default_timeout=None, - client_info=client_info, - ), - self.restore_backup: self._wrap_method( - self.restore_backup, - default_timeout=60.0, - client_info=client_info, - ), - self.create_backup_plan: self._wrap_method( - self.create_backup_plan, - default_timeout=None, - client_info=client_info, - ), - self.update_backup_plan: self._wrap_method( - self.update_backup_plan, - default_timeout=None, - client_info=client_info, - ), - self.get_backup_plan: self._wrap_method( - self.get_backup_plan, - default_timeout=None, - client_info=client_info, - ), - self.list_backup_plans: self._wrap_method( - self.list_backup_plans, - default_timeout=None, - client_info=client_info, - ), - self.delete_backup_plan: self._wrap_method( - self.delete_backup_plan, - default_timeout=None, - client_info=client_info, - ), - self.get_backup_plan_revision: self._wrap_method( - self.get_backup_plan_revision, - default_timeout=None, - client_info=client_info, - ), - self.list_backup_plan_revisions: self._wrap_method( - self.list_backup_plan_revisions, - default_timeout=None, - client_info=client_info, - ), - self.create_backup_plan_association: self._wrap_method( - self.create_backup_plan_association, - default_timeout=None, - client_info=client_info, - ), - self.update_backup_plan_association: self._wrap_method( - self.update_backup_plan_association, - default_timeout=None, - client_info=client_info, - ), - self.get_backup_plan_association: self._wrap_method( - self.get_backup_plan_association, - default_timeout=None, - client_info=client_info, - ), - self.list_backup_plan_associations: self._wrap_method( - self.list_backup_plan_associations, - default_timeout=None, - client_info=client_info, - ), + @property + def create_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.CreateAutoProtectionPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create auto protection policy method over gRPC. + + Creates a new AutoProtectionPolicy in a given project + and location. + + Returns: + Callable[[~.CreateAutoProtectionPolicyRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_auto_protection_policy" not in self._stubs: + self._stubs["create_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.CreateAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_auto_protection_policy"] + + @property + def list_auto_protection_policies( + self, + ) -> Callable[ + [autoprotectionpolicy.ListAutoProtectionPoliciesRequest], + Awaitable[autoprotectionpolicy.ListAutoProtectionPoliciesResponse], + ]: + r"""Return a callable for the list auto protection policies method over gRPC. + + Lists AutoProtectionPolicies for a given project and + location. + + Returns: + Callable[[~.ListAutoProtectionPoliciesRequest], + Awaitable[~.ListAutoProtectionPoliciesResponse]]: + 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_auto_protection_policies" not in self._stubs: + self._stubs["list_auto_protection_policies"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListAutoProtectionPolicies", + request_serializer=autoprotectionpolicy.ListAutoProtectionPoliciesRequest.serialize, + response_deserializer=autoprotectionpolicy.ListAutoProtectionPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_auto_protection_policies"] + + @property + def get_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.GetAutoProtectionPolicyRequest], + Awaitable[autoprotectionpolicy.AutoProtectionPolicy], + ]: + r"""Return a callable for the get auto protection policy method over gRPC. + + Gets details of a single AutoProtectionPolicy. + + Returns: + Callable[[~.GetAutoProtectionPolicyRequest], + Awaitable[~.AutoProtectionPolicy]]: + 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_auto_protection_policy" not in self._stubs: + self._stubs["get_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.GetAutoProtectionPolicyRequest.serialize, + response_deserializer=autoprotectionpolicy.AutoProtectionPolicy.deserialize, + ) + ) + return self._stubs["get_auto_protection_policy"] + + @property + def update_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.UpdateAutoProtectionPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update auto protection policy method over gRPC. + + Updates the parameters of a single + AutoProtectionPolicy. + + Returns: + Callable[[~.UpdateAutoProtectionPolicyRequest], + 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 "update_auto_protection_policy" not in self._stubs: + self._stubs["update_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/UpdateAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["update_auto_protection_policy"] + + @property + def delete_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.DeleteAutoProtectionPolicyRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete auto protection policy method over gRPC. + + Deletes a single AutoProtectionPolicy. + + Returns: + Callable[[~.DeleteAutoProtectionPolicyRequest], + 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_auto_protection_policy" not in self._stubs: + self._stubs["delete_auto_protection_policy"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/DeleteAutoProtectionPolicy", + request_serializer=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_auto_protection_policy"] + + @property + def create_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create auto protection policy + binding method over gRPC. + + Creates a new AutoProtectionPolicyBinding in a given + project and location. + + Returns: + Callable[[~.CreateAutoProtectionPolicyBindingRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_auto_protection_policy_binding" not in self._stubs: + self._stubs["create_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_auto_protection_policy_binding"] + + @property + def get_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest], + Awaitable[autoprotectionpolicybinding.AutoProtectionPolicyBinding], + ]: + r"""Return a callable for the get auto protection policy + binding method over gRPC. + + Returns the auto protection policy binding read from + the CCFE tables. + + Returns: + Callable[[~.GetAutoProtectionPolicyBindingRequest], + Awaitable[~.AutoProtectionPolicyBinding]]: + 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_auto_protection_policy_binding" not in self._stubs: + self._stubs["get_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=autoprotectionpolicybinding.AutoProtectionPolicyBinding.deserialize, + ) + ) + return self._stubs["get_auto_protection_policy_binding"] + + @property + def list_auto_protection_policy_bindings( + self, + ) -> Callable[ + [autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest], + Awaitable[autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse], + ]: + r"""Return a callable for the list auto protection policy + bindings method over gRPC. + + Returns the auto protection policy bindings read from + the CCFE tables. + + Returns: + Callable[[~.ListAutoProtectionPolicyBindingsRequest], + Awaitable[~.ListAutoProtectionPolicyBindingsResponse]]: + 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_auto_protection_policy_bindings" not in self._stubs: + self._stubs["list_auto_protection_policy_bindings"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListAutoProtectionPolicyBindings", + request_serializer=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest.serialize, + response_deserializer=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.deserialize, + ) + ) + return self._stubs["list_auto_protection_policy_bindings"] + + @property + def list_applied_auto_protection_policies( + self, + ) -> Callable[ + [appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest], + Awaitable[ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse + ], + ]: + r"""Return a callable for the list applied auto protection + policies method over gRPC. + + Lists AppliedAutoProtectionPolicies in a given + project and location. + + Returns: + Callable[[~.ListAppliedAutoProtectionPoliciesRequest], + Awaitable[~.ListAppliedAutoProtectionPoliciesResponse]]: + 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_applied_auto_protection_policies" not in self._stubs: + self._stubs["list_applied_auto_protection_policies"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListAppliedAutoProtectionPolicies", + request_serializer=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest.serialize, + response_deserializer=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.deserialize, + ) + ) + return self._stubs["list_applied_auto_protection_policies"] + + @property + def initiate_delete_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the initiate delete auto + protection policy binding method over gRPC. + + InitiateDeleteAutoProtectionPolicyBinding initiates + delete for AutoProtectionPolicy Binding + + Returns: + Callable[[~.InitiateDeleteAutoProtectionPolicyBindingRequest], + 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 "initiate_delete_auto_protection_policy_binding" not in self._stubs: + self._stubs["initiate_delete_auto_protection_policy_binding"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/InitiateDeleteAutoProtectionPolicyBinding", + request_serializer=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["initiate_delete_auto_protection_policy_binding"] + + @property + def list_binding_matching_resources( + self, + ) -> Callable[ + [bindingmatchingresource.ListBindingMatchingResourcesRequest], + Awaitable[bindingmatchingresource.ListBindingMatchingResourcesResponse], + ]: + r"""Return a callable for the list binding matching + resources method over gRPC. + + Lists Binding Matching Resources for a given + AutoProtectionPolicyBinding. + + Returns: + Callable[[~.ListBindingMatchingResourcesRequest], + Awaitable[~.ListBindingMatchingResourcesResponse]]: + 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_binding_matching_resources" not in self._stubs: + self._stubs["list_binding_matching_resources"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListBindingMatchingResources", + request_serializer=bindingmatchingresource.ListBindingMatchingResourcesRequest.serialize, + response_deserializer=bindingmatchingresource.ListBindingMatchingResourcesResponse.deserialize, + ) + ) + return self._stubs["list_binding_matching_resources"] + + @property + def create_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.CreateRestoreTemplateRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create restore template method over gRPC. + + Creates a new RestoreTemplate in a given project and + location. + + Returns: + Callable[[~.CreateRestoreTemplateRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_template" not in self._stubs: + self._stubs["create_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateRestoreTemplate", + request_serializer=gcb_restore_template.CreateRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_restore_template"] + + @property + def get_restore_template( + self, + ) -> Callable[ + [restore_template.GetRestoreTemplateRequest], + Awaitable[restore_template.RestoreTemplate], + ]: + r"""Return a callable for the get restore template method over gRPC. + + Gets details of a RestoreTemplate. + + Returns: + Callable[[~.GetRestoreTemplateRequest], + Awaitable[~.RestoreTemplate]]: + 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_restore_template" not in self._stubs: + self._stubs["get_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetRestoreTemplate", + request_serializer=restore_template.GetRestoreTemplateRequest.serialize, + response_deserializer=restore_template.RestoreTemplate.deserialize, + ) + return self._stubs["get_restore_template"] + + @property + def list_restore_templates( + self, + ) -> Callable[ + [restore_template.ListRestoreTemplatesRequest], + Awaitable[restore_template.ListRestoreTemplatesResponse], + ]: + r"""Return a callable for the list restore templates method over gRPC. + + Lists RestoreTemplates in a given project and + location. + + Returns: + Callable[[~.ListRestoreTemplatesRequest], + Awaitable[~.ListRestoreTemplatesResponse]]: + 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_restore_templates" not in self._stubs: + self._stubs["list_restore_templates"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListRestoreTemplates", + request_serializer=restore_template.ListRestoreTemplatesRequest.serialize, + response_deserializer=restore_template.ListRestoreTemplatesResponse.deserialize, + ) + return self._stubs["list_restore_templates"] + + @property + def update_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.UpdateRestoreTemplateRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update restore template method over gRPC. + + Updates the settings of a RestoreTemplate. + + Returns: + Callable[[~.UpdateRestoreTemplateRequest], + 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 "update_restore_template" not in self._stubs: + self._stubs["update_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/UpdateRestoreTemplate", + request_serializer=gcb_restore_template.UpdateRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_restore_template"] + + @property + def delete_restore_template( + self, + ) -> Callable[ + [restore_template.DeleteRestoreTemplateRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete restore template method over gRPC. + + Deletes a RestoreTemplate. + + Returns: + Callable[[~.DeleteRestoreTemplateRequest], + 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_restore_template" not in self._stubs: + self._stubs["delete_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/DeleteRestoreTemplate", + request_serializer=restore_template.DeleteRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_restore_template"] + + @property + def run_restore_template( + self, + ) -> Callable[ + [restore_template.RunRestoreTemplateRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the run restore template method over gRPC. + + Runs a RestoreTemplate. + + Returns: + Callable[[~.RunRestoreTemplateRequest], + 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 "run_restore_template" not in self._stubs: + self._stubs["run_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/RunRestoreTemplate", + request_serializer=restore_template.RunRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_restore_template"] + + @property + def get_restore_template_execution( + self, + ) -> Callable[ + [restore_template_execution.GetRestoreTemplateExecutionRequest], + Awaitable[restore_template_execution.RestoreTemplateExecution], + ]: + r"""Return a callable for the get restore template execution method over gRPC. + + Gets details of a RestoreTemplateExecution. + + Returns: + Callable[[~.GetRestoreTemplateExecutionRequest], + Awaitable[~.RestoreTemplateExecution]]: + 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_restore_template_execution" not in self._stubs: + self._stubs["get_restore_template_execution"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetRestoreTemplateExecution", + request_serializer=restore_template_execution.GetRestoreTemplateExecutionRequest.serialize, + response_deserializer=restore_template_execution.RestoreTemplateExecution.deserialize, + ) + ) + return self._stubs["get_restore_template_execution"] + + @property + def list_restore_template_executions( + self, + ) -> Callable[ + [restore_template_execution.ListRestoreTemplateExecutionsRequest], + Awaitable[restore_template_execution.ListRestoreTemplateExecutionsResponse], + ]: + r"""Return a callable for the list restore template + executions method over gRPC. + + Lists RestoreTemplateExecutions in a given project, + location and restore template. + + Returns: + Callable[[~.ListRestoreTemplateExecutionsRequest], + Awaitable[~.ListRestoreTemplateExecutionsResponse]]: + 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_restore_template_executions" not in self._stubs: + self._stubs["list_restore_template_executions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListRestoreTemplateExecutions", + request_serializer=restore_template_execution.ListRestoreTemplateExecutionsRequest.serialize, + response_deserializer=restore_template_execution.ListRestoreTemplateExecutionsResponse.deserialize, + ) + ) + return self._stubs["list_restore_template_executions"] + + @property + def trigger_restore_cleanup( + self, + ) -> Callable[ + [restore_template_execution.TriggerRestoreCleanupRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the trigger restore cleanup method over gRPC. + + Triggers cleanup of restored resources created during + execution. + + Returns: + Callable[[~.TriggerRestoreCleanupRequest], + 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 "trigger_restore_cleanup" not in self._stubs: + self._stubs["trigger_restore_cleanup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/TriggerRestoreCleanup", + request_serializer=restore_template_execution.TriggerRestoreCleanupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["trigger_restore_cleanup"] + + @property + def create_restore_verification_plan( + self, + ) -> Callable[ + [gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create restore verification + plan method over gRPC. + + Creates a new RestoreVerificationPlan in a given + project and location. + + Returns: + Callable[[~.CreateRestoreVerificationPlanRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_verification_plan" not in self._stubs: + self._stubs["create_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateRestoreVerificationPlan", + request_serializer=gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_restore_verification_plan"] + + @property + def create_restore_verification_plan_association( + self, + ) -> Callable[ + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create restore verification + plan association method over gRPC. + + Creates a new RestoreVerificationPlanAssociation in a + given RestoreVerificationPlan. + + Returns: + Callable[[~.CreateRestoreVerificationPlanAssociationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_verification_plan_association" not in self._stubs: + self._stubs["create_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/CreateRestoreVerificationPlanAssociation", + request_serializer=gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_restore_verification_plan_association"] + + @property + def get_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest + ], + Awaitable[ + restore_verification_plan_association.RestoreVerificationPlanAssociation + ], + ]: + r"""Return a callable for the get restore verification plan + association method over gRPC. + + Gets details of a single + RestoreVerificationPlanAssociation in a given + RestoreVerificationPlan. + + Returns: + Callable[[~.GetRestoreVerificationPlanAssociationRequest], + Awaitable[~.RestoreVerificationPlanAssociation]]: + 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_restore_verification_plan_association" not in self._stubs: + self._stubs["get_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetRestoreVerificationPlanAssociation", + request_serializer=restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=restore_verification_plan_association.RestoreVerificationPlanAssociation.deserialize, + ) + ) + return self._stubs["get_restore_verification_plan_association"] + + @property + def list_restore_verification_plan_associations( + self, + ) -> Callable[ + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest + ], + Awaitable[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ], + ]: + r"""Return a callable for the list restore verification plan + associations method over gRPC. + + Lists RestoreVerificationPlanAssociations in a given + RestoreVerificationPlan. + + Returns: + Callable[[~.ListRestoreVerificationPlanAssociationsRequest], + Awaitable[~.ListRestoreVerificationPlanAssociationsResponse]]: + 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_restore_verification_plan_associations" not in self._stubs: + self._stubs["list_restore_verification_plan_associations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListRestoreVerificationPlanAssociations", + request_serializer=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest.serialize, + response_deserializer=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.deserialize, + ) + ) + return self._stubs["list_restore_verification_plan_associations"] + + @property + def delete_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete restore verification + plan association method over gRPC. + + Deletes a single RestoreVerificationPlanAssociation + in a given RestoreVerificationPlan. + + Returns: + Callable[[~.DeleteRestoreVerificationPlanAssociationRequest], + 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_restore_verification_plan_association" not in self._stubs: + self._stubs["delete_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/DeleteRestoreVerificationPlanAssociation", + request_serializer=restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_restore_verification_plan_association"] + + @property + def trigger_restore_verification( + self, + ) -> Callable[ + [restore_verification_plan_association.TriggerRestoreVerificationRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the trigger restore verification method over gRPC. + + Triggers a new Restore Verification for the + association in a given RestoreVerificationPlan. + + Returns: + Callable[[~.TriggerRestoreVerificationRequest], + 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 "trigger_restore_verification" not in self._stubs: + self._stubs["trigger_restore_verification"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/TriggerRestoreVerification", + request_serializer=restore_verification_plan_association.TriggerRestoreVerificationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["trigger_restore_verification"] + + @property + def get_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.GetRestoreVerificationPlanRequest], + Awaitable[restore_verification_plan.RestoreVerificationPlan], + ]: + r"""Return a callable for the get restore verification plan method over gRPC. + + Gets details of a single RestoreVerificationPlan. + Returns the requested RestoreVerificationPlan. + + Returns: + Callable[[~.GetRestoreVerificationPlanRequest], + Awaitable[~.RestoreVerificationPlan]]: + 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_restore_verification_plan" not in self._stubs: + self._stubs["get_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/GetRestoreVerificationPlan", + request_serializer=restore_verification_plan.GetRestoreVerificationPlanRequest.serialize, + response_deserializer=restore_verification_plan.RestoreVerificationPlan.deserialize, + ) + ) + return self._stubs["get_restore_verification_plan"] + + @property + def list_restore_verification_plans( + self, + ) -> Callable[ + [restore_verification_plan.ListRestoreVerificationPlansRequest], + Awaitable[restore_verification_plan.ListRestoreVerificationPlansResponse], + ]: + r"""Return a callable for the list restore verification + plans method over gRPC. + + Lists RestoreVerificationPlans in a given project and + location. + + Returns: + Callable[[~.ListRestoreVerificationPlansRequest], + Awaitable[~.ListRestoreVerificationPlansResponse]]: + 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_restore_verification_plans" not in self._stubs: + self._stubs["list_restore_verification_plans"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/ListRestoreVerificationPlans", + request_serializer=restore_verification_plan.ListRestoreVerificationPlansRequest.serialize, + response_deserializer=restore_verification_plan.ListRestoreVerificationPlansResponse.deserialize, + ) + ) + return self._stubs["list_restore_verification_plans"] + + @property + def delete_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.DeleteRestoreVerificationPlanRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete restore verification + plan method over gRPC. + + Deletes a single RestoreVerificationPlan. If the ``force`` flag + is set to ``true``, any RestoreVerificationPlanAssociations + linked to this RestoreVerificationPlan will also be deleted. + + Returns: + Callable[[~.DeleteRestoreVerificationPlanRequest], + 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_restore_verification_plan" not in self._stubs: + self._stubs["delete_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1.BackupDR/DeleteRestoreVerificationPlan", + request_serializer=restore_verification_plan.DeleteRestoreVerificationPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_restore_verification_plan"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.list_management_servers: self._wrap_method( + self.list_management_servers, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_management_server: self._wrap_method( + self.get_management_server, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_management_server: self._wrap_method( + self.create_management_server, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_management_server: self._wrap_method( + self.delete_management_server, + default_timeout=60.0, + client_info=client_info, + ), + self.create_backup_vault: self._wrap_method( + self.create_backup_vault, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_backup_vaults: self._wrap_method( + self.list_backup_vaults, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.fetch_usable_backup_vaults: self._wrap_method( + self.fetch_usable_backup_vaults, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_backup_vault: self._wrap_method( + self.get_backup_vault, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_backup_vault: self._wrap_method( + self.update_backup_vault, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_backup_vault: self._wrap_method( + self.delete_backup_vault, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_data_sources: self._wrap_method( + self.list_data_sources, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_data_source: self._wrap_method( + self.get_data_source, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_data_source: self._wrap_method( + self.update_data_source, + default_timeout=60.0, + client_info=client_info, + ), + self.list_backups: self._wrap_method( + self.list_backups, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.fetch_backups_for_resource_type: self._wrap_method( + self.fetch_backups_for_resource_type, + default_timeout=None, + client_info=client_info, + ), + self.get_backup: self._wrap_method( + self.get_backup, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_backup: self._wrap_method( + self.update_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_backup: self._wrap_method( + self.delete_backup, + default_timeout=None, + client_info=client_info, + ), + self.restore_backup: self._wrap_method( + self.restore_backup, + default_timeout=60.0, + client_info=client_info, + ), + self.create_backup_plan: self._wrap_method( + self.create_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.update_backup_plan: self._wrap_method( + self.update_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_plan: self._wrap_method( + self.get_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_plans: self._wrap_method( + self.list_backup_plans, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup_plan: self._wrap_method( + self.delete_backup_plan, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_plan_revision: self._wrap_method( + self.get_backup_plan_revision, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_plan_revisions: self._wrap_method( + self.list_backup_plan_revisions, + default_timeout=None, + client_info=client_info, + ), + self.create_backup_plan_association: self._wrap_method( + self.create_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.update_backup_plan_association: self._wrap_method( + self.update_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_plan_association: self._wrap_method( + self.get_backup_plan_association, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_plan_associations: self._wrap_method( + self.list_backup_plan_associations, + default_timeout=None, + client_info=client_info, + ), self.fetch_backup_plan_associations_for_resource_type: self._wrap_method( self.fetch_backup_plan_associations_for_resource_type, default_timeout=None, @@ -1745,6 +2697,277 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.create_auto_protection_policy: self._wrap_method( + self.create_auto_protection_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.list_auto_protection_policies: self._wrap_method( + self.list_auto_protection_policies, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_auto_protection_policy: self._wrap_method( + self.get_auto_protection_policy, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_auto_protection_policy: self._wrap_method( + self.update_auto_protection_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_auto_protection_policy: self._wrap_method( + self.delete_auto_protection_policy, + default_timeout=60.0, + client_info=client_info, + ), + self.create_auto_protection_policy_binding: self._wrap_method( + self.create_auto_protection_policy_binding, + default_timeout=60.0, + client_info=client_info, + ), + self.get_auto_protection_policy_binding: self._wrap_method( + self.get_auto_protection_policy_binding, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_auto_protection_policy_bindings: self._wrap_method( + self.list_auto_protection_policy_bindings, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_applied_auto_protection_policies: self._wrap_method( + self.list_applied_auto_protection_policies, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.initiate_delete_auto_protection_policy_binding: self._wrap_method( + self.initiate_delete_auto_protection_policy_binding, + default_timeout=60.0, + client_info=client_info, + ), + self.list_binding_matching_resources: self._wrap_method( + self.list_binding_matching_resources, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_template: self._wrap_method( + self.create_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_template: self._wrap_method( + self.get_restore_template, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_templates: self._wrap_method( + self.list_restore_templates, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_restore_template: self._wrap_method( + self.update_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_template: self._wrap_method( + self.delete_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.run_restore_template: self._wrap_method( + self.run_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_template_execution: self._wrap_method( + self.get_restore_template_execution, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_template_executions: self._wrap_method( + self.list_restore_template_executions, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.trigger_restore_cleanup: self._wrap_method( + self.trigger_restore_cleanup, + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_verification_plan: self._wrap_method( + self.create_restore_verification_plan, + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_verification_plan_association: self._wrap_method( + self.create_restore_verification_plan_association, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_verification_plan_association: self._wrap_method( + self.get_restore_verification_plan_association, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_verification_plan_associations: self._wrap_method( + self.list_restore_verification_plan_associations, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_verification_plan_association: self._wrap_method( + self.delete_restore_verification_plan_association, + default_timeout=60.0, + client_info=client_info, + ), + self.trigger_restore_verification: self._wrap_method( + self.trigger_restore_verification, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_verification_plan: self._wrap_method( + self.get_restore_verification_plan, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_verification_plans: self._wrap_method( + self.list_restore_verification_plans, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_verification_plan: self._wrap_method( + self.delete_restore_verification_plan, + default_timeout=60.0, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest.py index 23c0cf12f64a..092e089a4016 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest.py @@ -36,11 +36,26 @@ from google.cloud.backupdr_v1._compat import transcode_request from google.cloud.backupdr_v1.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, backupdr, backupplan, backupplanassociation, backupvault, + bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO @@ -84,6 +99,22 @@ class BackupDRRestInterceptor: .. code-block:: python class MyCustomBackupDRInterceptor(BackupDRRestInterceptor): + def pre_create_auto_protection_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_auto_protection_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_auto_protection_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_auto_protection_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_backup_plan(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -116,6 +147,38 @@ def post_create_management_server(self, response): logging.log(f"Received response: {response}") return response + def pre_create_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_restore_verification_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_restore_verification_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_restore_verification_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_restore_verification_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_auto_protection_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_auto_protection_policy(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 @@ -156,6 +219,30 @@ def post_delete_management_server(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_restore_verification_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_restore_verification_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_restore_verification_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_restore_verification_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + def pre_fetch_backup_plan_associations_for_resource_type(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -188,6 +275,22 @@ def post_fetch_usable_backup_vaults(self, response): logging.log(f"Received response: {response}") return response + def pre_get_auto_protection_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_auto_protection_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_auto_protection_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_auto_protection_policy_binding(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 @@ -252,6 +355,38 @@ def post_get_management_server(self, response): logging.log(f"Received response: {response}") return response + def pre_get_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_restore_template_execution(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_restore_template_execution(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_restore_verification_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_restore_verification_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_restore_verification_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_restore_verification_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + def pre_initialize_service(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -260,6 +395,38 @@ def post_initialize_service(self, response): logging.log(f"Received response: {response}") return response + def pre_initiate_delete_auto_protection_policy_binding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_initiate_delete_auto_protection_policy_binding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_applied_auto_protection_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_applied_auto_protection_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_auto_protection_policies(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_auto_protection_policies(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_auto_protection_policy_bindings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_auto_protection_policy_bindings(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_backup_plan_associations(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -300,6 +467,14 @@ def post_list_backup_vaults(self, response): logging.log(f"Received response: {response}") return response + def pre_list_binding_matching_resources(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_binding_matching_resources(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_data_source_references(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -324,6 +499,38 @@ def post_list_management_servers(self, response): logging.log(f"Received response: {response}") return response + def pre_list_restore_template_executions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_restore_template_executions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_restore_templates(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_restore_templates(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_restore_verification_plan_associations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_restore_verification_plan_associations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_restore_verification_plans(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_restore_verification_plans(self, response): + logging.log(f"Received response: {response}") + return response + def pre_restore_backup(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -332,6 +539,14 @@ def post_restore_backup(self, response): logging.log(f"Received response: {response}") return response + def pre_run_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + def pre_trigger_backup(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -340,6 +555,30 @@ def post_trigger_backup(self, response): logging.log(f"Received response: {response}") return response + def pre_trigger_restore_cleanup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_trigger_restore_cleanup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_trigger_restore_verification(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_trigger_restore_verification(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_auto_protection_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_auto_protection_policy(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_backup(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -380,12 +619,118 @@ def post_update_data_source(self, response): logging.log(f"Received response: {response}") return response + def pre_update_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + transport = BackupDRRestTransport(interceptor=MyCustomBackupDRInterceptor()) client = BackupDRClient(transport=transport) """ + def pre_create_auto_protection_policy( + self, + request: autoprotectionpolicy.CreateAutoProtectionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.CreateAutoProtectionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_auto_protection_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_auto_protection_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_auto_protection_policy + + DEPRECATED. Please use the `post_create_auto_protection_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_auto_protection_policy` interceptor runs + before the `post_create_auto_protection_policy_with_metadata` interceptor. + """ + return response + + def post_create_auto_protection_policy_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_auto_protection_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_auto_protection_policy_with_metadata` + interceptor in new development instead of the `post_create_auto_protection_policy` interceptor. + When both interceptors are used, this `post_create_auto_protection_policy_with_metadata` interceptor runs after the + `post_create_auto_protection_policy` interceptor. The (possibly modified) response returned by + `post_create_auto_protection_policy` will be passed to + `post_create_auto_protection_policy_with_metadata`. + """ + return response, metadata + + def pre_create_auto_protection_policy_binding( + self, + request: autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_auto_protection_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_auto_protection_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_auto_protection_policy_binding + + DEPRECATED. Please use the `post_create_auto_protection_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_auto_protection_policy_binding` interceptor runs + before the `post_create_auto_protection_policy_binding_with_metadata` interceptor. + """ + return response + + def post_create_auto_protection_policy_binding_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_auto_protection_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_auto_protection_policy_binding_with_metadata` + interceptor in new development instead of the `post_create_auto_protection_policy_binding` interceptor. + When both interceptors are used, this `post_create_auto_protection_policy_binding_with_metadata` interceptor runs after the + `post_create_auto_protection_policy_binding` interceptor. The (possibly modified) response returned by + `post_create_auto_protection_policy_binding` will be passed to + `post_create_auto_protection_policy_binding_with_metadata`. + """ + return response, metadata + def pre_create_backup_plan( self, request: backupplan.CreateBackupPlanRequest, @@ -579,47 +924,243 @@ def post_create_management_server_with_metadata( """ return response, metadata - def pre_delete_backup( + def pre_create_restore_template( self, - request: backupvault.DeleteBackupRequest, + request: gcb_restore_template.CreateRestoreTemplateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupvault.DeleteBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + gcb_restore_template.CreateRestoreTemplateRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for delete_backup + """Pre-rpc interceptor for create_restore_template Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_delete_backup( + def post_create_restore_template( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_backup + """Post-rpc interceptor for create_restore_template - DEPRECATED. Please use the `post_delete_backup_with_metadata` + DEPRECATED. Please use the `post_create_restore_template_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_delete_backup` interceptor runs - before the `post_delete_backup_with_metadata` interceptor. + it is returned to user code. This `post_create_restore_template` interceptor runs + before the `post_create_restore_template_with_metadata` interceptor. """ return response - def post_delete_backup_with_metadata( + def post_create_restore_template_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_backup + """Post-rpc interceptor for create_restore_template Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_delete_backup_with_metadata` - interceptor in new development instead of the `post_delete_backup` interceptor. + We recommend only using this `post_create_restore_template_with_metadata` + interceptor in new development instead of the `post_create_restore_template` interceptor. + When both interceptors are used, this `post_create_restore_template_with_metadata` interceptor runs after the + `post_create_restore_template` interceptor. The (possibly modified) response returned by + `post_create_restore_template` will be passed to + `post_create_restore_template_with_metadata`. + """ + return response, metadata + + def pre_create_restore_verification_plan( + self, + request: gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_restore_verification_plan + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_restore_verification_plan( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_restore_verification_plan + + DEPRECATED. Please use the `post_create_restore_verification_plan_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_restore_verification_plan` interceptor runs + before the `post_create_restore_verification_plan_with_metadata` interceptor. + """ + return response + + def post_create_restore_verification_plan_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_restore_verification_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_restore_verification_plan_with_metadata` + interceptor in new development instead of the `post_create_restore_verification_plan` interceptor. + When both interceptors are used, this `post_create_restore_verification_plan_with_metadata` interceptor runs after the + `post_create_restore_verification_plan` interceptor. The (possibly modified) response returned by + `post_create_restore_verification_plan` will be passed to + `post_create_restore_verification_plan_with_metadata`. + """ + return response, metadata + + def pre_create_restore_verification_plan_association( + self, + request: gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_restore_verification_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_restore_verification_plan_association( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_restore_verification_plan_association + + DEPRECATED. Please use the `post_create_restore_verification_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_restore_verification_plan_association` interceptor runs + before the `post_create_restore_verification_plan_association_with_metadata` interceptor. + """ + return response + + def post_create_restore_verification_plan_association_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_restore_verification_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_restore_verification_plan_association_with_metadata` + interceptor in new development instead of the `post_create_restore_verification_plan_association` interceptor. + When both interceptors are used, this `post_create_restore_verification_plan_association_with_metadata` interceptor runs after the + `post_create_restore_verification_plan_association` interceptor. The (possibly modified) response returned by + `post_create_restore_verification_plan_association` will be passed to + `post_create_restore_verification_plan_association_with_metadata`. + """ + return response, metadata + + def pre_delete_auto_protection_policy( + self, + request: autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_auto_protection_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_auto_protection_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_auto_protection_policy + + DEPRECATED. Please use the `post_delete_auto_protection_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_auto_protection_policy` interceptor runs + before the `post_delete_auto_protection_policy_with_metadata` interceptor. + """ + return response + + def post_delete_auto_protection_policy_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_auto_protection_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_auto_protection_policy_with_metadata` + interceptor in new development instead of the `post_delete_auto_protection_policy` interceptor. + When both interceptors are used, this `post_delete_auto_protection_policy_with_metadata` interceptor runs after the + `post_delete_auto_protection_policy` interceptor. The (possibly modified) response returned by + `post_delete_auto_protection_policy` will be passed to + `post_delete_auto_protection_policy_with_metadata`. + """ + return response, metadata + + def pre_delete_backup( + self, + request: backupvault.DeleteBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.DeleteBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_backup + + 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 BackupDR server but before + it is returned to user code. This `post_delete_backup` interceptor runs + before the `post_delete_backup_with_metadata` interceptor. + """ + return response + + def post_delete_backup_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_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + 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 @@ -820,6 +1361,153 @@ def post_delete_management_server_with_metadata( """ return response, metadata + def pre_delete_restore_template( + self, + request: restore_template.DeleteRestoreTemplateRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template.DeleteRestoreTemplateRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_restore_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_restore_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_restore_template + + DEPRECATED. Please use the `post_delete_restore_template_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_restore_template` interceptor runs + before the `post_delete_restore_template_with_metadata` interceptor. + """ + return response + + def post_delete_restore_template_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_restore_template + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_restore_template_with_metadata` + interceptor in new development instead of the `post_delete_restore_template` interceptor. + When both interceptors are used, this `post_delete_restore_template_with_metadata` interceptor runs after the + `post_delete_restore_template` interceptor. The (possibly modified) response returned by + `post_delete_restore_template` will be passed to + `post_delete_restore_template_with_metadata`. + """ + return response, metadata + + def pre_delete_restore_verification_plan( + self, + request: restore_verification_plan.DeleteRestoreVerificationPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan.DeleteRestoreVerificationPlanRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_restore_verification_plan + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_restore_verification_plan( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_restore_verification_plan + + DEPRECATED. Please use the `post_delete_restore_verification_plan_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_restore_verification_plan` interceptor runs + before the `post_delete_restore_verification_plan_with_metadata` interceptor. + """ + return response + + def post_delete_restore_verification_plan_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_restore_verification_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_restore_verification_plan_with_metadata` + interceptor in new development instead of the `post_delete_restore_verification_plan` interceptor. + When both interceptors are used, this `post_delete_restore_verification_plan_with_metadata` interceptor runs after the + `post_delete_restore_verification_plan` interceptor. The (possibly modified) response returned by + `post_delete_restore_verification_plan` will be passed to + `post_delete_restore_verification_plan_with_metadata`. + """ + return response, metadata + + def pre_delete_restore_verification_plan_association( + self, + request: restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_restore_verification_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_restore_verification_plan_association( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_restore_verification_plan_association + + DEPRECATED. Please use the `post_delete_restore_verification_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_restore_verification_plan_association` interceptor runs + before the `post_delete_restore_verification_plan_association_with_metadata` interceptor. + """ + return response + + def post_delete_restore_verification_plan_association_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_restore_verification_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_restore_verification_plan_association_with_metadata` + interceptor in new development instead of the `post_delete_restore_verification_plan_association` interceptor. + When both interceptors are used, this `post_delete_restore_verification_plan_association_with_metadata` interceptor runs after the + `post_delete_restore_verification_plan_association` interceptor. The (possibly modified) response returned by + `post_delete_restore_verification_plan_association` will be passed to + `post_delete_restore_verification_plan_association_with_metadata`. + """ + return response, metadata + def pre_fetch_backup_plan_associations_for_resource_type( self, request: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, @@ -1030,42 +1718,146 @@ def post_fetch_usable_backup_vaults_with_metadata( """ return response, metadata - def pre_get_backup( + def pre_get_auto_protection_policy( self, - request: backupvault.GetBackupRequest, + request: autoprotectionpolicy.GetAutoProtectionPolicyRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[backupvault.GetBackupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_backup + ) -> Tuple[ + autoprotectionpolicy.GetAutoProtectionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_auto_protection_policy Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_get_backup(self, response: backupvault.Backup) -> backupvault.Backup: - """Post-rpc interceptor for get_backup + def post_get_auto_protection_policy( + self, response: autoprotectionpolicy.AutoProtectionPolicy + ) -> autoprotectionpolicy.AutoProtectionPolicy: + """Post-rpc interceptor for get_auto_protection_policy - DEPRECATED. Please use the `post_get_backup_with_metadata` + DEPRECATED. Please use the `post_get_auto_protection_policy_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_get_backup` interceptor runs - before the `post_get_backup_with_metadata` interceptor. + it is returned to user code. This `post_get_auto_protection_policy` interceptor runs + before the `post_get_auto_protection_policy_with_metadata` interceptor. """ return response - def post_get_backup_with_metadata( + def post_get_auto_protection_policy_with_metadata( self, - response: backupvault.Backup, + response: autoprotectionpolicy.AutoProtectionPolicy, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[backupvault.Backup, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_backup + ) -> Tuple[ + autoprotectionpolicy.AutoProtectionPolicy, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_auto_protection_policy Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_get_backup_with_metadata` + We recommend only using this `post_get_auto_protection_policy_with_metadata` + interceptor in new development instead of the `post_get_auto_protection_policy` interceptor. + When both interceptors are used, this `post_get_auto_protection_policy_with_metadata` interceptor runs after the + `post_get_auto_protection_policy` interceptor. The (possibly modified) response returned by + `post_get_auto_protection_policy` will be passed to + `post_get_auto_protection_policy_with_metadata`. + """ + return response, metadata + + def pre_get_auto_protection_policy_binding( + self, + request: autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_auto_protection_policy_binding + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_auto_protection_policy_binding( + self, response: autoprotectionpolicybinding.AutoProtectionPolicyBinding + ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: + """Post-rpc interceptor for get_auto_protection_policy_binding + + DEPRECATED. Please use the `post_get_auto_protection_policy_binding_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_auto_protection_policy_binding` interceptor runs + before the `post_get_auto_protection_policy_binding_with_metadata` interceptor. + """ + return response + + def post_get_auto_protection_policy_binding_with_metadata( + self, + response: autoprotectionpolicybinding.AutoProtectionPolicyBinding, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_auto_protection_policy_binding + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_auto_protection_policy_binding_with_metadata` + interceptor in new development instead of the `post_get_auto_protection_policy_binding` interceptor. + When both interceptors are used, this `post_get_auto_protection_policy_binding_with_metadata` interceptor runs after the + `post_get_auto_protection_policy_binding` interceptor. The (possibly modified) response returned by + `post_get_auto_protection_policy_binding` will be passed to + `post_get_auto_protection_policy_binding_with_metadata`. + """ + return response, metadata + + def pre_get_backup( + self, + request: backupvault.GetBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupvault.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 BackupDR server. + """ + return request, metadata + + def post_get_backup(self, response: backupvault.Backup) -> backupvault.Backup: + """Post-rpc interceptor for get_backup + + 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 BackupDR server but before + it is returned to user code. This `post_get_backup` interceptor runs + before the `post_get_backup_with_metadata` interceptor. + """ + return response + + def post_get_backup_with_metadata( + self, + response: backupvault.Backup, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[backupvault.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 BackupDR 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 @@ -1417,1167 +2209,6356 @@ def post_get_management_server_with_metadata( """ return response, metadata - def pre_initialize_service( + def pre_get_restore_template( self, - request: backupdr.InitializeServiceRequest, + request: restore_template.GetRestoreTemplateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupdr.InitializeServiceRequest, Sequence[Tuple[str, Union[str, bytes]]] + restore_template.GetRestoreTemplateRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for initialize_service + """Pre-rpc interceptor for get_restore_template Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_initialize_service( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for initialize_service + def post_get_restore_template( + self, response: restore_template.RestoreTemplate + ) -> restore_template.RestoreTemplate: + """Post-rpc interceptor for get_restore_template - DEPRECATED. Please use the `post_initialize_service_with_metadata` + DEPRECATED. Please use the `post_get_restore_template_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_initialize_service` interceptor runs - before the `post_initialize_service_with_metadata` interceptor. + it is returned to user code. This `post_get_restore_template` interceptor runs + before the `post_get_restore_template_with_metadata` interceptor. """ return response - def post_initialize_service_with_metadata( + def post_get_restore_template_with_metadata( self, - response: operations_pb2.Operation, + response: restore_template.RestoreTemplate, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for initialize_service + ) -> Tuple[ + restore_template.RestoreTemplate, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_restore_template Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_initialize_service_with_metadata` - interceptor in new development instead of the `post_initialize_service` interceptor. - When both interceptors are used, this `post_initialize_service_with_metadata` interceptor runs after the - `post_initialize_service` interceptor. The (possibly modified) response returned by - `post_initialize_service` will be passed to - `post_initialize_service_with_metadata`. + We recommend only using this `post_get_restore_template_with_metadata` + interceptor in new development instead of the `post_get_restore_template` interceptor. + When both interceptors are used, this `post_get_restore_template_with_metadata` interceptor runs after the + `post_get_restore_template` interceptor. The (possibly modified) response returned by + `post_get_restore_template` will be passed to + `post_get_restore_template_with_metadata`. """ return response, metadata - def pre_list_backup_plan_associations( + def pre_get_restore_template_execution( self, - request: backupplanassociation.ListBackupPlanAssociationsRequest, + request: restore_template_execution.GetRestoreTemplateExecutionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupplanassociation.ListBackupPlanAssociationsRequest, + restore_template_execution.GetRestoreTemplateExecutionRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_backup_plan_associations + """Pre-rpc interceptor for get_restore_template_execution Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_list_backup_plan_associations( - self, response: backupplanassociation.ListBackupPlanAssociationsResponse - ) -> backupplanassociation.ListBackupPlanAssociationsResponse: - """Post-rpc interceptor for list_backup_plan_associations + def post_get_restore_template_execution( + self, response: restore_template_execution.RestoreTemplateExecution + ) -> restore_template_execution.RestoreTemplateExecution: + """Post-rpc interceptor for get_restore_template_execution - DEPRECATED. Please use the `post_list_backup_plan_associations_with_metadata` + DEPRECATED. Please use the `post_get_restore_template_execution_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_list_backup_plan_associations` interceptor runs - before the `post_list_backup_plan_associations_with_metadata` interceptor. + it is returned to user code. This `post_get_restore_template_execution` interceptor runs + before the `post_get_restore_template_execution_with_metadata` interceptor. """ return response - def post_list_backup_plan_associations_with_metadata( + def post_get_restore_template_execution_with_metadata( self, - response: backupplanassociation.ListBackupPlanAssociationsResponse, + response: restore_template_execution.RestoreTemplateExecution, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupplanassociation.ListBackupPlanAssociationsResponse, + restore_template_execution.RestoreTemplateExecution, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for list_backup_plan_associations + """Post-rpc interceptor for get_restore_template_execution Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_list_backup_plan_associations_with_metadata` - interceptor in new development instead of the `post_list_backup_plan_associations` interceptor. - When both interceptors are used, this `post_list_backup_plan_associations_with_metadata` interceptor runs after the - `post_list_backup_plan_associations` interceptor. The (possibly modified) response returned by - `post_list_backup_plan_associations` will be passed to - `post_list_backup_plan_associations_with_metadata`. + We recommend only using this `post_get_restore_template_execution_with_metadata` + interceptor in new development instead of the `post_get_restore_template_execution` interceptor. + When both interceptors are used, this `post_get_restore_template_execution_with_metadata` interceptor runs after the + `post_get_restore_template_execution` interceptor. The (possibly modified) response returned by + `post_get_restore_template_execution` will be passed to + `post_get_restore_template_execution_with_metadata`. """ return response, metadata - def pre_list_backup_plan_revisions( + def pre_get_restore_verification_plan( self, - request: backupplan.ListBackupPlanRevisionsRequest, + request: restore_verification_plan.GetRestoreVerificationPlanRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupplan.ListBackupPlanRevisionsRequest, + restore_verification_plan.GetRestoreVerificationPlanRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_backup_plan_revisions + """Pre-rpc interceptor for get_restore_verification_plan Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_list_backup_plan_revisions( - self, response: backupplan.ListBackupPlanRevisionsResponse - ) -> backupplan.ListBackupPlanRevisionsResponse: - """Post-rpc interceptor for list_backup_plan_revisions + def post_get_restore_verification_plan( + self, response: restore_verification_plan.RestoreVerificationPlan + ) -> restore_verification_plan.RestoreVerificationPlan: + """Post-rpc interceptor for get_restore_verification_plan - DEPRECATED. Please use the `post_list_backup_plan_revisions_with_metadata` + DEPRECATED. Please use the `post_get_restore_verification_plan_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_list_backup_plan_revisions` interceptor runs - before the `post_list_backup_plan_revisions_with_metadata` interceptor. + it is returned to user code. This `post_get_restore_verification_plan` interceptor runs + before the `post_get_restore_verification_plan_with_metadata` interceptor. """ return response - def post_list_backup_plan_revisions_with_metadata( + def post_get_restore_verification_plan_with_metadata( self, - response: backupplan.ListBackupPlanRevisionsResponse, + response: restore_verification_plan.RestoreVerificationPlan, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupplan.ListBackupPlanRevisionsResponse, + restore_verification_plan.RestoreVerificationPlan, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for list_backup_plan_revisions + """Post-rpc interceptor for get_restore_verification_plan Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_list_backup_plan_revisions_with_metadata` - interceptor in new development instead of the `post_list_backup_plan_revisions` interceptor. - When both interceptors are used, this `post_list_backup_plan_revisions_with_metadata` interceptor runs after the - `post_list_backup_plan_revisions` interceptor. The (possibly modified) response returned by - `post_list_backup_plan_revisions` will be passed to - `post_list_backup_plan_revisions_with_metadata`. + We recommend only using this `post_get_restore_verification_plan_with_metadata` + interceptor in new development instead of the `post_get_restore_verification_plan` interceptor. + When both interceptors are used, this `post_get_restore_verification_plan_with_metadata` interceptor runs after the + `post_get_restore_verification_plan` interceptor. The (possibly modified) response returned by + `post_get_restore_verification_plan` will be passed to + `post_get_restore_verification_plan_with_metadata`. """ return response, metadata - def pre_list_backup_plans( + def pre_get_restore_verification_plan_association( self, - request: backupplan.ListBackupPlansRequest, + request: restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupplan.ListBackupPlansRequest, Sequence[Tuple[str, Union[str, bytes]]] + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_backup_plans + """Pre-rpc interceptor for get_restore_verification_plan_association Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_list_backup_plans( - self, response: backupplan.ListBackupPlansResponse - ) -> backupplan.ListBackupPlansResponse: - """Post-rpc interceptor for list_backup_plans + def post_get_restore_verification_plan_association( + self, + response: restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) -> restore_verification_plan_association.RestoreVerificationPlanAssociation: + """Post-rpc interceptor for get_restore_verification_plan_association - DEPRECATED. Please use the `post_list_backup_plans_with_metadata` + DEPRECATED. Please use the `post_get_restore_verification_plan_association_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_list_backup_plans` interceptor runs - before the `post_list_backup_plans_with_metadata` interceptor. + it is returned to user code. This `post_get_restore_verification_plan_association` interceptor runs + before the `post_get_restore_verification_plan_association_with_metadata` interceptor. """ return response - def post_list_backup_plans_with_metadata( + def post_get_restore_verification_plan_association_with_metadata( self, - response: backupplan.ListBackupPlansResponse, + response: restore_verification_plan_association.RestoreVerificationPlanAssociation, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupplan.ListBackupPlansResponse, Sequence[Tuple[str, Union[str, bytes]]] + restore_verification_plan_association.RestoreVerificationPlanAssociation, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for list_backup_plans + """Post-rpc interceptor for get_restore_verification_plan_association Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_list_backup_plans_with_metadata` - interceptor in new development instead of the `post_list_backup_plans` interceptor. - When both interceptors are used, this `post_list_backup_plans_with_metadata` interceptor runs after the - `post_list_backup_plans` interceptor. The (possibly modified) response returned by - `post_list_backup_plans` will be passed to - `post_list_backup_plans_with_metadata`. + We recommend only using this `post_get_restore_verification_plan_association_with_metadata` + interceptor in new development instead of the `post_get_restore_verification_plan_association` interceptor. + When both interceptors are used, this `post_get_restore_verification_plan_association_with_metadata` interceptor runs after the + `post_get_restore_verification_plan_association` interceptor. The (possibly modified) response returned by + `post_get_restore_verification_plan_association` will be passed to + `post_get_restore_verification_plan_association_with_metadata`. """ return response, metadata - def pre_list_backups( + def pre_initialize_service( self, - request: backupvault.ListBackupsRequest, + request: backupdr.InitializeServiceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[backupvault.ListBackupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for list_backups + ) -> Tuple[ + backupdr.InitializeServiceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for initialize_service Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_list_backups( - self, response: backupvault.ListBackupsResponse - ) -> backupvault.ListBackupsResponse: - """Post-rpc interceptor for list_backups + def post_initialize_service( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for initialize_service - DEPRECATED. Please use the `post_list_backups_with_metadata` + DEPRECATED. Please use the `post_initialize_service_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_list_backups` interceptor runs - before the `post_list_backups_with_metadata` interceptor. + it is returned to user code. This `post_initialize_service` interceptor runs + before the `post_initialize_service_with_metadata` interceptor. """ return response - def post_list_backups_with_metadata( + def post_initialize_service_with_metadata( self, - response: backupvault.ListBackupsResponse, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - backupvault.ListBackupsResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for list_backups + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for initialize_service Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR 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`. + We recommend only using this `post_initialize_service_with_metadata` + interceptor in new development instead of the `post_initialize_service` interceptor. + When both interceptors are used, this `post_initialize_service_with_metadata` interceptor runs after the + `post_initialize_service` interceptor. The (possibly modified) response returned by + `post_initialize_service` will be passed to + `post_initialize_service_with_metadata`. """ return response, metadata - def pre_list_backup_vaults( + def pre_initiate_delete_auto_protection_policy_binding( self, - request: backupvault.ListBackupVaultsRequest, + request: autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupvault.ListBackupVaultsRequest, Sequence[Tuple[str, Union[str, bytes]]] + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_backup_vaults + """Pre-rpc interceptor for initiate_delete_auto_protection_policy_binding Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_list_backup_vaults( - self, response: backupvault.ListBackupVaultsResponse - ) -> backupvault.ListBackupVaultsResponse: - """Post-rpc interceptor for list_backup_vaults + def post_initiate_delete_auto_protection_policy_binding( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for initiate_delete_auto_protection_policy_binding - DEPRECATED. Please use the `post_list_backup_vaults_with_metadata` + DEPRECATED. Please use the `post_initiate_delete_auto_protection_policy_binding_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_list_backup_vaults` interceptor runs - before the `post_list_backup_vaults_with_metadata` interceptor. + it is returned to user code. This `post_initiate_delete_auto_protection_policy_binding` interceptor runs + before the `post_initiate_delete_auto_protection_policy_binding_with_metadata` interceptor. """ return response - def post_list_backup_vaults_with_metadata( + def post_initiate_delete_auto_protection_policy_binding_with_metadata( self, - response: backupvault.ListBackupVaultsResponse, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - backupvault.ListBackupVaultsResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for list_backup_vaults + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for initiate_delete_auto_protection_policy_binding Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_list_backup_vaults_with_metadata` - interceptor in new development instead of the `post_list_backup_vaults` interceptor. - When both interceptors are used, this `post_list_backup_vaults_with_metadata` interceptor runs after the - `post_list_backup_vaults` interceptor. The (possibly modified) response returned by - `post_list_backup_vaults` will be passed to - `post_list_backup_vaults_with_metadata`. + We recommend only using this `post_initiate_delete_auto_protection_policy_binding_with_metadata` + interceptor in new development instead of the `post_initiate_delete_auto_protection_policy_binding` interceptor. + When both interceptors are used, this `post_initiate_delete_auto_protection_policy_binding_with_metadata` interceptor runs after the + `post_initiate_delete_auto_protection_policy_binding` interceptor. The (possibly modified) response returned by + `post_initiate_delete_auto_protection_policy_binding` will be passed to + `post_initiate_delete_auto_protection_policy_binding_with_metadata`. """ return response, metadata - def pre_list_data_source_references( + def pre_list_applied_auto_protection_policies( self, - request: datasourcereference.ListDataSourceReferencesRequest, + request: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - datasourcereference.ListDataSourceReferencesRequest, + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_data_source_references + """Pre-rpc interceptor for list_applied_auto_protection_policies Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_list_data_source_references( - self, response: datasourcereference.ListDataSourceReferencesResponse - ) -> datasourcereference.ListDataSourceReferencesResponse: - """Post-rpc interceptor for list_data_source_references + def post_list_applied_auto_protection_policies( + self, + response: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + ) -> appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: + """Post-rpc interceptor for list_applied_auto_protection_policies - DEPRECATED. Please use the `post_list_data_source_references_with_metadata` + DEPRECATED. Please use the `post_list_applied_auto_protection_policies_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_list_data_source_references` interceptor runs - before the `post_list_data_source_references_with_metadata` interceptor. + it is returned to user code. This `post_list_applied_auto_protection_policies` interceptor runs + before the `post_list_applied_auto_protection_policies_with_metadata` interceptor. """ return response - def post_list_data_source_references_with_metadata( + def post_list_applied_auto_protection_policies_with_metadata( self, - response: datasourcereference.ListDataSourceReferencesResponse, + response: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - datasourcereference.ListDataSourceReferencesResponse, + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for list_data_source_references + """Post-rpc interceptor for list_applied_auto_protection_policies Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_list_data_source_references_with_metadata` - interceptor in new development instead of the `post_list_data_source_references` interceptor. - When both interceptors are used, this `post_list_data_source_references_with_metadata` interceptor runs after the - `post_list_data_source_references` interceptor. The (possibly modified) response returned by - `post_list_data_source_references` will be passed to - `post_list_data_source_references_with_metadata`. + We recommend only using this `post_list_applied_auto_protection_policies_with_metadata` + interceptor in new development instead of the `post_list_applied_auto_protection_policies` interceptor. + When both interceptors are used, this `post_list_applied_auto_protection_policies_with_metadata` interceptor runs after the + `post_list_applied_auto_protection_policies` interceptor. The (possibly modified) response returned by + `post_list_applied_auto_protection_policies` will be passed to + `post_list_applied_auto_protection_policies_with_metadata`. """ return response, metadata - def pre_list_data_sources( + def pre_list_auto_protection_policies( self, - request: backupvault.ListDataSourcesRequest, + request: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupvault.ListDataSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]] + autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_data_sources + """Pre-rpc interceptor for list_auto_protection_policies Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_list_data_sources( - self, response: backupvault.ListDataSourcesResponse - ) -> backupvault.ListDataSourcesResponse: - """Post-rpc interceptor for list_data_sources + def post_list_auto_protection_policies( + self, response: autoprotectionpolicy.ListAutoProtectionPoliciesResponse + ) -> autoprotectionpolicy.ListAutoProtectionPoliciesResponse: + """Post-rpc interceptor for list_auto_protection_policies - DEPRECATED. Please use the `post_list_data_sources_with_metadata` + DEPRECATED. Please use the `post_list_auto_protection_policies_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_list_data_sources` interceptor runs - before the `post_list_data_sources_with_metadata` interceptor. + it is returned to user code. This `post_list_auto_protection_policies` interceptor runs + before the `post_list_auto_protection_policies_with_metadata` interceptor. """ return response - def post_list_data_sources_with_metadata( + def post_list_auto_protection_policies_with_metadata( self, - response: backupvault.ListDataSourcesResponse, + response: autoprotectionpolicy.ListAutoProtectionPoliciesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupvault.ListDataSourcesResponse, Sequence[Tuple[str, Union[str, bytes]]] + autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for list_data_sources + """Post-rpc interceptor for list_auto_protection_policies Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_list_data_sources_with_metadata` - interceptor in new development instead of the `post_list_data_sources` interceptor. - When both interceptors are used, this `post_list_data_sources_with_metadata` interceptor runs after the - `post_list_data_sources` interceptor. The (possibly modified) response returned by - `post_list_data_sources` will be passed to - `post_list_data_sources_with_metadata`. + We recommend only using this `post_list_auto_protection_policies_with_metadata` + interceptor in new development instead of the `post_list_auto_protection_policies` interceptor. + When both interceptors are used, this `post_list_auto_protection_policies_with_metadata` interceptor runs after the + `post_list_auto_protection_policies` interceptor. The (possibly modified) response returned by + `post_list_auto_protection_policies` will be passed to + `post_list_auto_protection_policies_with_metadata`. """ return response, metadata - def pre_list_management_servers( + def pre_list_auto_protection_policy_bindings( self, - request: backupdr.ListManagementServersRequest, + request: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupdr.ListManagementServersRequest, Sequence[Tuple[str, Union[str, bytes]]] + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_management_servers + """Pre-rpc interceptor for list_auto_protection_policy_bindings Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_list_management_servers( - self, response: backupdr.ListManagementServersResponse - ) -> backupdr.ListManagementServersResponse: - """Post-rpc interceptor for list_management_servers + def post_list_auto_protection_policy_bindings( + self, + response: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + ) -> autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: + """Post-rpc interceptor for list_auto_protection_policy_bindings - DEPRECATED. Please use the `post_list_management_servers_with_metadata` + DEPRECATED. Please use the `post_list_auto_protection_policy_bindings_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_list_management_servers` interceptor runs - before the `post_list_management_servers_with_metadata` interceptor. + it is returned to user code. This `post_list_auto_protection_policy_bindings` interceptor runs + before the `post_list_auto_protection_policy_bindings_with_metadata` interceptor. """ return response - def post_list_management_servers_with_metadata( + def post_list_auto_protection_policy_bindings_with_metadata( self, - response: backupdr.ListManagementServersResponse, + response: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupdr.ListManagementServersResponse, Sequence[Tuple[str, Union[str, bytes]]] + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for list_management_servers + """Post-rpc interceptor for list_auto_protection_policy_bindings Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_list_management_servers_with_metadata` - interceptor in new development instead of the `post_list_management_servers` interceptor. - When both interceptors are used, this `post_list_management_servers_with_metadata` interceptor runs after the - `post_list_management_servers` interceptor. The (possibly modified) response returned by - `post_list_management_servers` will be passed to - `post_list_management_servers_with_metadata`. + We recommend only using this `post_list_auto_protection_policy_bindings_with_metadata` + interceptor in new development instead of the `post_list_auto_protection_policy_bindings` interceptor. + When both interceptors are used, this `post_list_auto_protection_policy_bindings_with_metadata` interceptor runs after the + `post_list_auto_protection_policy_bindings` interceptor. The (possibly modified) response returned by + `post_list_auto_protection_policy_bindings` will be passed to + `post_list_auto_protection_policy_bindings_with_metadata`. """ return response, metadata - def pre_restore_backup( + def pre_list_backup_plan_associations( self, - request: backupvault.RestoreBackupRequest, + request: backupplanassociation.ListBackupPlanAssociationsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupvault.RestoreBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + backupplanassociation.ListBackupPlanAssociationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for restore_backup + """Pre-rpc interceptor for list_backup_plan_associations Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_restore_backup( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for restore_backup + def post_list_backup_plan_associations( + self, response: backupplanassociation.ListBackupPlanAssociationsResponse + ) -> backupplanassociation.ListBackupPlanAssociationsResponse: + """Post-rpc interceptor for list_backup_plan_associations - DEPRECATED. Please use the `post_restore_backup_with_metadata` + DEPRECATED. Please use the `post_list_backup_plan_associations_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_restore_backup` interceptor runs - before the `post_restore_backup_with_metadata` interceptor. + it is returned to user code. This `post_list_backup_plan_associations` interceptor runs + before the `post_list_backup_plan_associations_with_metadata` interceptor. """ return response - def post_restore_backup_with_metadata( + def post_list_backup_plan_associations_with_metadata( self, - response: operations_pb2.Operation, + response: backupplanassociation.ListBackupPlanAssociationsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for restore_backup + ) -> Tuple[ + backupplanassociation.ListBackupPlanAssociationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_backup_plan_associations Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_restore_backup_with_metadata` - interceptor in new development instead of the `post_restore_backup` interceptor. - When both interceptors are used, this `post_restore_backup_with_metadata` interceptor runs after the - `post_restore_backup` interceptor. The (possibly modified) response returned by - `post_restore_backup` will be passed to - `post_restore_backup_with_metadata`. + We recommend only using this `post_list_backup_plan_associations_with_metadata` + interceptor in new development instead of the `post_list_backup_plan_associations` interceptor. + When both interceptors are used, this `post_list_backup_plan_associations_with_metadata` interceptor runs after the + `post_list_backup_plan_associations` interceptor. The (possibly modified) response returned by + `post_list_backup_plan_associations` will be passed to + `post_list_backup_plan_associations_with_metadata`. """ return response, metadata - def pre_trigger_backup( + def pre_list_backup_plan_revisions( self, - request: backupplanassociation.TriggerBackupRequest, + request: backupplan.ListBackupPlanRevisionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupplanassociation.TriggerBackupRequest, + backupplan.ListBackupPlanRevisionsRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for trigger_backup + """Pre-rpc interceptor for list_backup_plan_revisions Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_trigger_backup( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for trigger_backup + def post_list_backup_plan_revisions( + self, response: backupplan.ListBackupPlanRevisionsResponse + ) -> backupplan.ListBackupPlanRevisionsResponse: + """Post-rpc interceptor for list_backup_plan_revisions - DEPRECATED. Please use the `post_trigger_backup_with_metadata` + DEPRECATED. Please use the `post_list_backup_plan_revisions_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_trigger_backup` interceptor runs - before the `post_trigger_backup_with_metadata` interceptor. + it is returned to user code. This `post_list_backup_plan_revisions` interceptor runs + before the `post_list_backup_plan_revisions_with_metadata` interceptor. """ return response - def post_trigger_backup_with_metadata( + def post_list_backup_plan_revisions_with_metadata( self, - response: operations_pb2.Operation, + response: backupplan.ListBackupPlanRevisionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for trigger_backup + ) -> Tuple[ + backupplan.ListBackupPlanRevisionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_backup_plan_revisions Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_trigger_backup_with_metadata` - interceptor in new development instead of the `post_trigger_backup` interceptor. - When both interceptors are used, this `post_trigger_backup_with_metadata` interceptor runs after the - `post_trigger_backup` interceptor. The (possibly modified) response returned by - `post_trigger_backup` will be passed to - `post_trigger_backup_with_metadata`. + We recommend only using this `post_list_backup_plan_revisions_with_metadata` + interceptor in new development instead of the `post_list_backup_plan_revisions` interceptor. + When both interceptors are used, this `post_list_backup_plan_revisions_with_metadata` interceptor runs after the + `post_list_backup_plan_revisions` interceptor. The (possibly modified) response returned by + `post_list_backup_plan_revisions` will be passed to + `post_list_backup_plan_revisions_with_metadata`. """ return response, metadata - def pre_update_backup( + def pre_list_backup_plans( self, - request: backupvault.UpdateBackupRequest, + request: backupplan.ListBackupPlansRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupvault.UpdateBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + backupplan.ListBackupPlansRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for update_backup + """Pre-rpc interceptor for list_backup_plans Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_update_backup( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_backup + def post_list_backup_plans( + self, response: backupplan.ListBackupPlansResponse + ) -> backupplan.ListBackupPlansResponse: + """Post-rpc interceptor for list_backup_plans - DEPRECATED. Please use the `post_update_backup_with_metadata` + DEPRECATED. Please use the `post_list_backup_plans_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_update_backup` interceptor runs - before the `post_update_backup_with_metadata` interceptor. + it is returned to user code. This `post_list_backup_plans` interceptor runs + before the `post_list_backup_plans_with_metadata` interceptor. """ return response - def post_update_backup_with_metadata( + def post_list_backup_plans_with_metadata( self, - response: operations_pb2.Operation, + response: backupplan.ListBackupPlansResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_backup + ) -> Tuple[ + backupplan.ListBackupPlansResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_backup_plans Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_update_backup_with_metadata` - interceptor in new development instead of the `post_update_backup` interceptor. - When both interceptors are used, this `post_update_backup_with_metadata` interceptor runs after the - `post_update_backup` interceptor. The (possibly modified) response returned by - `post_update_backup` will be passed to - `post_update_backup_with_metadata`. + We recommend only using this `post_list_backup_plans_with_metadata` + interceptor in new development instead of the `post_list_backup_plans` interceptor. + When both interceptors are used, this `post_list_backup_plans_with_metadata` interceptor runs after the + `post_list_backup_plans` interceptor. The (possibly modified) response returned by + `post_list_backup_plans` will be passed to + `post_list_backup_plans_with_metadata`. """ return response, metadata - def pre_update_backup_plan( + def pre_list_backups( self, - request: backupplan.UpdateBackupPlanRequest, + request: backupvault.ListBackupsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - backupplan.UpdateBackupPlanRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for update_backup_plan + ) -> Tuple[backupvault.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 BackupDR server. """ return request, metadata - def post_update_backup_plan( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_backup_plan + def post_list_backups( + self, response: backupvault.ListBackupsResponse + ) -> backupvault.ListBackupsResponse: + """Post-rpc interceptor for list_backups - DEPRECATED. Please use the `post_update_backup_plan_with_metadata` + 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 BackupDR server but before - it is returned to user code. This `post_update_backup_plan` interceptor runs - before the `post_update_backup_plan_with_metadata` interceptor. + it is returned to user code. This `post_list_backups` interceptor runs + before the `post_list_backups_with_metadata` interceptor. """ return response - def post_update_backup_plan_with_metadata( + def post_list_backups_with_metadata( self, - response: operations_pb2.Operation, + response: backupvault.ListBackupsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_backup_plan + ) -> Tuple[ + backupvault.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 BackupDR server but before it is returned to user code. - We recommend only using this `post_update_backup_plan_with_metadata` - interceptor in new development instead of the `post_update_backup_plan` interceptor. - When both interceptors are used, this `post_update_backup_plan_with_metadata` interceptor runs after the - `post_update_backup_plan` interceptor. The (possibly modified) response returned by - `post_update_backup_plan` will be passed to - `post_update_backup_plan_with_metadata`. + 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_update_backup_plan_association( + def pre_list_backup_vaults( self, - request: backupplanassociation.UpdateBackupPlanAssociationRequest, + request: backupvault.ListBackupVaultsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupplanassociation.UpdateBackupPlanAssociationRequest, - Sequence[Tuple[str, Union[str, bytes]]], + backupvault.ListBackupVaultsRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for update_backup_plan_association + """Pre-rpc interceptor for list_backup_vaults Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_update_backup_plan_association( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_backup_plan_association + def post_list_backup_vaults( + self, response: backupvault.ListBackupVaultsResponse + ) -> backupvault.ListBackupVaultsResponse: + """Post-rpc interceptor for list_backup_vaults - DEPRECATED. Please use the `post_update_backup_plan_association_with_metadata` + DEPRECATED. Please use the `post_list_backup_vaults_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_update_backup_plan_association` interceptor runs - before the `post_update_backup_plan_association_with_metadata` interceptor. + it is returned to user code. This `post_list_backup_vaults` interceptor runs + before the `post_list_backup_vaults_with_metadata` interceptor. """ return response - def post_update_backup_plan_association_with_metadata( + def post_list_backup_vaults_with_metadata( self, - response: operations_pb2.Operation, + response: backupvault.ListBackupVaultsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_backup_plan_association + ) -> Tuple[ + backupvault.ListBackupVaultsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_backup_vaults Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_update_backup_plan_association_with_metadata` - interceptor in new development instead of the `post_update_backup_plan_association` interceptor. - When both interceptors are used, this `post_update_backup_plan_association_with_metadata` interceptor runs after the - `post_update_backup_plan_association` interceptor. The (possibly modified) response returned by - `post_update_backup_plan_association` will be passed to - `post_update_backup_plan_association_with_metadata`. + We recommend only using this `post_list_backup_vaults_with_metadata` + interceptor in new development instead of the `post_list_backup_vaults` interceptor. + When both interceptors are used, this `post_list_backup_vaults_with_metadata` interceptor runs after the + `post_list_backup_vaults` interceptor. The (possibly modified) response returned by + `post_list_backup_vaults` will be passed to + `post_list_backup_vaults_with_metadata`. """ return response, metadata - def pre_update_backup_vault( + def pre_list_binding_matching_resources( self, - request: backupvault.UpdateBackupVaultRequest, + request: bindingmatchingresource.ListBindingMatchingResourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupvault.UpdateBackupVaultRequest, Sequence[Tuple[str, Union[str, bytes]]] + bindingmatchingresource.ListBindingMatchingResourcesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for update_backup_vault + """Pre-rpc interceptor for list_binding_matching_resources Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_update_backup_vault( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_backup_vault + def post_list_binding_matching_resources( + self, response: bindingmatchingresource.ListBindingMatchingResourcesResponse + ) -> bindingmatchingresource.ListBindingMatchingResourcesResponse: + """Post-rpc interceptor for list_binding_matching_resources - DEPRECATED. Please use the `post_update_backup_vault_with_metadata` + DEPRECATED. Please use the `post_list_binding_matching_resources_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_update_backup_vault` interceptor runs - before the `post_update_backup_vault_with_metadata` interceptor. + it is returned to user code. This `post_list_binding_matching_resources` interceptor runs + before the `post_list_binding_matching_resources_with_metadata` interceptor. """ return response - def post_update_backup_vault_with_metadata( + def post_list_binding_matching_resources_with_metadata( self, - response: operations_pb2.Operation, + response: bindingmatchingresource.ListBindingMatchingResourcesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_backup_vault + ) -> Tuple[ + bindingmatchingresource.ListBindingMatchingResourcesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_binding_matching_resources Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_update_backup_vault_with_metadata` - interceptor in new development instead of the `post_update_backup_vault` interceptor. - When both interceptors are used, this `post_update_backup_vault_with_metadata` interceptor runs after the - `post_update_backup_vault` interceptor. The (possibly modified) response returned by - `post_update_backup_vault` will be passed to - `post_update_backup_vault_with_metadata`. + We recommend only using this `post_list_binding_matching_resources_with_metadata` + interceptor in new development instead of the `post_list_binding_matching_resources` interceptor. + When both interceptors are used, this `post_list_binding_matching_resources_with_metadata` interceptor runs after the + `post_list_binding_matching_resources` interceptor. The (possibly modified) response returned by + `post_list_binding_matching_resources` will be passed to + `post_list_binding_matching_resources_with_metadata`. """ return response, metadata - def pre_update_data_source( + def pre_list_data_source_references( self, - request: backupvault.UpdateDataSourceRequest, + request: datasourcereference.ListDataSourceReferencesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupvault.UpdateDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + datasourcereference.ListDataSourceReferencesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for update_data_source + """Pre-rpc interceptor for list_data_source_references Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_update_data_source( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_data_source + def post_list_data_source_references( + self, response: datasourcereference.ListDataSourceReferencesResponse + ) -> datasourcereference.ListDataSourceReferencesResponse: + """Post-rpc interceptor for list_data_source_references - DEPRECATED. Please use the `post_update_data_source_with_metadata` + DEPRECATED. Please use the `post_list_data_source_references_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_update_data_source` interceptor runs - before the `post_update_data_source_with_metadata` interceptor. + it is returned to user code. This `post_list_data_source_references` interceptor runs + before the `post_list_data_source_references_with_metadata` interceptor. """ return response - def post_update_data_source_with_metadata( + def post_list_data_source_references_with_metadata( self, - response: operations_pb2.Operation, + response: datasourcereference.ListDataSourceReferencesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_data_source + ) -> Tuple[ + datasourcereference.ListDataSourceReferencesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_data_source_references Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_update_data_source_with_metadata` - interceptor in new development instead of the `post_update_data_source` interceptor. - When both interceptors are used, this `post_update_data_source_with_metadata` interceptor runs after the - `post_update_data_source` interceptor. The (possibly modified) response returned by - `post_update_data_source` will be passed to - `post_update_data_source_with_metadata`. + We recommend only using this `post_list_data_source_references_with_metadata` + interceptor in new development instead of the `post_list_data_source_references` interceptor. + When both interceptors are used, this `post_list_data_source_references_with_metadata` interceptor runs after the + `post_list_data_source_references` interceptor. The (possibly modified) response returned by + `post_list_data_source_references` will be passed to + `post_list_data_source_references_with_metadata`. """ return response, metadata - def pre_get_location( + def pre_list_data_sources( self, - request: locations_pb2.GetLocationRequest, + request: backupvault.ListDataSourcesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + backupvault.ListDataSourcesRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for get_location + """Pre-rpc interceptor for list_data_sources Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location + def post_list_data_sources( + self, response: backupvault.ListDataSourcesResponse + ) -> backupvault.ListDataSourcesResponse: + """Post-rpc interceptor for list_data_sources - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_data_sources_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. + it is returned to user code. This `post_list_data_sources` interceptor runs + before the `post_list_data_sources_with_metadata` interceptor. """ return response - def pre_list_locations( + def post_list_data_sources_with_metadata( self, - request: locations_pb2.ListLocationsRequest, + response: backupvault.ListDataSourcesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + backupvault.ListDataSourcesResponse, 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 BackupDR server. - """ - return request, metadata + """Post-rpc interceptor for list_data_sources - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. - Override in a subclass to manipulate the response - after it is returned by the BackupDR server but before - it is returned to user code. + We recommend only using this `post_list_data_sources_with_metadata` + interceptor in new development instead of the `post_list_data_sources` interceptor. + When both interceptors are used, this `post_list_data_sources_with_metadata` interceptor runs after the + `post_list_data_sources` interceptor. The (possibly modified) response returned by + `post_list_data_sources` will be passed to + `post_list_data_sources_with_metadata`. """ - return response + return response, metadata - def pre_get_iam_policy( + def pre_list_management_servers( self, - request: iam_policy_pb2.GetIamPolicyRequest, + request: backupdr.ListManagementServersRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + backupdr.ListManagementServersRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for get_iam_policy + """Pre-rpc interceptor for list_management_servers Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: - """Post-rpc interceptor for get_iam_policy + def post_list_management_servers( + self, response: backupdr.ListManagementServersResponse + ) -> backupdr.ListManagementServersResponse: + """Post-rpc interceptor for list_management_servers - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_management_servers_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. + it is returned to user code. This `post_list_management_servers` interceptor runs + before the `post_list_management_servers_with_metadata` interceptor. """ return response - def pre_set_iam_policy( + def post_list_management_servers_with_metadata( self, - request: iam_policy_pb2.SetIamPolicyRequest, + response: backupdr.ListManagementServersResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + backupdr.ListManagementServersResponse, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for set_iam_policy - - Override in a subclass to manipulate the request or metadata - before they are sent to the BackupDR server. - """ - return request, metadata + """Post-rpc interceptor for list_management_servers - def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: - """Post-rpc interceptor for set_iam_policy + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. - Override in a subclass to manipulate the response - after it is returned by the BackupDR server but before - it is returned to user code. + We recommend only using this `post_list_management_servers_with_metadata` + interceptor in new development instead of the `post_list_management_servers` interceptor. + When both interceptors are used, this `post_list_management_servers_with_metadata` interceptor runs after the + `post_list_management_servers` interceptor. The (possibly modified) response returned by + `post_list_management_servers` will be passed to + `post_list_management_servers_with_metadata`. """ - return response + return response, metadata - def pre_test_iam_permissions( + def pre_list_restore_template_executions( self, - request: iam_policy_pb2.TestIamPermissionsRequest, + request: restore_template_execution.ListRestoreTemplateExecutionsRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - iam_policy_pb2.TestIamPermissionsRequest, + restore_template_execution.ListRestoreTemplateExecutionsRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for test_iam_permissions + """Pre-rpc interceptor for list_restore_template_executions Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_test_iam_permissions( - self, response: iam_policy_pb2.TestIamPermissionsResponse - ) -> iam_policy_pb2.TestIamPermissionsResponse: - """Post-rpc interceptor for test_iam_permissions + def post_list_restore_template_executions( + self, response: restore_template_execution.ListRestoreTemplateExecutionsResponse + ) -> restore_template_execution.ListRestoreTemplateExecutionsResponse: + """Post-rpc interceptor for list_restore_template_executions - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_restore_template_executions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. + it is returned to user code. This `post_list_restore_template_executions` interceptor runs + before the `post_list_restore_template_executions_with_metadata` interceptor. """ return response - def pre_cancel_operation( + def post_list_restore_template_executions_with_metadata( self, - request: operations_pb2.CancelOperationRequest, + response: restore_template_execution.ListRestoreTemplateExecutionsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + restore_template_execution.ListRestoreTemplateExecutionsResponse, + 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 BackupDR server. - """ - return request, metadata + """Post-rpc interceptor for list_restore_template_executions - def post_cancel_operation(self, response: None) -> None: - """Post-rpc interceptor for cancel_operation + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. - Override in a subclass to manipulate the response - after it is returned by the BackupDR server but before - it is returned to user code. + We recommend only using this `post_list_restore_template_executions_with_metadata` + interceptor in new development instead of the `post_list_restore_template_executions` interceptor. + When both interceptors are used, this `post_list_restore_template_executions_with_metadata` interceptor runs after the + `post_list_restore_template_executions` interceptor. The (possibly modified) response returned by + `post_list_restore_template_executions` will be passed to + `post_list_restore_template_executions_with_metadata`. """ - return response + return response, metadata - def pre_delete_operation( + def pre_list_restore_templates( self, - request: operations_pb2.DeleteOperationRequest, + request: restore_template.ListRestoreTemplatesRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + restore_template.ListRestoreTemplatesRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for delete_operation + """Pre-rpc interceptor for list_restore_templates Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_delete_operation(self, response: None) -> None: - """Post-rpc interceptor for delete_operation + def post_list_restore_templates( + self, response: restore_template.ListRestoreTemplatesResponse + ) -> restore_template.ListRestoreTemplatesResponse: + """Post-rpc interceptor for list_restore_templates - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_restore_templates_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. + it is returned to user code. This `post_list_restore_templates` interceptor runs + before the `post_list_restore_templates_with_metadata` interceptor. """ return response - def pre_get_operation( + def post_list_restore_templates_with_metadata( self, - request: operations_pb2.GetOperationRequest, + response: restore_template.ListRestoreTemplatesResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + restore_template.ListRestoreTemplatesResponse, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for get_operation + """Post-rpc interceptor for list_restore_templates + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_restore_templates_with_metadata` + interceptor in new development instead of the `post_list_restore_templates` interceptor. + When both interceptors are used, this `post_list_restore_templates_with_metadata` interceptor runs after the + `post_list_restore_templates` interceptor. The (possibly modified) response returned by + `post_list_restore_templates` will be passed to + `post_list_restore_templates_with_metadata`. + """ + return response, metadata + + def pre_list_restore_verification_plan_associations( + self, + request: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_restore_verification_plan_associations Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation + def post_list_restore_verification_plan_associations( + self, + response: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + ) -> restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse: + """Post-rpc interceptor for list_restore_verification_plan_associations - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_restore_verification_plan_associations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. + it is returned to user code. This `post_list_restore_verification_plan_associations` interceptor runs + before the `post_list_restore_verification_plan_associations_with_metadata` interceptor. """ return response - def pre_list_operations( + def post_list_restore_verification_plan_associations_with_metadata( self, - request: operations_pb2.ListOperationsRequest, + response: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for list_operations + """Post-rpc interceptor for list_restore_verification_plan_associations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_restore_verification_plan_associations_with_metadata` + interceptor in new development instead of the `post_list_restore_verification_plan_associations` interceptor. + When both interceptors are used, this `post_list_restore_verification_plan_associations_with_metadata` interceptor runs after the + `post_list_restore_verification_plan_associations` interceptor. The (possibly modified) response returned by + `post_list_restore_verification_plan_associations` will be passed to + `post_list_restore_verification_plan_associations_with_metadata`. + """ + return response, metadata + + def pre_list_restore_verification_plans( + self, + request: restore_verification_plan.ListRestoreVerificationPlansRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan.ListRestoreVerificationPlansRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_restore_verification_plans Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations + def post_list_restore_verification_plans( + self, response: restore_verification_plan.ListRestoreVerificationPlansResponse + ) -> restore_verification_plan.ListRestoreVerificationPlansResponse: + """Post-rpc interceptor for list_restore_verification_plans - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_list_restore_verification_plans_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. + it is returned to user code. This `post_list_restore_verification_plans` interceptor runs + before the `post_list_restore_verification_plans_with_metadata` interceptor. """ return response + def post_list_restore_verification_plans_with_metadata( + self, + response: restore_verification_plan.ListRestoreVerificationPlansResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan.ListRestoreVerificationPlansResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_restore_verification_plans -@dataclasses.dataclass -class BackupDRRestStub: - _session: AuthorizedSession - _host: str - _interceptor: BackupDRRestInterceptor + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + We recommend only using this `post_list_restore_verification_plans_with_metadata` + interceptor in new development instead of the `post_list_restore_verification_plans` interceptor. + When both interceptors are used, this `post_list_restore_verification_plans_with_metadata` interceptor runs after the + `post_list_restore_verification_plans` interceptor. The (possibly modified) response returned by + `post_list_restore_verification_plans` will be passed to + `post_list_restore_verification_plans_with_metadata`. + """ + return response, metadata -class BackupDRRestTransport(_BaseBackupDRRestTransport): - """REST backend synchronous transport for BackupDR. + def pre_restore_backup( + self, + request: backupvault.RestoreBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.RestoreBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for restore_backup - The BackupDR Service + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR 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_restore_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for restore_backup - It sends JSON representations of protocol buffers over HTTP/1.1 - """ + DEPRECATED. Please use the `post_restore_backup_with_metadata` + interceptor instead. - def __init__( + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_restore_backup` interceptor runs + before the `post_restore_backup_with_metadata` interceptor. + """ + return response + + def post_restore_backup_with_metadata( self, - *, - host: str = "backupdr.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[BackupDRRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. + 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 restore_backup - Args: - host (Optional[str]): - The hostname to connect to (default: 'backupdr.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 BackupDR 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[BackupDRRestInterceptor]): 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_restore_backup_with_metadata` + interceptor in new development instead of the `post_restore_backup` interceptor. + When both interceptors are used, this `post_restore_backup_with_metadata` interceptor runs after the + `post_restore_backup` interceptor. The (possibly modified) response returned by + `post_restore_backup` will be passed to + `post_restore_backup_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 BackupDRRestInterceptor() - self._prep_wrapped_messages(client_info) + return response, metadata - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. + def pre_run_restore_template( + self, + request: restore_template.RunRestoreTemplateRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template.RunRestoreTemplateRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for run_restore_template - This property caches on the instance; repeated calls return the same - client. + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. """ - # 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": "/v1/{name=projects/*/locations/*/operations/*}:cancel", - "body": "*", - }, - ], - "google.longrunning.Operations.DeleteOperation": [ - { - "method": "delete", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ], - "google.longrunning.Operations.GetOperation": [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*/operations/*}", - }, - ], - "google.longrunning.Operations.ListOperations": [ - { - "method": "get", - "uri": "/v1/{name=projects/*/locations/*}/operations", - }, - ], - } + return request, metadata + + def post_run_restore_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for run_restore_template + + DEPRECATED. Please use the `post_run_restore_template_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_run_restore_template` interceptor runs + before the `post_run_restore_template_with_metadata` interceptor. + """ + return response + + def post_run_restore_template_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 run_restore_template + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_run_restore_template_with_metadata` + interceptor in new development instead of the `post_run_restore_template` interceptor. + When both interceptors are used, this `post_run_restore_template_with_metadata` interceptor runs after the + `post_run_restore_template` interceptor. The (possibly modified) response returned by + `post_run_restore_template` will be passed to + `post_run_restore_template_with_metadata`. + """ + return response, metadata + + def pre_trigger_backup( + self, + request: backupplanassociation.TriggerBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.TriggerBackupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for trigger_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_trigger_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for trigger_backup + + DEPRECATED. Please use the `post_trigger_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_trigger_backup` interceptor runs + before the `post_trigger_backup_with_metadata` interceptor. + """ + return response + + def post_trigger_backup_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 trigger_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_trigger_backup_with_metadata` + interceptor in new development instead of the `post_trigger_backup` interceptor. + When both interceptors are used, this `post_trigger_backup_with_metadata` interceptor runs after the + `post_trigger_backup` interceptor. The (possibly modified) response returned by + `post_trigger_backup` will be passed to + `post_trigger_backup_with_metadata`. + """ + return response, metadata + + def pre_trigger_restore_cleanup( + self, + request: restore_template_execution.TriggerRestoreCleanupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template_execution.TriggerRestoreCleanupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for trigger_restore_cleanup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_trigger_restore_cleanup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for trigger_restore_cleanup + + DEPRECATED. Please use the `post_trigger_restore_cleanup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_trigger_restore_cleanup` interceptor runs + before the `post_trigger_restore_cleanup_with_metadata` interceptor. + """ + return response + + def post_trigger_restore_cleanup_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 trigger_restore_cleanup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_trigger_restore_cleanup_with_metadata` + interceptor in new development instead of the `post_trigger_restore_cleanup` interceptor. + When both interceptors are used, this `post_trigger_restore_cleanup_with_metadata` interceptor runs after the + `post_trigger_restore_cleanup` interceptor. The (possibly modified) response returned by + `post_trigger_restore_cleanup` will be passed to + `post_trigger_restore_cleanup_with_metadata`. + """ + return response, metadata + + def pre_trigger_restore_verification( + self, + request: restore_verification_plan_association.TriggerRestoreVerificationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan_association.TriggerRestoreVerificationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for trigger_restore_verification + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_trigger_restore_verification( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for trigger_restore_verification + + DEPRECATED. Please use the `post_trigger_restore_verification_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_trigger_restore_verification` interceptor runs + before the `post_trigger_restore_verification_with_metadata` interceptor. + """ + return response + + def post_trigger_restore_verification_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 trigger_restore_verification + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_trigger_restore_verification_with_metadata` + interceptor in new development instead of the `post_trigger_restore_verification` interceptor. + When both interceptors are used, this `post_trigger_restore_verification_with_metadata` interceptor runs after the + `post_trigger_restore_verification` interceptor. The (possibly modified) response returned by + `post_trigger_restore_verification` will be passed to + `post_trigger_restore_verification_with_metadata`. + """ + return response, metadata + + def pre_update_auto_protection_policy( + self, + request: autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_auto_protection_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_auto_protection_policy( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_auto_protection_policy + + DEPRECATED. Please use the `post_update_auto_protection_policy_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_auto_protection_policy` interceptor runs + before the `post_update_auto_protection_policy_with_metadata` interceptor. + """ + return response + + def post_update_auto_protection_policy_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_auto_protection_policy + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_auto_protection_policy_with_metadata` + interceptor in new development instead of the `post_update_auto_protection_policy` interceptor. + When both interceptors are used, this `post_update_auto_protection_policy_with_metadata` interceptor runs after the + `post_update_auto_protection_policy` interceptor. The (possibly modified) response returned by + `post_update_auto_protection_policy` will be passed to + `post_update_auto_protection_policy_with_metadata`. + """ + return response, metadata + + def pre_update_backup( + self, + request: backupvault.UpdateBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.UpdateBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_backup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup + + DEPRECATED. Please use the `post_update_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_backup` interceptor runs + before the `post_update_backup_with_metadata` interceptor. + """ + return response + + def post_update_backup_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_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_backup_with_metadata` + interceptor in new development instead of the `post_update_backup` interceptor. + When both interceptors are used, this `post_update_backup_with_metadata` interceptor runs after the + `post_update_backup` interceptor. The (possibly modified) response returned by + `post_update_backup` will be passed to + `post_update_backup_with_metadata`. + """ + return response, metadata + + def pre_update_backup_plan( + self, + request: backupplan.UpdateBackupPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplan.UpdateBackupPlanRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_backup_plan + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_backup_plan( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup_plan + + DEPRECATED. Please use the `post_update_backup_plan_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_backup_plan` interceptor runs + before the `post_update_backup_plan_with_metadata` interceptor. + """ + return response + + def post_update_backup_plan_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_backup_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_backup_plan_with_metadata` + interceptor in new development instead of the `post_update_backup_plan` interceptor. + When both interceptors are used, this `post_update_backup_plan_with_metadata` interceptor runs after the + `post_update_backup_plan` interceptor. The (possibly modified) response returned by + `post_update_backup_plan` will be passed to + `post_update_backup_plan_with_metadata`. + """ + return response, metadata + + def pre_update_backup_plan_association( + self, + request: backupplanassociation.UpdateBackupPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.UpdateBackupPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_backup_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_backup_plan_association( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup_plan_association + + DEPRECATED. Please use the `post_update_backup_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_backup_plan_association` interceptor runs + before the `post_update_backup_plan_association_with_metadata` interceptor. + """ + return response + + def post_update_backup_plan_association_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_backup_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_backup_plan_association_with_metadata` + interceptor in new development instead of the `post_update_backup_plan_association` interceptor. + When both interceptors are used, this `post_update_backup_plan_association_with_metadata` interceptor runs after the + `post_update_backup_plan_association` interceptor. The (possibly modified) response returned by + `post_update_backup_plan_association` will be passed to + `post_update_backup_plan_association_with_metadata`. + """ + return response, metadata + + def pre_update_backup_vault( + self, + request: backupvault.UpdateBackupVaultRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.UpdateBackupVaultRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_backup_vault + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_backup_vault( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_backup_vault + + DEPRECATED. Please use the `post_update_backup_vault_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_backup_vault` interceptor runs + before the `post_update_backup_vault_with_metadata` interceptor. + """ + return response + + def post_update_backup_vault_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_backup_vault + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_backup_vault_with_metadata` + interceptor in new development instead of the `post_update_backup_vault` interceptor. + When both interceptors are used, this `post_update_backup_vault_with_metadata` interceptor runs after the + `post_update_backup_vault` interceptor. The (possibly modified) response returned by + `post_update_backup_vault` will be passed to + `post_update_backup_vault_with_metadata`. + """ + return response, metadata + + def pre_update_data_source( + self, + request: backupvault.UpdateDataSourceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.UpdateDataSourceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_data_source + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_data_source( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_data_source + + DEPRECATED. Please use the `post_update_data_source_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_data_source` interceptor runs + before the `post_update_data_source_with_metadata` interceptor. + """ + return response + + def post_update_data_source_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_data_source + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_data_source_with_metadata` + interceptor in new development instead of the `post_update_data_source` interceptor. + When both interceptors are used, this `post_update_data_source_with_metadata` interceptor runs after the + `post_update_data_source` interceptor. The (possibly modified) response returned by + `post_update_data_source` will be passed to + `post_update_data_source_with_metadata`. + """ + return response, metadata + + def pre_update_restore_template( + self, + request: gcb_restore_template.UpdateRestoreTemplateRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcb_restore_template.UpdateRestoreTemplateRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_restore_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_restore_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_restore_template + + DEPRECATED. Please use the `post_update_restore_template_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_restore_template` interceptor runs + before the `post_update_restore_template_with_metadata` interceptor. + """ + return response + + def post_update_restore_template_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_restore_template + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_restore_template_with_metadata` + interceptor in new development instead of the `post_update_restore_template` interceptor. + When both interceptors are used, this `post_update_restore_template_with_metadata` interceptor runs after the + `post_update_restore_template` interceptor. The (possibly modified) response returned by + `post_update_restore_template` will be passed to + `post_update_restore_template_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 BackupDR 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 BackupDR 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 BackupDR 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 BackupDR server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + iam_policy_pb2.TestIamPermissionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the BackupDR 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 BackupDR 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 BackupDR 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 BackupDR 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 BackupDR 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 BackupDR 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 BackupDR 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 BackupDR 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 BackupDR server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class BackupDRRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BackupDRRestInterceptor + + +class BackupDRRestTransport(_BaseBackupDRRestTransport): + """REST backend synchronous transport for BackupDR. + + The BackupDR Service + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "backupdr.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[BackupDRRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'backupdr.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[BackupDRRestInterceptor]): 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 BackupDRRestInterceptor() + 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": "/v1/{name=projects/*/locations/*/operations/*}:cancel", + "body": "*", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _CreateAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicy, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateAutoProtectionPolicy") + + @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: autoprotectionpolicy.CreateAutoProtectionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create auto protection + policy method over HTTP. + + Args: + request (~.autoprotectionpolicy.CreateAutoProtectionPolicyRequest): + The request object. Request message for creating an + AutoProtectionPolicy. + 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 = _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_create_auto_protection_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicy, + "_BaseCreateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.CreateAutoProtectionPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateAutoProtectionPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateAutoProtectionPolicy._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_auto_protection_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_auto_protection_policy_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.backupdr_v1.BackupDRClient.create_auto_protection_policy", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateAutoProtectionPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAutoProtectionPolicyBinding( + _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicyBinding, + BackupDRRestStub, + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateAutoProtectionPolicyBinding") + + @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: autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create auto protection + policy binding method over HTTP. + + Args: + request (~.autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest): + The request object. Request message for creating an + AutoProtectionPolicyBinding. + 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 = _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicyBinding._get_http_options() + request, metadata = ( + self._interceptor.pre_create_auto_protection_policy_binding( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateAutoProtectionPolicyBinding, + "_BaseCreateAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.CreateAutoProtectionPolicyBinding", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateAutoProtectionPolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._CreateAutoProtectionPolicyBinding._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_auto_protection_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_auto_protection_policy_binding_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.backupdr_v1.BackupDRClient.create_auto_protection_policy_binding", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateAutoProtectionPolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateBackupPlan( + _BaseBackupDRRestTransport._BaseCreateBackupPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateBackupPlan") + + @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: backupplan.CreateBackupPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create backup plan method over HTTP. + + Args: + request (~.backupplan.CreateBackupPlanRequest): + The request object. The request message for creating a ``BackupPlan``. + 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 = ( + _BaseBackupDRRestTransport._BaseCreateBackupPlan._get_http_options() + ) + request, metadata = self._interceptor.pre_create_backup_plan( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateBackupPlan, + "_BaseCreateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.CreateBackupPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateBackupPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateBackupPlan._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_backup_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_backup_plan_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.backupdr_v1.BackupDRClient.create_backup_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateBackupPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateBackupPlanAssociation( + _BaseBackupDRRestTransport._BaseCreateBackupPlanAssociation, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateBackupPlanAssociation") + + @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: backupplanassociation.CreateBackupPlanAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create backup plan + association method over HTTP. + + Args: + request (~.backupplanassociation.CreateBackupPlanAssociationRequest): + The request object. Request message for creating a backup + plan. + 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 = _BaseBackupDRRestTransport._BaseCreateBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_create_backup_plan_association( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateBackupPlanAssociation, + "_BaseCreateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.CreateBackupPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateBackupPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateBackupPlanAssociation._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_backup_plan_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_backup_plan_association_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.backupdr_v1.BackupDRClient.create_backup_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateBackupPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateBackupVault( + _BaseBackupDRRestTransport._BaseCreateBackupVault, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateBackupVault") + + @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: backupvault.CreateBackupVaultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create backup vault method over HTTP. + + Args: + request (~.backupvault.CreateBackupVaultRequest): + The request object. Message for creating a BackupVault. + 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 = ( + _BaseBackupDRRestTransport._BaseCreateBackupVault._get_http_options() + ) + request, metadata = self._interceptor.pre_create_backup_vault( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateBackupVault, + "_BaseCreateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.CreateBackupVault", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateBackupVault", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateBackupVault._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_backup_vault(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_backup_vault_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.backupdr_v1.BackupDRClient.create_backup_vault", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateBackupVault", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateManagementServer( + _BaseBackupDRRestTransport._BaseCreateManagementServer, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateManagementServer") + + @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: backupdr.CreateManagementServerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create management server method over HTTP. + + Args: + request (~.backupdr.CreateManagementServerRequest): + The request object. Request message for creating a + management server instance. + 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 = _BaseBackupDRRestTransport._BaseCreateManagementServer._get_http_options() + request, metadata = self._interceptor.pre_create_management_server( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateManagementServer, + "_BaseCreateManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.CreateManagementServer", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateManagementServer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateManagementServer._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_management_server(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_management_server_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.backupdr_v1.BackupDRClient.create_management_server", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateManagementServer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateRestoreTemplate( + _BaseBackupDRRestTransport._BaseCreateRestoreTemplate, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateRestoreTemplate") + + @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: gcb_restore_template.CreateRestoreTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create restore template method over HTTP. + + Args: + request (~.gcb_restore_template.CreateRestoreTemplateRequest): + The request object. Request message for creating a + RestoreTemplate instance. + 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 = _BaseBackupDRRestTransport._BaseCreateRestoreTemplate._get_http_options() + request, metadata = self._interceptor.pre_create_restore_template( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateRestoreTemplate, + "_BaseCreateRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.CreateRestoreTemplate", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateRestoreTemplate", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateRestoreTemplate._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_restore_template(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_restore_template_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.backupdr_v1.BackupDRClient.create_restore_template", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateRestoreTemplate", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateRestoreVerificationPlan( + _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.CreateRestoreVerificationPlan") + + @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: gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create restore + verification plan method over HTTP. + + Args: + request (~.gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest): + The request object. The request message for creating a + ``RestoreVerificationPlan``. + 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 = _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlan._get_http_options() + request, metadata = self._interceptor.pre_create_restore_verification_plan( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlan, + "_BaseCreateRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.CreateRestoreVerificationPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateRestoreVerificationPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._CreateRestoreVerificationPlan._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_restore_verification_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_restore_verification_plan_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.backupdr_v1.BackupDRClient.create_restore_verification_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateRestoreVerificationPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateRestoreVerificationPlanAssociation( + _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlanAssociation, + BackupDRRestStub, + ): + def __hash__(self): + return hash( + "BackupDRRestTransport.CreateRestoreVerificationPlanAssociation" + ) + + @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: gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create restore + verification plan association method over HTTP. + + Args: + request (~.gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest): + The request object. Request message for + CreateRestoreVerificationPlanAssociation. + 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 = _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlanAssociation._get_http_options() + request, metadata = ( + self._interceptor.pre_create_restore_verification_plan_association( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlanAssociation, + "_BaseCreateRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.CreateRestoreVerificationPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateRestoreVerificationPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._CreateRestoreVerificationPlanAssociation._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_restore_verification_plan_association( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_restore_verification_plan_association_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.backupdr_v1.BackupDRClient.create_restore_verification_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "CreateRestoreVerificationPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteAutoProtectionPolicy") + + @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: autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete auto protection + policy method over HTTP. + + Args: + request (~.autoprotectionpolicy.DeleteAutoProtectionPolicyRequest): + The request object. Request message for deleting an + AutoProtectionPolicy. + 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 = _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_delete_auto_protection_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy, + "_BaseDeleteAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.DeleteAutoProtectionPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteAutoProtectionPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteAutoProtectionPolicy._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_auto_protection_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_auto_protection_policy_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.backupdr_v1.BackupDRClient.delete_auto_protection_policy", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteAutoProtectionPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBackup(_BaseBackupDRRestTransport._BaseDeleteBackup, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.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: backupvault.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 (~.backupvault.DeleteBackupRequest): + The request object. Message for deleting a Backup. + 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 = ( + _BaseBackupDRRestTransport._BaseDeleteBackup._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_backup(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteBackup, + "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.DeleteBackup", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._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.backupdr_v1.BackupDRClient.delete_backup", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBackupPlan( + _BaseBackupDRRestTransport._BaseDeleteBackupPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteBackupPlan") + + @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: backupplan.DeleteBackupPlanRequest, + *, + 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 plan method over HTTP. + + Args: + request (~.backupplan.DeleteBackupPlanRequest): + The request object. The request message for deleting a ``BackupPlan``. + 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 = ( + _BaseBackupDRRestTransport._BaseDeleteBackupPlan._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_backup_plan( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteBackupPlan, + "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.DeleteBackupPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteBackupPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteBackupPlan._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_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_backup_plan_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.backupdr_v1.BackupDRClient.delete_backup_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteBackupPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBackupPlanAssociation( + _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteBackupPlanAssociation") + + @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: backupplanassociation.DeleteBackupPlanAssociationRequest, + *, + 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 plan + association method over HTTP. + + Args: + request (~.backupplanassociation.DeleteBackupPlanAssociationRequest): + The request object. Request message for deleting a backup + plan association. + 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 = _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_delete_backup_plan_association( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, + "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.DeleteBackupPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteBackupPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteBackupPlanAssociation._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_plan_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_backup_plan_association_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.backupdr_v1.BackupDRClient.delete_backup_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteBackupPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBackupVault( + _BaseBackupDRRestTransport._BaseDeleteBackupVault, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteBackupVault") + + @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: backupvault.DeleteBackupVaultRequest, + *, + 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 vault method over HTTP. + + Args: + request (~.backupvault.DeleteBackupVaultRequest): + The request object. Message for deleting a BackupVault. + 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 = ( + _BaseBackupDRRestTransport._BaseDeleteBackupVault._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_backup_vault( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteBackupVault, + "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.DeleteBackupVault", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteBackupVault", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteBackupVault._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_vault(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_backup_vault_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.backupdr_v1.BackupDRClient.delete_backup_vault", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteBackupVault", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteManagementServer( + _BaseBackupDRRestTransport._BaseDeleteManagementServer, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteManagementServer") + + @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: backupdr.DeleteManagementServerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete management server method over HTTP. + + Args: + request (~.backupdr.DeleteManagementServerRequest): + The request object. Request message for deleting a + management server instance. + 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 = _BaseBackupDRRestTransport._BaseDeleteManagementServer._get_http_options() + request, metadata = self._interceptor.pre_delete_management_server( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteManagementServer, + "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.DeleteManagementServer", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteManagementServer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteManagementServer._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_management_server(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_management_server_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.backupdr_v1.BackupDRClient.delete_management_server", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteManagementServer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteRestoreTemplate( + _BaseBackupDRRestTransport._BaseDeleteRestoreTemplate, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteRestoreTemplate") + + @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: restore_template.DeleteRestoreTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete restore template method over HTTP. + + Args: + request (~.restore_template.DeleteRestoreTemplateRequest): + The request object. Request message for deleting a + RestoreTemplate instance. + 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 = _BaseBackupDRRestTransport._BaseDeleteRestoreTemplate._get_http_options() + request, metadata = self._interceptor.pre_delete_restore_template( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteRestoreTemplate, + "_BaseDeleteRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.DeleteRestoreTemplate", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteRestoreTemplate", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteRestoreTemplate._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_restore_template(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_restore_template_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.backupdr_v1.BackupDRClient.delete_restore_template", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteRestoreTemplate", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteRestoreVerificationPlan( + _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.DeleteRestoreVerificationPlan") + + @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: restore_verification_plan.DeleteRestoreVerificationPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete restore + verification plan method over HTTP. + + Args: + request (~.restore_verification_plan.DeleteRestoreVerificationPlanRequest): + The request object. The request message for deleting a + ``RestoreVerificationPlan``. + 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 = _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlan._get_http_options() + request, metadata = self._interceptor.pre_delete_restore_verification_plan( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlan, + "_BaseDeleteRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.DeleteRestoreVerificationPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteRestoreVerificationPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._DeleteRestoreVerificationPlan._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_restore_verification_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_restore_verification_plan_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.backupdr_v1.BackupDRClient.delete_restore_verification_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteRestoreVerificationPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteRestoreVerificationPlanAssociation( + _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlanAssociation, + BackupDRRestStub, + ): + def __hash__(self): + return hash( + "BackupDRRestTransport.DeleteRestoreVerificationPlanAssociation" + ) + + @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: restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete restore + verification plan association method over HTTP. + + Args: + request (~.restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest): + The request object. Request message for + DeleteRestoreVerificationPlanAssociation. + 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 = _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlanAssociation._get_http_options() + request, metadata = ( + self._interceptor.pre_delete_restore_verification_plan_association( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlanAssociation, + "_BaseDeleteRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.DeleteRestoreVerificationPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteRestoreVerificationPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._DeleteRestoreVerificationPlanAssociation._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_restore_verification_plan_association( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_delete_restore_verification_plan_association_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.backupdr_v1.BackupDRClient.delete_restore_verification_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "DeleteRestoreVerificationPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchBackupPlanAssociationsForResourceType( + _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, + BackupDRRestStub, + ): + def __hash__(self): + return hash( + "BackupDRRestTransport.FetchBackupPlanAssociationsForResourceType" + ) + + @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: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: + r"""Call the fetch backup plan + associations for resource type method over HTTP. + + Args: + request (~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest): + The request object. Request for the + FetchBackupPlanAssociationsForResourceType + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: + Response for the + FetchBackupPlanAssociationsForResourceType + method. + + """ + + http_options = _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_backup_plan_associations_for_resource_type( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, + "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.FetchBackupPlanAssociationsForResourceType", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "FetchBackupPlanAssociationsForResourceType", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._FetchBackupPlanAssociationsForResourceType._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 = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + pb_resp = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = ( + self._interceptor.post_fetch_backup_plan_associations_for_resource_type( + resp + ) + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_fetch_backup_plan_associations_for_resource_type_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.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.backupdr_v1.BackupDRClient.fetch_backup_plan_associations_for_resource_type", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "FetchBackupPlanAssociationsForResourceType", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchBackupsForResourceType( + _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.FetchBackupsForResourceType") + + @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: backupvault.FetchBackupsForResourceTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.FetchBackupsForResourceTypeResponse: + r"""Call the fetch backups for + resource type method over HTTP. + + Args: + request (~.backupvault.FetchBackupsForResourceTypeRequest): + The request object. Request for the + FetchBackupsForResourceType method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.backupvault.FetchBackupsForResourceTypeResponse: + Response for the + FetchBackupsForResourceType method. + + """ + + http_options = _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType._get_http_options() + request, metadata = self._interceptor.pre_fetch_backups_for_resource_type( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, + "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.FetchBackupsForResourceType", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "FetchBackupsForResourceType", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._FetchBackupsForResourceType._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 = backupvault.FetchBackupsForResourceTypeResponse() + pb_resp = backupvault.FetchBackupsForResourceTypeResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_backups_for_resource_type(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_fetch_backups_for_resource_type_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + backupvault.FetchBackupsForResourceTypeResponse.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.backupdr_v1.BackupDRClient.fetch_backups_for_resource_type", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "FetchBackupsForResourceType", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchDataSourceReferencesForResourceType( + _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, + BackupDRRestStub, + ): + def __hash__(self): + return hash( + "BackupDRRestTransport.FetchDataSourceReferencesForResourceType" + ) + + @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: datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: + r"""Call the fetch data source + references for resource type method over HTTP. + + Args: + request (~.datasourcereference.FetchDataSourceReferencesForResourceTypeRequest): + The request object. Request for the + FetchDataSourceReferencesForResourceType + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: + Response for the + FetchDataSourceReferencesForResourceType + method. + + """ + + http_options = _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_data_source_references_for_resource_type( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, + "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.FetchDataSourceReferencesForResourceType", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "FetchDataSourceReferencesForResourceType", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._FetchDataSourceReferencesForResourceType._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 = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + pb_resp = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = ( + self._interceptor.post_fetch_data_source_references_for_resource_type( + resp + ) + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_fetch_data_source_references_for_resource_type_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.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.backupdr_v1.BackupDRClient.fetch_data_source_references_for_resource_type", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "FetchDataSourceReferencesForResourceType", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FetchUsableBackupVaults( + _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.FetchUsableBackupVaults") + + @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: backupvault.FetchUsableBackupVaultsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.FetchUsableBackupVaultsResponse: + r"""Call the fetch usable backup + vaults method over HTTP. + + Args: + request (~.backupvault.FetchUsableBackupVaultsRequest): + The request object. Request message for fetching usable + BackupVaults. + 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: + ~.backupvault.FetchUsableBackupVaultsResponse: + Response message for fetching usable + BackupVaults. + + """ + + http_options = _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults._get_http_options() + request, metadata = self._interceptor.pre_fetch_usable_backup_vaults( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, + "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.FetchUsableBackupVaults", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "FetchUsableBackupVaults", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._FetchUsableBackupVaults._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 = backupvault.FetchUsableBackupVaultsResponse() + pb_resp = backupvault.FetchUsableBackupVaultsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_usable_backup_vaults(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_fetch_usable_backup_vaults_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + backupvault.FetchUsableBackupVaultsResponse.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.backupdr_v1.BackupDRClient.fetch_usable_backup_vaults", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "FetchUsableBackupVaults", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetAutoProtectionPolicy") + + @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: autoprotectionpolicy.GetAutoProtectionPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicy.AutoProtectionPolicy: + r"""Call the get auto protection + policy method over HTTP. + + Args: + request (~.autoprotectionpolicy.GetAutoProtectionPolicyRequest): + The request object. Request message for getting an + AutoProtectionPolicy. + 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: + ~.autoprotectionpolicy.AutoProtectionPolicy: + An AutoprotectionPolicy is a policy + resource designed to automate backup + management, moving from manual + per-resource protection to a bulk + approach. The policy dynamically + discovers and applies a specified backup + plan to all eligible resources that + match its defined scope and criteria. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_auto_protection_policy( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy, + "_BaseGetAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.GetAutoProtectionPolicy", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetAutoProtectionPolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetAutoProtectionPolicy._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 = autoprotectionpolicy.AutoProtectionPolicy() + pb_resp = autoprotectionpolicy.AutoProtectionPolicy.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_auto_protection_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_auto_protection_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + autoprotectionpolicy.AutoProtectionPolicy.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.backupdr_v1.BackupDRClient.get_auto_protection_policy", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetAutoProtectionPolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAutoProtectionPolicyBinding( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetAutoProtectionPolicyBinding") + + @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: autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: + r"""Call the get auto protection + policy binding method over HTTP. + + Args: + request (~.autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest): + The request object. Request message for getting an + AutoProtectionPolicyBinding. + 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: + ~.autoprotectionpolicybinding.AutoProtectionPolicyBinding: + An AutoProtectionPolicyBinding (APPA) + acts as the bridge between an + AutoProtectionPolicy and the scope + (Project) where the policy should be + applied. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding._get_http_options() + request, metadata = ( + self._interceptor.pre_get_auto_protection_policy_binding( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding, + "_BaseGetAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.GetAutoProtectionPolicyBinding", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetAutoProtectionPolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._GetAutoProtectionPolicyBinding._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 = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + pb_resp = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_auto_protection_policy_binding(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_auto_protection_policy_binding_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + autoprotectionpolicybinding.AutoProtectionPolicyBinding.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.backupdr_v1.BackupDRClient.get_auto_protection_policy_binding", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetAutoProtectionPolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackup(_BaseBackupDRRestTransport._BaseGetBackup, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.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: backupvault.GetBackupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.Backup: + r"""Call the get backup method over HTTP. + + Args: + request (~.backupvault.GetBackupRequest): + The request object. Request message for getting a Backup. + 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: + ~.backupvault.Backup: + Message describing a Backup object. + """ + + http_options = _BaseBackupDRRestTransport._BaseGetBackup._get_http_options() + request, metadata = self._interceptor.pre_get_backup(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBackup, + "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.GetBackup", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._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 = backupvault.Backup() + pb_resp = backupvault.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 = backupvault.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.backupdr_v1.BackupDRClient.get_backup", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackupPlan( + _BaseBackupDRRestTransport._BaseGetBackupPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetBackupPlan") + + @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: backupplan.GetBackupPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.BackupPlan: + r"""Call the get backup plan method over HTTP. + + Args: + request (~.backupplan.GetBackupPlanRequest): + The request object. The request message for getting a ``BackupPlan``. + 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: + ~.backupplan.BackupPlan: + A ``BackupPlan`` specifies some common fields, such as + ``description`` as well as one or more ``BackupRule`` + messages. Each ``BackupRule`` has a retention policy and + defines a schedule by which the system is to perform + backup workloads. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetBackupPlan._get_http_options() + ) + request, metadata = self._interceptor.pre_get_backup_plan(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBackupPlan, + "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.GetBackupPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetBackupPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetBackupPlan._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 = backupplan.BackupPlan() + pb_resp = backupplan.BackupPlan.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_plan_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplan.BackupPlan.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.backupdr_v1.BackupDRClient.get_backup_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetBackupPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackupPlanAssociation( + _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetBackupPlanAssociation") + + @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: backupplanassociation.GetBackupPlanAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplanassociation.BackupPlanAssociation: + r"""Call the get backup plan + association method over HTTP. + + Args: + request (~.backupplanassociation.GetBackupPlanAssociationRequest): + The request object. Request message for getting a + BackupPlanAssociation resource. + 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: + ~.backupplanassociation.BackupPlanAssociation: + A BackupPlanAssociation represents a + single BackupPlanAssociation which + contains details like workload, backup + plan etc + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_get_backup_plan_association( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, + "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.GetBackupPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetBackupPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetBackupPlanAssociation._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 = backupplanassociation.BackupPlanAssociation() + pb_resp = backupplanassociation.BackupPlanAssociation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_plan_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_plan_association_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + backupplanassociation.BackupPlanAssociation.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.backupdr_v1.BackupDRClient.get_backup_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetBackupPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackupPlanRevision( + _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetBackupPlanRevision") + + @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: backupplan.GetBackupPlanRevisionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.BackupPlanRevision: + r"""Call the get backup plan revision method over HTTP. + + Args: + request (~.backupplan.GetBackupPlanRevisionRequest): + The request object. The request message for getting a + ``BackupPlanRevision``. + 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`. - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1", + Returns: + ~.backupplan.BackupPlanRevision: + ``BackupPlanRevision`` represents a snapshot of a + ``BackupPlan`` at a point in time. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanRevision._get_http_options() + request, metadata = self._interceptor.pre_get_backup_plan_revision( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, + "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, ) - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport + 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.backupdr_v1.BackupDRClient.GetBackupPlanRevision", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetBackupPlanRevision", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetBackupPlanRevision._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) - # Return the client from cache. - return self._operations_client + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) - class _CreateBackupPlan( - _BaseBackupDRRestTransport._BaseCreateBackupPlan, BackupDRRestStub + # Return the response + resp = backupplan.BackupPlanRevision() + pb_resp = backupplan.BackupPlanRevision.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_plan_revision(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_plan_revision_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplan.BackupPlanRevision.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.backupdr_v1.BackupDRClient.get_backup_plan_revision", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "GetBackupPlanRevision", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackupVault( + _BaseBackupDRRestTransport._BaseGetBackupVault, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.CreateBackupPlan") + return hash("BackupDRRestTransport.GetBackupVault") @staticmethod def _get_response( @@ -2598,23 +8579,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: backupplan.CreateBackupPlanRequest, + request: backupvault.GetBackupVaultRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create backup plan method over HTTP. + ) -> backupvault.BackupVault: + r"""Call the get backup vault method over HTTP. Args: - request (~.backupplan.CreateBackupPlanRequest): - The request object. The request message for creating a ``BackupPlan``. + request (~.backupvault.GetBackupVaultRequest): + The request object. Request message for getting a + BackupVault. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2624,25 +8605,24 @@ 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. + ~.backupvault.BackupVault: + Message describing a BackupVault + object. """ http_options = ( - _BaseBackupDRRestTransport._BaseCreateBackupPlan._get_http_options() + _BaseBackupDRRestTransport._BaseGetBackupVault._get_http_options() ) - request, metadata = self._interceptor.pre_create_backup_plan( + request, metadata = self._interceptor.pre_get_backup_vault( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseCreateBackupPlan, - "_BaseCreateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetBackupVault, + "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -2666,24 +8646,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.CreateBackupPlan", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetBackupVault", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "CreateBackupPlan", + "rpcName": "GetBackupVault", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._CreateBackupPlan._get_response( + response = BackupDRRestTransport._GetBackupVault._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2692,19 +8671,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 = backupvault.BackupVault() + pb_resp = backupvault.BackupVault.pb(resp) - resp = self._interceptor.post_create_backup_plan(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_vault(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_backup_plan_with_metadata( + resp, _ = self._interceptor.post_get_backup_vault_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 = backupvault.BackupVault.to_json(response) except: response_payload = None http_response = { @@ -2713,21 +8694,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.create_backup_plan", + "Received response for google.cloud.backupdr_v1.BackupDRClient.get_backup_vault", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "CreateBackupPlan", + "rpcName": "GetBackupVault", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _CreateBackupPlanAssociation( - _BaseBackupDRRestTransport._BaseCreateBackupPlanAssociation, BackupDRRestStub + class _GetDataSource( + _BaseBackupDRRestTransport._BaseGetDataSource, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.CreateBackupPlanAssociation") + return hash("BackupDRRestTransport.GetDataSource") @staticmethod def _get_response( @@ -2748,51 +8729,50 @@ 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: backupplanassociation.CreateBackupPlanAssociationRequest, + request: backupvault.GetDataSourceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create backup plan - association method over HTTP. + ) -> backupvault.DataSource: + r"""Call the get data source method over HTTP. - Args: - request (~.backupplanassociation.CreateBackupPlanAssociationRequest): - The request object. Request message for creating a backup - plan. - 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 (~.backupvault.GetDataSourceRequest): + The request object. Request message for getting a + DataSource instance. + 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. + Returns: + ~.backupvault.DataSource: + Message describing a DataSource + object. Datasource object used to + represent Datasource details for both + admin and basic view. """ - http_options = _BaseBackupDRRestTransport._BaseCreateBackupPlanAssociation._get_http_options() - request, metadata = self._interceptor.pre_create_backup_plan_association( - request, metadata + http_options = ( + _BaseBackupDRRestTransport._BaseGetDataSource._get_http_options() ) + request, metadata = self._interceptor.pre_get_data_source(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseCreateBackupPlanAssociation, - "_BaseCreateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetDataSource, + "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -2816,24 +8796,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.CreateBackupPlanAssociation", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetDataSource", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "CreateBackupPlanAssociation", + "rpcName": "GetDataSource", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._CreateBackupPlanAssociation._get_response( + response = BackupDRRestTransport._GetDataSource._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2842,21 +8821,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 = backupvault.DataSource() + pb_resp = backupvault.DataSource.pb(resp) - resp = self._interceptor.post_create_backup_plan_association(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_data_source(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_create_backup_plan_association_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_get_data_source_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 = backupvault.DataSource.to_json(response) except: response_payload = None http_response = { @@ -2865,21 +8844,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.create_backup_plan_association", + "Received response for google.cloud.backupdr_v1.BackupDRClient.get_data_source", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "CreateBackupPlanAssociation", + "rpcName": "GetDataSource", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _CreateBackupVault( - _BaseBackupDRRestTransport._BaseCreateBackupVault, BackupDRRestStub + class _GetDataSourceReference( + _BaseBackupDRRestTransport._BaseGetDataSourceReference, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.CreateBackupVault") + return hash("BackupDRRestTransport.GetDataSourceReference") @staticmethod def _get_response( @@ -2900,23 +8879,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: backupvault.CreateBackupVaultRequest, + request: datasourcereference.GetDataSourceReferenceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create backup vault method over HTTP. + ) -> datasourcereference.DataSourceReference: + r"""Call the get data source reference method over HTTP. Args: - request (~.backupvault.CreateBackupVaultRequest): - The request object. Message for creating a BackupVault. + request (~.datasourcereference.GetDataSourceReferenceRequest): + The request object. Request for the + GetDataSourceReference method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2926,25 +8905,22 @@ 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. + ~.datasourcereference.DataSourceReference: + DataSourceReference is a reference to + a DataSource resource. """ - http_options = ( - _BaseBackupDRRestTransport._BaseCreateBackupVault._get_http_options() - ) - request, metadata = self._interceptor.pre_create_backup_vault( + http_options = _BaseBackupDRRestTransport._BaseGetDataSourceReference._get_http_options() + request, metadata = self._interceptor.pre_get_data_source_reference( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseCreateBackupVault, - "_BaseCreateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetDataSourceReference, + "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -2968,24 +8944,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.CreateBackupVault", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetDataSourceReference", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "CreateBackupVault", + "rpcName": "GetDataSourceReference", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._CreateBackupVault._get_response( + response = BackupDRRestTransport._GetDataSourceReference._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2994,19 +8969,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 = datasourcereference.DataSourceReference() + pb_resp = datasourcereference.DataSourceReference.pb(resp) - resp = self._interceptor.post_create_backup_vault(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_data_source_reference(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_backup_vault_with_metadata( + resp, _ = self._interceptor.post_get_data_source_reference_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 = datasourcereference.DataSourceReference.to_json( + response + ) except: response_payload = None http_response = { @@ -3015,21 +8994,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.create_backup_vault", + "Received response for google.cloud.backupdr_v1.BackupDRClient.get_data_source_reference", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "CreateBackupVault", + "rpcName": "GetDataSourceReference", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _CreateManagementServer( - _BaseBackupDRRestTransport._BaseCreateManagementServer, BackupDRRestStub + class _GetManagementServer( + _BaseBackupDRRestTransport._BaseGetManagementServer, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.CreateManagementServer") + return hash("BackupDRRestTransport.GetManagementServer") @staticmethod def _get_response( @@ -3050,23 +9029,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: backupdr.CreateManagementServerRequest, + request: backupdr.GetManagementServerRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create management server method over HTTP. + ) -> backupdr.ManagementServer: + r"""Call the get management server method over HTTP. Args: - request (~.backupdr.CreateManagementServerRequest): - The request object. Request message for creating a + request (~.backupdr.GetManagementServerRequest): + The request object. Request message for getting a management server instance. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -3077,23 +9055,24 @@ 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. + ~.backupdr.ManagementServer: + ManagementServer describes a single + BackupDR ManagementServer instance. """ - http_options = _BaseBackupDRRestTransport._BaseCreateManagementServer._get_http_options() - request, metadata = self._interceptor.pre_create_management_server( + http_options = ( + _BaseBackupDRRestTransport._BaseGetManagementServer._get_http_options() + ) + request, metadata = self._interceptor.pre_get_management_server( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseCreateManagementServer, - "_BaseCreateManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetManagementServer, + "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3117,24 +9096,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.CreateManagementServer", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetManagementServer", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "CreateManagementServer", + "rpcName": "GetManagementServer", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._CreateManagementServer._get_response( + response = BackupDRRestTransport._GetManagementServer._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3143,19 +9121,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 = backupdr.ManagementServer() + pb_resp = backupdr.ManagementServer.pb(resp) - resp = self._interceptor.post_create_management_server(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_management_server(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_management_server_with_metadata( + resp, _ = self._interceptor.post_get_management_server_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 = backupdr.ManagementServer.to_json(response) except: response_payload = None http_response = { @@ -3164,19 +9144,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.create_management_server", + "Received response for google.cloud.backupdr_v1.BackupDRClient.get_management_server", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "CreateManagementServer", + "rpcName": "GetManagementServer", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteBackup(_BaseBackupDRRestTransport._BaseDeleteBackup, BackupDRRestStub): + class _GetRestoreTemplate( + _BaseBackupDRRestTransport._BaseGetRestoreTemplate, BackupDRRestStub + ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteBackup") + return hash("BackupDRRestTransport.GetRestoreTemplate") @staticmethod def _get_response( @@ -3202,17 +9184,18 @@ def _get_response( def __call__( self, - request: backupvault.DeleteBackupRequest, + request: restore_template.GetRestoreTemplateRequest, *, 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. + ) -> restore_template.RestoreTemplate: + r"""Call the get restore template method over HTTP. Args: - request (~.backupvault.DeleteBackupRequest): - The request object. Message for deleting a Backup. + request (~.restore_template.GetRestoreTemplateRequest): + The request object. Request message for getting a + RestoreTemplate instance. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3222,23 +9205,24 @@ 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. + ~.restore_template.RestoreTemplate: + A ``RestoreTemplate`` encapsulates DR readiness + configurations for validating backups. """ http_options = ( - _BaseBackupDRRestTransport._BaseDeleteBackup._get_http_options() + _BaseBackupDRRestTransport._BaseGetRestoreTemplate._get_http_options() + ) + request, metadata = self._interceptor.pre_get_restore_template( + request, metadata ) - request, metadata = self._interceptor.pre_delete_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteBackup, - "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetRestoreTemplate, + "_BaseGetRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3262,17 +9246,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.DeleteBackup", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetRestoreTemplate", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteBackup", + "rpcName": "GetRestoreTemplate", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteBackup._get_response( + response = BackupDRRestTransport._GetRestoreTemplate._get_response( self._host, metadata, query_params, @@ -3287,19 +9271,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 = restore_template.RestoreTemplate() + pb_resp = restore_template.RestoreTemplate.pb(resp) - resp = self._interceptor.post_delete_backup(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_restore_template(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_backup_with_metadata( + resp, _ = self._interceptor.post_get_restore_template_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 = restore_template.RestoreTemplate.to_json( + response + ) except: response_payload = None http_response = { @@ -3308,21 +9296,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.delete_backup", + "Received response for google.cloud.backupdr_v1.BackupDRClient.get_restore_template", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteBackup", + "rpcName": "GetRestoreTemplate", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteBackupPlan( - _BaseBackupDRRestTransport._BaseDeleteBackupPlan, BackupDRRestStub + class _GetRestoreTemplateExecution( + _BaseBackupDRRestTransport._BaseGetRestoreTemplateExecution, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteBackupPlan") + return hash("BackupDRRestTransport.GetRestoreTemplateExecution") @staticmethod def _get_response( @@ -3348,45 +9336,44 @@ def _get_response( def __call__( self, - request: backupplan.DeleteBackupPlanRequest, + request: restore_template_execution.GetRestoreTemplateExecutionRequest, *, 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 plan method over HTTP. + ) -> restore_template_execution.RestoreTemplateExecution: + r"""Call the get restore template + execution method over HTTP. - Args: - request (~.backupplan.DeleteBackupPlanRequest): - The request object. The request message for deleting a ``BackupPlan``. - 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 (~.restore_template_execution.GetRestoreTemplateExecutionRequest): + The request object. Request message for getting a + RestoreTemplateExecution instance. + 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. + Returns: + ~.restore_template_execution.RestoreTemplateExecution: + A ``RestoreTemplateExecution`` represents a single + historical or active execution run. """ - http_options = ( - _BaseBackupDRRestTransport._BaseDeleteBackupPlan._get_http_options() - ) - request, metadata = self._interceptor.pre_delete_backup_plan( + http_options = _BaseBackupDRRestTransport._BaseGetRestoreTemplateExecution._get_http_options() + request, metadata = self._interceptor.pre_get_restore_template_execution( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteBackupPlan, - "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetRestoreTemplateExecution, + "_BaseGetRestoreTemplateExecution__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3410,17 +9397,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.DeleteBackupPlan", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetRestoreTemplateExecution", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteBackupPlan", + "rpcName": "GetRestoreTemplateExecution", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteBackupPlan._get_response( + response = BackupDRRestTransport._GetRestoreTemplateExecution._get_response( self._host, metadata, query_params, @@ -3435,19 +9422,27 @@ 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 = restore_template_execution.RestoreTemplateExecution() + pb_resp = restore_template_execution.RestoreTemplateExecution.pb(resp) - resp = self._interceptor.post_delete_backup_plan(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_restore_template_execution(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_backup_plan_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_get_restore_template_execution_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 = ( + restore_template_execution.RestoreTemplateExecution.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -3456,21 +9451,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.delete_backup_plan", + "Received response for google.cloud.backupdr_v1.BackupDRClient.get_restore_template_execution", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteBackupPlan", + "rpcName": "GetRestoreTemplateExecution", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteBackupPlanAssociation( - _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, BackupDRRestStub + class _GetRestoreVerificationPlan( + _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlan, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteBackupPlanAssociation") + return hash("BackupDRRestTransport.GetRestoreVerificationPlan") @staticmethod def _get_response( @@ -3496,19 +9491,19 @@ def _get_response( def __call__( self, - request: backupplanassociation.DeleteBackupPlanAssociationRequest, + request: restore_verification_plan.GetRestoreVerificationPlanRequest, *, 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 plan - association method over HTTP. + ) -> restore_verification_plan.RestoreVerificationPlan: + r"""Call the get restore verification + plan method over HTTP. Args: - request (~.backupplanassociation.DeleteBackupPlanAssociationRequest): - The request object. Request message for deleting a backup - plan association. + request (~.restore_verification_plan.GetRestoreVerificationPlanRequest): + The request object. The request message for getting a + ``RestoreVerificationPlan``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3518,23 +9513,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. + ~.restore_verification_plan.RestoreVerificationPlan: + A ``RestoreVerificationPlan`` specifies the scheduling + and clean-up template for automated restore + verification. It contains a ``schedule`` to dictate when + the verifications should run, and a + ``RestoreVerificationCleanupRule`` for post-verification + resource deletion. """ - http_options = _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation._get_http_options() - request, metadata = self._interceptor.pre_delete_backup_plan_association( + http_options = _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlan._get_http_options() + request, metadata = self._interceptor.pre_get_restore_verification_plan( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, - "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlan, + "_BaseGetRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3558,17 +9556,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.DeleteBackupPlanAssociation", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetRestoreVerificationPlan", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteBackupPlanAssociation", + "rpcName": "GetRestoreVerificationPlan", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteBackupPlanAssociation._get_response( + response = BackupDRRestTransport._GetRestoreVerificationPlan._get_response( self._host, metadata, query_params, @@ -3583,13 +9581,15 @@ 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 = restore_verification_plan.RestoreVerificationPlan() + pb_resp = restore_verification_plan.RestoreVerificationPlan.pb(resp) - resp = self._interceptor.post_delete_backup_plan_association(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_restore_verification_plan(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_delete_backup_plan_association_with_metadata( + self._interceptor.post_get_restore_verification_plan_with_metadata( resp, response_metadata ) ) @@ -3597,7 +9597,11 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = ( + restore_verification_plan.RestoreVerificationPlan.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -3606,21 +9610,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.delete_backup_plan_association", + "Received response for google.cloud.backupdr_v1.BackupDRClient.get_restore_verification_plan", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteBackupPlanAssociation", + "rpcName": "GetRestoreVerificationPlan", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteBackupVault( - _BaseBackupDRRestTransport._BaseDeleteBackupVault, BackupDRRestStub + class _GetRestoreVerificationPlanAssociation( + _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlanAssociation, + BackupDRRestStub, ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteBackupVault") + return hash("BackupDRRestTransport.GetRestoreVerificationPlanAssociation") @staticmethod def _get_response( @@ -3646,45 +9651,46 @@ def _get_response( def __call__( self, - request: backupvault.DeleteBackupVaultRequest, + request: restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, *, 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 vault method over HTTP. + ) -> restore_verification_plan_association.RestoreVerificationPlanAssociation: + r"""Call the get restore verification + plan association method over HTTP. - Args: - request (~.backupvault.DeleteBackupVaultRequest): - The request object. Message for deleting a BackupVault. - 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 (~.restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest): + The request object. Request message for + GetRestoreVerificationPlanAssociation. + 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. + Returns: + ~.restore_verification_plan_association.RestoreVerificationPlanAssociation: + A ``RestoreVerificationPlanAssociation`` binds a + specific workload to a ``RestoreVerificationPlan``. """ - http_options = ( - _BaseBackupDRRestTransport._BaseDeleteBackupVault._get_http_options() - ) - request, metadata = self._interceptor.pre_delete_backup_vault( - request, metadata + http_options = _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlanAssociation._get_http_options() + request, metadata = ( + self._interceptor.pre_get_restore_verification_plan_association( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteBackupVault, - "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlanAssociation, + "_BaseGetRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3708,17 +9714,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.DeleteBackupVault", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetRestoreVerificationPlanAssociation", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteBackupVault", + "rpcName": "GetRestoreVerificationPlanAssociation", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteBackupVault._get_response( + response = BackupDRRestTransport._GetRestoreVerificationPlanAssociation._get_response( self._host, metadata, query_params, @@ -3733,19 +9739,29 @@ 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 = restore_verification_plan_association.RestoreVerificationPlanAssociation() + pb_resp = restore_verification_plan_association.RestoreVerificationPlanAssociation.pb( + resp + ) - resp = self._interceptor.post_delete_backup_vault(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_restore_verification_plan_association( + resp + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_backup_vault_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_get_restore_verification_plan_association_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 = restore_verification_plan_association.RestoreVerificationPlanAssociation.to_json( + response + ) except: response_payload = None http_response = { @@ -3754,21 +9770,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.delete_backup_vault", + "Received response for google.cloud.backupdr_v1.BackupDRClient.get_restore_verification_plan_association", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteBackupVault", + "rpcName": "GetRestoreVerificationPlanAssociation", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteManagementServer( - _BaseBackupDRRestTransport._BaseDeleteManagementServer, BackupDRRestStub + class _InitializeService( + _BaseBackupDRRestTransport._BaseInitializeService, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteManagementServer") + return hash("BackupDRRestTransport.InitializeService") @staticmethod def _get_response( @@ -3789,23 +9805,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: backupdr.DeleteManagementServerRequest, + request: backupdr.InitializeServiceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the delete management server method over HTTP. + r"""Call the initialize service method over HTTP. Args: - request (~.backupdr.DeleteManagementServerRequest): - The request object. Request message for deleting a - management server instance. + request (~.backupdr.InitializeServiceRequest): + The request object. Request message for initializing the + service. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3822,16 +9839,18 @@ def __call__( """ - http_options = _BaseBackupDRRestTransport._BaseDeleteManagementServer._get_http_options() - request, metadata = self._interceptor.pre_delete_management_server( + http_options = ( + _BaseBackupDRRestTransport._BaseInitializeService._get_http_options() + ) + request, metadata = self._interceptor.pre_initialize_service( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteManagementServer, - "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseInitializeService, + "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3855,23 +9874,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.DeleteManagementServer", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.InitializeService", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteManagementServer", + "rpcName": "InitializeService", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteManagementServer._get_response( + response = BackupDRRestTransport._InitializeService._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3883,9 +9903,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_management_server(resp) + resp = self._interceptor.post_initialize_service(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_management_server_with_metadata( + resp, _ = self._interceptor.post_initialize_service_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -3901,23 +9921,23 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.delete_management_server", + "Received response for google.cloud.backupdr_v1.BackupDRClient.initialize_service", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "DeleteManagementServer", + "rpcName": "InitializeService", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchBackupPlanAssociationsForResourceType( - _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, + class _InitiateDeleteAutoProtectionPolicyBinding( + _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding, BackupDRRestStub, ): def __hash__(self): return hash( - "BackupDRRestTransport.FetchBackupPlanAssociationsForResourceType" + "BackupDRRestTransport.InitiateDeleteAutoProtectionPolicyBinding" ) @staticmethod @@ -3939,25 +9959,25 @@ 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: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + request: autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: - r"""Call the fetch backup plan - associations for resource type method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the initiate delete auto + protection policy binding method over HTTP. Args: - request (~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest): - The request object. Request for the - FetchBackupPlanAssociationsForResourceType - method. + request (~.autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest): + The request object. Request message for initiating delete + of an AutoProtectionPolicyBinding. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3967,16 +9987,16 @@ def __call__( be of type `bytes`. Returns: - ~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: - Response for the - FetchBackupPlanAssociationsForResourceType - method. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding._get_http_options() request, metadata = ( - self._interceptor.pre_fetch_backup_plan_associations_for_resource_type( + self._interceptor.pre_initiate_delete_auto_protection_policy_binding( request, metadata ) ) @@ -3984,8 +10004,8 @@ def __call__( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, - "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding, + "_BaseInitiateDeleteAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4009,23 +10029,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.FetchBackupPlanAssociationsForResourceType", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.InitiateDeleteAutoProtectionPolicyBinding", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "FetchBackupPlanAssociationsForResourceType", + "rpcName": "InitiateDeleteAutoProtectionPolicyBinding", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._FetchBackupPlanAssociationsForResourceType._get_response( + response = BackupDRRestTransport._InitiateDeleteAutoProtectionPolicyBinding._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4034,21 +10055,17 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - pb_resp = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.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_fetch_backup_plan_associations_for_resource_type( + self._interceptor.post_initiate_delete_auto_protection_policy_binding( resp ) ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_fetch_backup_plan_associations_for_resource_type_with_metadata( + self._interceptor.post_initiate_delete_auto_protection_policy_binding_with_metadata( resp, response_metadata ) ) @@ -4056,9 +10073,7 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -4067,21 +10082,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.fetch_backup_plan_associations_for_resource_type", + "Received response for google.cloud.backupdr_v1.BackupDRClient.initiate_delete_auto_protection_policy_binding", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "FetchBackupPlanAssociationsForResourceType", + "rpcName": "InitiateDeleteAutoProtectionPolicyBinding", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchBackupsForResourceType( - _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, BackupDRRestStub + class _ListAppliedAutoProtectionPolicies( + _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies, + BackupDRRestStub, ): def __hash__(self): - return hash("BackupDRRestTransport.FetchBackupsForResourceType") + return hash("BackupDRRestTransport.ListAppliedAutoProtectionPolicies") @staticmethod def _get_response( @@ -4107,19 +10123,19 @@ def _get_response( def __call__( self, - request: backupvault.FetchBackupsForResourceTypeRequest, + request: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.FetchBackupsForResourceTypeResponse: - r"""Call the fetch backups for - resource type method over HTTP. + ) -> appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: + r"""Call the list applied auto + protection policies method over HTTP. Args: - request (~.backupvault.FetchBackupsForResourceTypeRequest): - The request object. Request for the - FetchBackupsForResourceType method. + request (~.appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest): + The request object. Request message for listing + AppliedAutoProtectionPolicies. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4129,22 +10145,24 @@ def __call__( be of type `bytes`. Returns: - ~.backupvault.FetchBackupsForResourceTypeResponse: - Response for the - FetchBackupsForResourceType method. + ~.appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: + Response message for + ListAppliedAutoProtectionPolicies. """ - http_options = _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType._get_http_options() - request, metadata = self._interceptor.pre_fetch_backups_for_resource_type( - request, metadata + http_options = _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies._get_http_options() + request, metadata = ( + self._interceptor.pre_list_applied_auto_protection_policies( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, - "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies, + "_BaseListAppliedAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4168,23 +10186,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.FetchBackupsForResourceType", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListAppliedAutoProtectionPolicies", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "FetchBackupsForResourceType", + "rpcName": "ListAppliedAutoProtectionPolicies", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._FetchBackupsForResourceType._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + BackupDRRestTransport._ListAppliedAutoProtectionPolicies._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4193,15 +10213,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.FetchBackupsForResourceTypeResponse() - pb_resp = backupvault.FetchBackupsForResourceTypeResponse.pb(resp) + resp = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + pb_resp = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + resp + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_backups_for_resource_type(resp) + resp = self._interceptor.post_list_applied_auto_protection_policies(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_fetch_backups_for_resource_type_with_metadata( + self._interceptor.post_list_applied_auto_protection_policies_with_metadata( resp, response_metadata ) ) @@ -4209,10 +10233,8 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - backupvault.FetchBackupsForResourceTypeResponse.to_json( - response - ) + response_payload = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.to_json( + response ) except: response_payload = None @@ -4222,24 +10244,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.fetch_backups_for_resource_type", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_applied_auto_protection_policies", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "FetchBackupsForResourceType", + "rpcName": "ListAppliedAutoProtectionPolicies", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchDataSourceReferencesForResourceType( - _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, - BackupDRRestStub, + class _ListAutoProtectionPolicies( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies, BackupDRRestStub ): def __hash__(self): - return hash( - "BackupDRRestTransport.FetchDataSourceReferencesForResourceType" - ) + return hash("BackupDRRestTransport.ListAutoProtectionPolicies") @staticmethod def _get_response( @@ -4265,20 +10284,19 @@ def _get_response( def __call__( self, - request: datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + request: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: - r"""Call the fetch data source - references for resource type method over HTTP. + ) -> autoprotectionpolicy.ListAutoProtectionPoliciesResponse: + r"""Call the list auto protection + policies method over HTTP. Args: - request (~.datasourcereference.FetchDataSourceReferencesForResourceTypeRequest): - The request object. Request for the - FetchDataSourceReferencesForResourceType - method. + request (~.autoprotectionpolicy.ListAutoProtectionPoliciesRequest): + The request object. Request message for + ListAutoProtectionPolicies. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4288,25 +10306,22 @@ def __call__( be of type `bytes`. Returns: - ~.datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: - Response for the - FetchDataSourceReferencesForResourceType - method. + ~.autoprotectionpolicy.ListAutoProtectionPoliciesResponse: + Response message for + ListAutoProtectionPolicies. """ - http_options = _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType._get_http_options() - request, metadata = ( - self._interceptor.pre_fetch_data_source_references_for_resource_type( - request, metadata - ) + http_options = _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies._get_http_options() + request, metadata = self._interceptor.pre_list_auto_protection_policies( + request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, - "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies, + "_BaseListAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4330,17 +10345,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.FetchDataSourceReferencesForResourceType", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListAutoProtectionPolicies", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "FetchDataSourceReferencesForResourceType", + "rpcName": "ListAutoProtectionPolicies", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._FetchDataSourceReferencesForResourceType._get_response( + response = BackupDRRestTransport._ListAutoProtectionPolicies._get_response( self._host, metadata, query_params, @@ -4355,25 +10370,15 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() - ) - pb_resp = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( - resp - ) - ) + resp = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + pb_resp = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = ( - self._interceptor.post_fetch_data_source_references_for_resource_type( - resp - ) - ) + resp = self._interceptor.post_list_auto_protection_policies(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_fetch_data_source_references_for_resource_type_with_metadata( + self._interceptor.post_list_auto_protection_policies_with_metadata( resp, response_metadata ) ) @@ -4381,8 +10386,10 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.to_json( - response + response_payload = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse.to_json( + response + ) ) except: response_payload = None @@ -4392,21 +10399,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.fetch_data_source_references_for_resource_type", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_auto_protection_policies", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "FetchDataSourceReferencesForResourceType", + "rpcName": "ListAutoProtectionPolicies", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchUsableBackupVaults( - _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, BackupDRRestStub + class _ListAutoProtectionPolicyBindings( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings, + BackupDRRestStub, ): def __hash__(self): - return hash("BackupDRRestTransport.FetchUsableBackupVaults") + return hash("BackupDRRestTransport.ListAutoProtectionPolicyBindings") @staticmethod def _get_response( @@ -4432,19 +10440,19 @@ def _get_response( def __call__( self, - request: backupvault.FetchUsableBackupVaultsRequest, + request: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.FetchUsableBackupVaultsResponse: - r"""Call the fetch usable backup - vaults method over HTTP. + ) -> autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: + r"""Call the list auto protection + policy bindings method over HTTP. Args: - request (~.backupvault.FetchUsableBackupVaultsRequest): - The request object. Request message for fetching usable - BackupVaults. + request (~.autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest): + The request object. Request message for + ListAutoProtectionPolicyBindings. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4454,22 +10462,24 @@ def __call__( be of type `bytes`. Returns: - ~.backupvault.FetchUsableBackupVaultsResponse: - Response message for fetching usable - BackupVaults. + ~.autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: + Response message for + ListAutoProtectionPolicyBindings. """ - http_options = _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults._get_http_options() - request, metadata = self._interceptor.pre_fetch_usable_backup_vaults( - request, metadata + http_options = _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings._get_http_options() + request, metadata = ( + self._interceptor.pre_list_auto_protection_policy_bindings( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, - "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings, + "_BaseListAutoProtectionPolicyBindings__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4493,23 +10503,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.FetchUsableBackupVaults", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListAutoProtectionPolicyBindings", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "FetchUsableBackupVaults", + "rpcName": "ListAutoProtectionPolicyBindings", "httpRequest": http_request, "metadata": http_request["headers"], }, ) - # Send the request - response = BackupDRRestTransport._FetchUsableBackupVaults._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + # Send the request + response = ( + BackupDRRestTransport._ListAutoProtectionPolicyBindings._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4518,22 +10530,30 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.FetchUsableBackupVaultsResponse() - pb_resp = backupvault.FetchUsableBackupVaultsResponse.pb(resp) + resp = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + pb_resp = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + resp + ) + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_usable_backup_vaults(resp) + resp = self._interceptor.post_list_auto_protection_policy_bindings(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_usable_backup_vaults_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_list_auto_protection_policy_bindings_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - backupvault.FetchUsableBackupVaultsResponse.to_json(response) + response_payload = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.to_json( + response ) except: response_payload = None @@ -4543,19 +10563,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.fetch_usable_backup_vaults", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_auto_protection_policy_bindings", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "FetchUsableBackupVaults", + "rpcName": "ListAutoProtectionPolicyBindings", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBackup(_BaseBackupDRRestTransport._BaseGetBackup, BackupDRRestStub): + class _ListBackupPlanAssociations( + _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, BackupDRRestStub + ): def __hash__(self): - return hash("BackupDRRestTransport.GetBackup") + return hash("BackupDRRestTransport.ListBackupPlanAssociations") @staticmethod def _get_response( @@ -4581,38 +10603,44 @@ def _get_response( def __call__( self, - request: backupvault.GetBackupRequest, + request: backupplanassociation.ListBackupPlanAssociationsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.Backup: - r"""Call the get backup method over HTTP. + ) -> backupplanassociation.ListBackupPlanAssociationsResponse: + r"""Call the list backup plan + associations method over HTTP. - Args: - request (~.backupvault.GetBackupRequest): - The request object. Request message for getting a Backup. - 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 (~.backupplanassociation.ListBackupPlanAssociationsRequest): + The request object. Request message for List + BackupPlanAssociation + 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: + ~.backupplanassociation.ListBackupPlanAssociationsResponse: + Response message for List + BackupPlanAssociation - Returns: - ~.backupvault.Backup: - Message describing a Backup object. """ - http_options = _BaseBackupDRRestTransport._BaseGetBackup._get_http_options() - request, metadata = self._interceptor.pre_get_backup(request, metadata) + http_options = _BaseBackupDRRestTransport._BaseListBackupPlanAssociations._get_http_options() + request, metadata = self._interceptor.pre_list_backup_plan_associations( + request, metadata + ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackup, - "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, + "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4636,17 +10664,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetBackup", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackupPlanAssociations", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackup", + "rpcName": "ListBackupPlanAssociations", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackup._get_response( + response = BackupDRRestTransport._ListBackupPlanAssociations._get_response( self._host, metadata, query_params, @@ -4661,21 +10689,25 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.Backup() - pb_resp = backupvault.Backup.pb(resp) + resp = backupplanassociation.ListBackupPlanAssociationsResponse() + pb_resp = backupplanassociation.ListBackupPlanAssociationsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup(resp) + resp = self._interceptor.post_list_backup_plan_associations(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_list_backup_plan_associations_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.Backup.to_json(response) + response_payload = backupplanassociation.ListBackupPlanAssociationsResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -4684,21 +10716,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.get_backup", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backup_plan_associations", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackup", + "rpcName": "ListBackupPlanAssociations", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBackupPlan( - _BaseBackupDRRestTransport._BaseGetBackupPlan, BackupDRRestStub + class _ListBackupPlanRevisions( + _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetBackupPlan") + return hash("BackupDRRestTransport.ListBackupPlanRevisions") @staticmethod def _get_response( @@ -4724,45 +10756,44 @@ def _get_response( def __call__( self, - request: backupplan.GetBackupPlanRequest, + request: backupplan.ListBackupPlanRevisionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplan.BackupPlan: - r"""Call the get backup plan method over HTTP. + ) -> backupplan.ListBackupPlanRevisionsResponse: + r"""Call the list backup plan + revisions method over HTTP. - Args: - request (~.backupplan.GetBackupPlanRequest): - The request object. The request message for getting a ``BackupPlan``. - 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 (~.backupplan.ListBackupPlanRevisionsRequest): + The request object. The request message for getting a list of + ``BackupPlanRevision``. + 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: - ~.backupplan.BackupPlan: - A ``BackupPlan`` specifies some common fields, such as - ``description`` as well as one or more ``BackupRule`` - messages. Each ``BackupRule`` has a retention policy and - defines a schedule by which the system is to perform - backup workloads. + Returns: + ~.backupplan.ListBackupPlanRevisionsResponse: + The response message for getting a list of + ``BackupPlanRevision``. """ - http_options = ( - _BaseBackupDRRestTransport._BaseGetBackupPlan._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseListBackupPlanRevisions._get_http_options() + request, metadata = self._interceptor.pre_list_backup_plan_revisions( + request, metadata ) - request, metadata = self._interceptor.pre_get_backup_plan(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackupPlan, - "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, + "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4786,17 +10817,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetBackupPlan", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackupPlanRevisions", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackupPlan", + "rpcName": "ListBackupPlanRevisions", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackupPlan._get_response( + response = BackupDRRestTransport._ListBackupPlanRevisions._get_response( self._host, metadata, query_params, @@ -4811,21 +10842,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplan.BackupPlan() - pb_resp = backupplan.BackupPlan.pb(resp) + resp = backupplan.ListBackupPlanRevisionsResponse() + pb_resp = backupplan.ListBackupPlanRevisionsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup_plan(resp) + resp = self._interceptor.post_list_backup_plan_revisions(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_plan_with_metadata( + resp, _ = self._interceptor.post_list_backup_plan_revisions_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupplan.BackupPlan.to_json(response) + response_payload = ( + backupplan.ListBackupPlanRevisionsResponse.to_json(response) + ) except: response_payload = None http_response = { @@ -4834,21 +10867,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.get_backup_plan", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backup_plan_revisions", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackupPlan", + "rpcName": "ListBackupPlanRevisions", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBackupPlanAssociation( - _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, BackupDRRestStub + class _ListBackupPlans( + _BaseBackupDRRestTransport._BaseListBackupPlans, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetBackupPlanAssociation") + return hash("BackupDRRestTransport.ListBackupPlans") @staticmethod def _get_response( @@ -4874,46 +10907,44 @@ def _get_response( def __call__( self, - request: backupplanassociation.GetBackupPlanAssociationRequest, + request: backupplan.ListBackupPlansRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplanassociation.BackupPlanAssociation: - r"""Call the get backup plan - association method over HTTP. + ) -> backupplan.ListBackupPlansResponse: + r"""Call the list backup plans method over HTTP. - Args: - request (~.backupplanassociation.GetBackupPlanAssociationRequest): - The request object. Request message for getting a - BackupPlanAssociation resource. - 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 (~.backupplan.ListBackupPlansRequest): + The request object. The request message for getting a list ``BackupPlan``. + 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: - ~.backupplanassociation.BackupPlanAssociation: - A BackupPlanAssociation represents a - single BackupPlanAssociation which - contains details like workload, backup - plan etc + Returns: + ~.backupplan.ListBackupPlansResponse: + The response message for getting a list of + ``BackupPlan``. """ - http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation._get_http_options() - request, metadata = self._interceptor.pre_get_backup_plan_association( + http_options = ( + _BaseBackupDRRestTransport._BaseListBackupPlans._get_http_options() + ) + request, metadata = self._interceptor.pre_list_backup_plans( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, - "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListBackupPlans, + "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4937,17 +10968,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetBackupPlanAssociation", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackupPlans", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackupPlanAssociation", + "rpcName": "ListBackupPlans", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackupPlanAssociation._get_response( + response = BackupDRRestTransport._ListBackupPlans._get_response( self._host, metadata, query_params, @@ -4962,22 +10993,22 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplanassociation.BackupPlanAssociation() - pb_resp = backupplanassociation.BackupPlanAssociation.pb(resp) + resp = backupplan.ListBackupPlansResponse() + pb_resp = backupplan.ListBackupPlansResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup_plan_association(resp) + resp = self._interceptor.post_list_backup_plans(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_plan_association_with_metadata( + resp, _ = self._interceptor.post_list_backup_plans_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - backupplanassociation.BackupPlanAssociation.to_json(response) + response_payload = backupplan.ListBackupPlansResponse.to_json( + response ) except: response_payload = None @@ -4987,21 +11018,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.get_backup_plan_association", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backup_plans", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackupPlanAssociation", + "rpcName": "ListBackupPlans", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - - class _GetBackupPlanRevision( - _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, BackupDRRestStub - ): + + class _ListBackups(_BaseBackupDRRestTransport._BaseListBackups, BackupDRRestStub): def __hash__(self): - return hash("BackupDRRestTransport.GetBackupPlanRevision") + return hash("BackupDRRestTransport.ListBackups") @staticmethod def _get_response( @@ -5027,18 +11056,17 @@ def _get_response( def __call__( self, - request: backupplan.GetBackupPlanRevisionRequest, + request: backupvault.ListBackupsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplan.BackupPlanRevision: - r"""Call the get backup plan revision method over HTTP. + ) -> backupvault.ListBackupsResponse: + r"""Call the list backups method over HTTP. Args: - request (~.backupplan.GetBackupPlanRevisionRequest): - The request object. The request message for getting a - ``BackupPlanRevision``. + request (~.backupvault.ListBackupsRequest): + The request object. Request message for listing Backups. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5048,22 +11076,20 @@ def __call__( be of type `bytes`. Returns: - ~.backupplan.BackupPlanRevision: - ``BackupPlanRevision`` represents a snapshot of a - ``BackupPlan`` at a point in time. - + ~.backupvault.ListBackupsResponse: + Response message for listing Backups. """ - http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanRevision._get_http_options() - request, metadata = self._interceptor.pre_get_backup_plan_revision( - request, metadata + http_options = ( + _BaseBackupDRRestTransport._BaseListBackups._get_http_options() ) + request, metadata = self._interceptor.pre_list_backups(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, - "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListBackups, + "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5087,17 +11113,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetBackupPlanRevision", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackups", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackupPlanRevision", + "rpcName": "ListBackups", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackupPlanRevision._get_response( + response = BackupDRRestTransport._ListBackups._get_response( self._host, metadata, query_params, @@ -5112,21 +11138,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplan.BackupPlanRevision() - pb_resp = backupplan.BackupPlanRevision.pb(resp) + resp = backupvault.ListBackupsResponse() + pb_resp = backupvault.ListBackupsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup_plan_revision(resp) + resp = self._interceptor.post_list_backups(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_plan_revision_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 = backupplan.BackupPlanRevision.to_json(response) + response_payload = backupvault.ListBackupsResponse.to_json(response) except: response_payload = None http_response = { @@ -5135,21 +11161,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.get_backup_plan_revision", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backups", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackupPlanRevision", + "rpcName": "ListBackups", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBackupVault( - _BaseBackupDRRestTransport._BaseGetBackupVault, BackupDRRestStub + class _ListBackupVaults( + _BaseBackupDRRestTransport._BaseListBackupVaults, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetBackupVault") + return hash("BackupDRRestTransport.ListBackupVaults") @staticmethod def _get_response( @@ -5175,18 +11201,18 @@ def _get_response( def __call__( self, - request: backupvault.GetBackupVaultRequest, + request: backupvault.ListBackupVaultsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.BackupVault: - r"""Call the get backup vault method over HTTP. + ) -> backupvault.ListBackupVaultsResponse: + r"""Call the list backup vaults method over HTTP. Args: - request (~.backupvault.GetBackupVaultRequest): - The request object. Request message for getting a - BackupVault. + request (~.backupvault.ListBackupVaultsRequest): + The request object. Request message for listing + backupvault stores. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5196,24 +11222,24 @@ def __call__( be of type `bytes`. Returns: - ~.backupvault.BackupVault: - Message describing a BackupVault - object. + ~.backupvault.ListBackupVaultsResponse: + Response message for listing + BackupVaults. """ http_options = ( - _BaseBackupDRRestTransport._BaseGetBackupVault._get_http_options() + _BaseBackupDRRestTransport._BaseListBackupVaults._get_http_options() ) - request, metadata = self._interceptor.pre_get_backup_vault( + request, metadata = self._interceptor.pre_list_backup_vaults( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackupVault, - "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListBackupVaults, + "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5237,17 +11263,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetBackupVault", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackupVaults", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackupVault", + "rpcName": "ListBackupVaults", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackupVault._get_response( + response = BackupDRRestTransport._ListBackupVaults._get_response( self._host, metadata, query_params, @@ -5262,21 +11288,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.BackupVault() - pb_resp = backupvault.BackupVault.pb(resp) + resp = backupvault.ListBackupVaultsResponse() + pb_resp = backupvault.ListBackupVaultsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup_vault(resp) + resp = self._interceptor.post_list_backup_vaults(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_vault_with_metadata( + resp, _ = self._interceptor.post_list_backup_vaults_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.BackupVault.to_json(response) + response_payload = backupvault.ListBackupVaultsResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -5285,21 +11313,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.get_backup_vault", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backup_vaults", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetBackupVault", + "rpcName": "ListBackupVaults", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetDataSource( - _BaseBackupDRRestTransport._BaseGetDataSource, BackupDRRestStub + class _ListBindingMatchingResources( + _BaseBackupDRRestTransport._BaseListBindingMatchingResources, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetDataSource") + return hash("BackupDRRestTransport.ListBindingMatchingResources") @staticmethod def _get_response( @@ -5325,45 +11353,44 @@ def _get_response( def __call__( self, - request: backupvault.GetDataSourceRequest, + request: bindingmatchingresource.ListBindingMatchingResourcesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.DataSource: - r"""Call the get data source method over HTTP. + ) -> bindingmatchingresource.ListBindingMatchingResourcesResponse: + r"""Call the list binding matching + resources method over HTTP. - Args: - request (~.backupvault.GetDataSourceRequest): - The request object. Request message for getting a - DataSource instance. - 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 (~.bindingmatchingresource.ListBindingMatchingResourcesRequest): + The request object. Request message for List + BindingMatchingResources. + 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: - ~.backupvault.DataSource: - Message describing a DataSource - object. Datasource object used to - represent Datasource details for both - admin and basic view. + Returns: + ~.bindingmatchingresource.ListBindingMatchingResourcesResponse: + The response message for getting a list of + ``BindingMatchingResources``. """ - http_options = ( - _BaseBackupDRRestTransport._BaseGetDataSource._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseListBindingMatchingResources._get_http_options() + request, metadata = self._interceptor.pre_list_binding_matching_resources( + request, metadata ) - request, metadata = self._interceptor.pre_get_data_source(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetDataSource, - "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListBindingMatchingResources, + "_BaseListBindingMatchingResources__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5387,23 +11414,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetDataSource", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBindingMatchingResources", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetDataSource", + "rpcName": "ListBindingMatchingResources", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetDataSource._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + BackupDRRestTransport._ListBindingMatchingResources._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -5412,21 +11441,27 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.DataSource() - pb_resp = backupvault.DataSource.pb(resp) + resp = bindingmatchingresource.ListBindingMatchingResourcesResponse() + pb_resp = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + resp + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_data_source(resp) + resp = self._interceptor.post_list_binding_matching_resources(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_data_source_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_list_binding_matching_resources_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.DataSource.to_json(response) + response_payload = bindingmatchingresource.ListBindingMatchingResourcesResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -5435,21 +11470,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.get_data_source", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_binding_matching_resources", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetDataSource", + "rpcName": "ListBindingMatchingResources", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetDataSourceReference( - _BaseBackupDRRestTransport._BaseGetDataSourceReference, BackupDRRestStub + class _ListDataSourceReferences( + _BaseBackupDRRestTransport._BaseListDataSourceReferences, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetDataSourceReference") + return hash("BackupDRRestTransport.ListDataSourceReferences") @staticmethod def _get_response( @@ -5475,43 +11510,44 @@ def _get_response( def __call__( self, - request: datasourcereference.GetDataSourceReferenceRequest, + request: datasourcereference.ListDataSourceReferencesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasourcereference.DataSourceReference: - r"""Call the get data source reference method over HTTP. + ) -> datasourcereference.ListDataSourceReferencesResponse: + r"""Call the list data source + references method over HTTP. - Args: - request (~.datasourcereference.GetDataSourceReferenceRequest): - The request object. Request for the - GetDataSourceReference method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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 (~.datasourcereference.ListDataSourceReferencesRequest): + The request object. Request for the + ListDataSourceReferences method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: - ~.datasourcereference.DataSourceReference: - DataSourceReference is a reference to - a DataSource resource. + Returns: + ~.datasourcereference.ListDataSourceReferencesResponse: + Response for the + ListDataSourceReferences method. """ - http_options = _BaseBackupDRRestTransport._BaseGetDataSourceReference._get_http_options() - request, metadata = self._interceptor.pre_get_data_source_reference( + http_options = _BaseBackupDRRestTransport._BaseListDataSourceReferences._get_http_options() + request, metadata = self._interceptor.pre_list_data_source_references( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetDataSourceReference, - "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListDataSourceReferences, + "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5535,17 +11571,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetDataSourceReference", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListDataSourceReferences", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetDataSourceReference", + "rpcName": "ListDataSourceReferences", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetDataSourceReference._get_response( + response = BackupDRRestTransport._ListDataSourceReferences._get_response( self._host, metadata, query_params, @@ -5560,22 +11596,24 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = datasourcereference.DataSourceReference() - pb_resp = datasourcereference.DataSourceReference.pb(resp) + resp = datasourcereference.ListDataSourceReferencesResponse() + pb_resp = datasourcereference.ListDataSourceReferencesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_data_source_reference(resp) + resp = self._interceptor.post_list_data_source_references(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_data_source_reference_with_metadata( + resp, _ = self._interceptor.post_list_data_source_references_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = datasourcereference.DataSourceReference.to_json( - response + response_payload = ( + datasourcereference.ListDataSourceReferencesResponse.to_json( + response + ) ) except: response_payload = None @@ -5585,21 +11623,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.get_data_source_reference", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_data_source_references", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetDataSourceReference", + "rpcName": "ListDataSourceReferences", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetManagementServer( - _BaseBackupDRRestTransport._BaseGetManagementServer, BackupDRRestStub + class _ListDataSources( + _BaseBackupDRRestTransport._BaseListDataSources, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetManagementServer") + return hash("BackupDRRestTransport.ListDataSources") @staticmethod def _get_response( @@ -5625,18 +11663,18 @@ def _get_response( def __call__( self, - request: backupdr.GetManagementServerRequest, + request: backupvault.ListDataSourcesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupdr.ManagementServer: - r"""Call the get management server method over HTTP. + ) -> backupvault.ListDataSourcesResponse: + r"""Call the list data sources method over HTTP. Args: - request (~.backupdr.GetManagementServerRequest): - The request object. Request message for getting a - management server instance. + request (~.backupvault.ListDataSourcesRequest): + The request object. Request message for listing + DataSources. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5646,24 +11684,24 @@ def __call__( be of type `bytes`. Returns: - ~.backupdr.ManagementServer: - ManagementServer describes a single - BackupDR ManagementServer instance. + ~.backupvault.ListDataSourcesResponse: + Response message for listing + DataSources. """ http_options = ( - _BaseBackupDRRestTransport._BaseGetManagementServer._get_http_options() + _BaseBackupDRRestTransport._BaseListDataSources._get_http_options() ) - request, metadata = self._interceptor.pre_get_management_server( + request, metadata = self._interceptor.pre_list_data_sources( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetManagementServer, - "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListDataSources, + "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5687,17 +11725,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.GetManagementServer", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListDataSources", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetManagementServer", + "rpcName": "ListDataSources", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetManagementServer._get_response( + response = BackupDRRestTransport._ListDataSources._get_response( self._host, metadata, query_params, @@ -5712,21 +11750,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupdr.ManagementServer() - pb_resp = backupdr.ManagementServer.pb(resp) + resp = backupvault.ListDataSourcesResponse() + pb_resp = backupvault.ListDataSourcesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_management_server(resp) + resp = self._interceptor.post_list_data_sources(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_management_server_with_metadata( + resp, _ = self._interceptor.post_list_data_sources_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupdr.ManagementServer.to_json(response) + response_payload = backupvault.ListDataSourcesResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -5735,21 +11775,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.get_management_server", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_data_sources", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "GetManagementServer", + "rpcName": "ListDataSources", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _InitializeService( - _BaseBackupDRRestTransport._BaseInitializeService, BackupDRRestStub + class _ListManagementServers( + _BaseBackupDRRestTransport._BaseListManagementServers, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.InitializeService") + return hash("BackupDRRestTransport.ListManagementServers") @staticmethod def _get_response( @@ -5770,24 +11810,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: backupdr.InitializeServiceRequest, + request: backupdr.ListManagementServersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the initialize service method over HTTP. + ) -> backupdr.ListManagementServersResponse: + r"""Call the list management servers method over HTTP. Args: - request (~.backupdr.InitializeServiceRequest): - The request object. Request message for initializing the - service. + request (~.backupdr.ListManagementServersRequest): + The request object. Request message for listing + management servers. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5797,25 +11836,22 @@ 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. + ~.backupdr.ListManagementServersResponse: + Response message for listing + management servers. """ - http_options = ( - _BaseBackupDRRestTransport._BaseInitializeService._get_http_options() - ) - request, metadata = self._interceptor.pre_initialize_service( + http_options = _BaseBackupDRRestTransport._BaseListManagementServers._get_http_options() + request, metadata = self._interceptor.pre_list_management_servers( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseInitializeService, - "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListManagementServers, + "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5839,24 +11875,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.InitializeService", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListManagementServers", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "InitializeService", + "rpcName": "ListManagementServers", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._InitializeService._get_response( + response = BackupDRRestTransport._ListManagementServers._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -5865,19 +11900,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 = backupdr.ListManagementServersResponse() + pb_resp = backupdr.ListManagementServersResponse.pb(resp) - resp = self._interceptor.post_initialize_service(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_management_servers(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_initialize_service_with_metadata( + resp, _ = self._interceptor.post_list_management_servers_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 = backupdr.ListManagementServersResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -5886,21 +11925,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.initialize_service", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_management_servers", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "InitializeService", + "rpcName": "ListManagementServers", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackupPlanAssociations( - _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, BackupDRRestStub + class _ListRestoreTemplateExecutions( + _BaseBackupDRRestTransport._BaseListRestoreTemplateExecutions, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackupPlanAssociations") + return hash("BackupDRRestTransport.ListRestoreTemplateExecutions") @staticmethod def _get_response( @@ -5926,19 +11965,19 @@ def _get_response( def __call__( self, - request: backupplanassociation.ListBackupPlanAssociationsRequest, + request: restore_template_execution.ListRestoreTemplateExecutionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplanassociation.ListBackupPlanAssociationsResponse: - r"""Call the list backup plan - associations method over HTTP. + ) -> restore_template_execution.ListRestoreTemplateExecutionsResponse: + r"""Call the list restore template + executions method over HTTP. Args: - request (~.backupplanassociation.ListBackupPlanAssociationsRequest): - The request object. Request message for List - BackupPlanAssociation + request (~.restore_template_execution.ListRestoreTemplateExecutionsRequest): + The request object. Request message for listing + RestoreTemplateExecutions. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5948,22 +11987,22 @@ def __call__( be of type `bytes`. Returns: - ~.backupplanassociation.ListBackupPlanAssociationsResponse: - Response message for List - BackupPlanAssociation + ~.restore_template_execution.ListRestoreTemplateExecutionsResponse: + Response message for listing + RestoreTemplateExecutions. """ - http_options = _BaseBackupDRRestTransport._BaseListBackupPlanAssociations._get_http_options() - request, metadata = self._interceptor.pre_list_backup_plan_associations( + http_options = _BaseBackupDRRestTransport._BaseListRestoreTemplateExecutions._get_http_options() + request, metadata = self._interceptor.pre_list_restore_template_executions( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, - "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListRestoreTemplateExecutions, + "_BaseListRestoreTemplateExecutions__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5987,23 +12026,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackupPlanAssociations", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListRestoreTemplateExecutions", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackupPlanAssociations", + "rpcName": "ListRestoreTemplateExecutions", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackupPlanAssociations._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + BackupDRRestTransport._ListRestoreTemplateExecutions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -6012,15 +12053,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplanassociation.ListBackupPlanAssociationsResponse() - pb_resp = backupplanassociation.ListBackupPlanAssociationsResponse.pb(resp) + resp = restore_template_execution.ListRestoreTemplateExecutionsResponse() + pb_resp = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse.pb( + resp + ) + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_backup_plan_associations(resp) + resp = self._interceptor.post_list_restore_template_executions(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_list_backup_plan_associations_with_metadata( + self._interceptor.post_list_restore_template_executions_with_metadata( resp, response_metadata ) ) @@ -6028,7 +12073,7 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupplanassociation.ListBackupPlanAssociationsResponse.to_json( + response_payload = restore_template_execution.ListRestoreTemplateExecutionsResponse.to_json( response ) except: @@ -6039,21 +12084,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backup_plan_associations", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_restore_template_executions", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackupPlanAssociations", + "rpcName": "ListRestoreTemplateExecutions", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackupPlanRevisions( - _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, BackupDRRestStub + class _ListRestoreTemplates( + _BaseBackupDRRestTransport._BaseListRestoreTemplates, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackupPlanRevisions") + return hash("BackupDRRestTransport.ListRestoreTemplates") @staticmethod def _get_response( @@ -6079,44 +12124,45 @@ def _get_response( def __call__( self, - request: backupplan.ListBackupPlanRevisionsRequest, + request: restore_template.ListRestoreTemplatesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplan.ListBackupPlanRevisionsResponse: - r"""Call the list backup plan - revisions method over HTTP. + ) -> restore_template.ListRestoreTemplatesResponse: + r"""Call the list restore templates method over HTTP. - Args: - request (~.backupplan.ListBackupPlanRevisionsRequest): - The request object. The request message for getting a list of - ``BackupPlanRevision``. - 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 (~.restore_template.ListRestoreTemplatesRequest): + The request object. Request message for listing + RestoreTemplates. + 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: - ~.backupplan.ListBackupPlanRevisionsResponse: - The response message for getting a list of - ``BackupPlanRevision``. + Returns: + ~.restore_template.ListRestoreTemplatesResponse: + Response message for listing + RestoreTemplates. """ - http_options = _BaseBackupDRRestTransport._BaseListBackupPlanRevisions._get_http_options() - request, metadata = self._interceptor.pre_list_backup_plan_revisions( + http_options = ( + _BaseBackupDRRestTransport._BaseListRestoreTemplates._get_http_options() + ) + request, metadata = self._interceptor.pre_list_restore_templates( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, - "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListRestoreTemplates, + "_BaseListRestoreTemplates__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6140,17 +12186,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackupPlanRevisions", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListRestoreTemplates", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackupPlanRevisions", + "rpcName": "ListRestoreTemplates", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackupPlanRevisions._get_response( + response = BackupDRRestTransport._ListRestoreTemplates._get_response( self._host, metadata, query_params, @@ -6165,14 +12211,14 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplan.ListBackupPlanRevisionsResponse() - pb_resp = backupplan.ListBackupPlanRevisionsResponse.pb(resp) + resp = restore_template.ListRestoreTemplatesResponse() + pb_resp = restore_template.ListRestoreTemplatesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_backup_plan_revisions(resp) + resp = self._interceptor.post_list_restore_templates(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_backup_plan_revisions_with_metadata( + resp, _ = self._interceptor.post_list_restore_templates_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -6180,7 +12226,7 @@ def __call__( ): # pragma: NO COVER try: response_payload = ( - backupplan.ListBackupPlanRevisionsResponse.to_json(response) + restore_template.ListRestoreTemplatesResponse.to_json(response) ) except: response_payload = None @@ -6190,21 +12236,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backup_plan_revisions", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_restore_templates", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackupPlanRevisions", + "rpcName": "ListRestoreTemplates", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackupPlans( - _BaseBackupDRRestTransport._BaseListBackupPlans, BackupDRRestStub + class _ListRestoreVerificationPlanAssociations( + _BaseBackupDRRestTransport._BaseListRestoreVerificationPlanAssociations, + BackupDRRestStub, ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackupPlans") + return hash("BackupDRRestTransport.ListRestoreVerificationPlanAssociations") @staticmethod def _get_response( @@ -6230,44 +12277,46 @@ def _get_response( def __call__( self, - request: backupplan.ListBackupPlansRequest, + request: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplan.ListBackupPlansResponse: - r"""Call the list backup plans method over HTTP. + ) -> restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse: + r"""Call the list restore verification + plan associations method over HTTP. - Args: - request (~.backupplan.ListBackupPlansRequest): - The request object. The request message for getting a list ``BackupPlan``. - 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 (~.restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest): + The request object. Request message for + ListRestoreVerificationPlanAssociations. + 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: - ~.backupplan.ListBackupPlansResponse: - The response message for getting a list of - ``BackupPlan``. + Returns: + ~.restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse: + Response message for + ListRestoreVerificationPlanAssociations. """ - http_options = ( - _BaseBackupDRRestTransport._BaseListBackupPlans._get_http_options() - ) - request, metadata = self._interceptor.pre_list_backup_plans( - request, metadata + http_options = _BaseBackupDRRestTransport._BaseListRestoreVerificationPlanAssociations._get_http_options() + request, metadata = ( + self._interceptor.pre_list_restore_verification_plan_associations( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackupPlans, - "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListRestoreVerificationPlanAssociations, + "_BaseListRestoreVerificationPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6291,17 +12340,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackupPlans", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListRestoreVerificationPlanAssociations", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackupPlans", + "rpcName": "ListRestoreVerificationPlanAssociations", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackupPlans._get_response( + response = BackupDRRestTransport._ListRestoreVerificationPlanAssociations._get_response( self._host, metadata, query_params, @@ -6316,21 +12365,27 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplan.ListBackupPlansResponse() - pb_resp = backupplan.ListBackupPlansResponse.pb(resp) + resp = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + pb_resp = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.pb( + resp + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_backup_plans(resp) + resp = self._interceptor.post_list_restore_verification_plan_associations( + resp + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_backup_plans_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_list_restore_verification_plan_associations_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupplan.ListBackupPlansResponse.to_json( + response_payload = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.to_json( response ) except: @@ -6341,19 +12396,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backup_plans", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_restore_verification_plan_associations", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackupPlans", + "rpcName": "ListRestoreVerificationPlanAssociations", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackups(_BaseBackupDRRestTransport._BaseListBackups, BackupDRRestStub): + class _ListRestoreVerificationPlans( + _BaseBackupDRRestTransport._BaseListRestoreVerificationPlans, BackupDRRestStub + ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackups") + return hash("BackupDRRestTransport.ListRestoreVerificationPlans") @staticmethod def _get_response( @@ -6379,40 +12436,44 @@ def _get_response( def __call__( self, - request: backupvault.ListBackupsRequest, + request: restore_verification_plan.ListRestoreVerificationPlansRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.ListBackupsResponse: - r"""Call the list backups method over HTTP. + ) -> restore_verification_plan.ListRestoreVerificationPlansResponse: + r"""Call the list restore verification + plans method over HTTP. + + Args: + request (~.restore_verification_plan.ListRestoreVerificationPlansRequest): + The request object. The request message for getting a list of + ``RestoreVerificationPlans``. + 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 (~.backupvault.ListBackupsRequest): - The request object. Request message for listing Backups. - 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: + ~.restore_verification_plan.ListRestoreVerificationPlansResponse: + The response message for getting a list of + ``RestoreVerificationPlans``. - Returns: - ~.backupvault.ListBackupsResponse: - Response message for listing Backups. """ - http_options = ( - _BaseBackupDRRestTransport._BaseListBackups._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseListRestoreVerificationPlans._get_http_options() + request, metadata = self._interceptor.pre_list_restore_verification_plans( + request, metadata ) - request, metadata = self._interceptor.pre_list_backups(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackups, - "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListRestoreVerificationPlans, + "_BaseListRestoreVerificationPlans__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6436,23 +12497,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackups", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListRestoreVerificationPlans", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackups", + "rpcName": "ListRestoreVerificationPlans", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackups._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + BackupDRRestTransport._ListRestoreVerificationPlans._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -6461,21 +12524,27 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.ListBackupsResponse() - pb_resp = backupvault.ListBackupsResponse.pb(resp) + resp = restore_verification_plan.ListRestoreVerificationPlansResponse() + pb_resp = restore_verification_plan.ListRestoreVerificationPlansResponse.pb( + resp + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_backups(resp) + resp = self._interceptor.post_list_restore_verification_plans(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_backups_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_list_restore_verification_plans_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.ListBackupsResponse.to_json(response) + response_payload = restore_verification_plan.ListRestoreVerificationPlansResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -6484,21 +12553,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backups", + "Received response for google.cloud.backupdr_v1.BackupDRClient.list_restore_verification_plans", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackups", + "rpcName": "ListRestoreVerificationPlans", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackupVaults( - _BaseBackupDRRestTransport._BaseListBackupVaults, BackupDRRestStub + class _RestoreBackup( + _BaseBackupDRRestTransport._BaseRestoreBackup, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackupVaults") + return hash("BackupDRRestTransport.RestoreBackup") @staticmethod def _get_response( @@ -6519,23 +12588,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: backupvault.ListBackupVaultsRequest, + request: backupvault.RestoreBackupRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.ListBackupVaultsResponse: - r"""Call the list backup vaults method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the restore backup method over HTTP. Args: - request (~.backupvault.ListBackupVaultsRequest): - The request object. Request message for listing - backupvault stores. + request (~.backupvault.RestoreBackupRequest): + The request object. Request message for restoring from a + Backup. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6545,24 +12615,23 @@ def __call__( be of type `bytes`. Returns: - ~.backupvault.ListBackupVaultsResponse: - Response message for listing - BackupVaults. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseBackupDRRestTransport._BaseListBackupVaults._get_http_options() - ) - request, metadata = self._interceptor.pre_list_backup_vaults( - request, metadata + _BaseBackupDRRestTransport._BaseRestoreBackup._get_http_options() ) + request, metadata = self._interceptor.pre_restore_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackupVaults, - "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseRestoreBackup, + "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6586,23 +12655,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListBackupVaults", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.RestoreBackup", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackupVaults", + "rpcName": "RestoreBackup", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackupVaults._get_response( + response = BackupDRRestTransport._RestoreBackup._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -6611,23 +12681,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.ListBackupVaultsResponse() - pb_resp = backupvault.ListBackupVaultsResponse.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_backup_vaults(resp) + resp = self._interceptor.post_restore_backup(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_backup_vaults_with_metadata( + resp, _ = self._interceptor.post_restore_backup_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.ListBackupVaultsResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -6636,21 +12702,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.list_backup_vaults", + "Received response for google.cloud.backupdr_v1.BackupDRClient.restore_backup", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListBackupVaults", + "rpcName": "RestoreBackup", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListDataSourceReferences( - _BaseBackupDRRestTransport._BaseListDataSourceReferences, BackupDRRestStub + class _RunRestoreTemplate( + _BaseBackupDRRestTransport._BaseRunRestoreTemplate, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListDataSourceReferences") + return hash("BackupDRRestTransport.RunRestoreTemplate") @staticmethod def _get_response( @@ -6671,49 +12737,52 @@ 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: datasourcereference.ListDataSourceReferencesRequest, + request: restore_template.RunRestoreTemplateRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasourcereference.ListDataSourceReferencesResponse: - r"""Call the list data source - references method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the run restore template method over HTTP. - Args: - request (~.datasourcereference.ListDataSourceReferencesRequest): - The request object. Request for the - ListDataSourceReferences method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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 (~.restore_template.RunRestoreTemplateRequest): + The request object. Request message for running a + RestoreTemplate. + 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: - ~.datasourcereference.ListDataSourceReferencesResponse: - Response for the - ListDataSourceReferences method. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseListDataSourceReferences._get_http_options() - request, metadata = self._interceptor.pre_list_data_source_references( + http_options = ( + _BaseBackupDRRestTransport._BaseRunRestoreTemplate._get_http_options() + ) + request, metadata = self._interceptor.pre_run_restore_template( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListDataSourceReferences, - "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseRunRestoreTemplate, + "_BaseRunRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6737,23 +12806,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListDataSourceReferences", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.RunRestoreTemplate", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListDataSourceReferences", + "rpcName": "RunRestoreTemplate", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListDataSourceReferences._get_response( + response = BackupDRRestTransport._RunRestoreTemplate._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -6762,25 +12832,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = datasourcereference.ListDataSourceReferencesResponse() - pb_resp = datasourcereference.ListDataSourceReferencesResponse.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_data_source_references(resp) + resp = self._interceptor.post_run_restore_template(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_data_source_references_with_metadata( + resp, _ = self._interceptor.post_run_restore_template_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - datasourcereference.ListDataSourceReferencesResponse.to_json( - response - ) - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -6789,21 +12853,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.list_data_source_references", + "Received response for google.cloud.backupdr_v1.BackupDRClient.run_restore_template", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListDataSourceReferences", + "rpcName": "RunRestoreTemplate", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListDataSources( - _BaseBackupDRRestTransport._BaseListDataSources, BackupDRRestStub + class _TriggerBackup( + _BaseBackupDRRestTransport._BaseTriggerBackup, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListDataSources") + return hash("BackupDRRestTransport.TriggerBackup") @staticmethod def _get_response( @@ -6824,23 +12888,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: backupvault.ListDataSourcesRequest, + request: backupplanassociation.TriggerBackupRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.ListDataSourcesResponse: - r"""Call the list data sources method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the trigger backup method over HTTP. Args: - request (~.backupvault.ListDataSourcesRequest): - The request object. Request message for listing - DataSources. + request (~.backupplanassociation.TriggerBackupRequest): + The request object. Request message for triggering a + backup. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6850,24 +12915,23 @@ def __call__( be of type `bytes`. Returns: - ~.backupvault.ListDataSourcesResponse: - Response message for listing - DataSources. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseBackupDRRestTransport._BaseListDataSources._get_http_options() - ) - request, metadata = self._interceptor.pre_list_data_sources( - request, metadata + _BaseBackupDRRestTransport._BaseTriggerBackup._get_http_options() ) + request, metadata = self._interceptor.pre_trigger_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListDataSources, - "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseTriggerBackup, + "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6891,23 +12955,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListDataSources", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.TriggerBackup", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListDataSources", + "rpcName": "TriggerBackup", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListDataSources._get_response( + response = BackupDRRestTransport._TriggerBackup._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -6916,23 +12981,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.ListDataSourcesResponse() - pb_resp = backupvault.ListDataSourcesResponse.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_data_sources(resp) + resp = self._interceptor.post_trigger_backup(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_data_sources_with_metadata( + resp, _ = self._interceptor.post_trigger_backup_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.ListDataSourcesResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -6941,21 +13002,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.list_data_sources", + "Received response for google.cloud.backupdr_v1.BackupDRClient.trigger_backup", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListDataSources", + "rpcName": "TriggerBackup", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListManagementServers( - _BaseBackupDRRestTransport._BaseListManagementServers, BackupDRRestStub + class _TriggerRestoreCleanup( + _BaseBackupDRRestTransport._BaseTriggerRestoreCleanup, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListManagementServers") + return hash("BackupDRRestTransport.TriggerRestoreCleanup") @staticmethod def _get_response( @@ -6976,23 +13037,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: backupdr.ListManagementServersRequest, + request: restore_template_execution.TriggerRestoreCleanupRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupdr.ListManagementServersResponse: - r"""Call the list management servers method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the trigger restore cleanup method over HTTP. Args: - request (~.backupdr.ListManagementServersRequest): - The request object. Request message for listing - management servers. + request (~.restore_template_execution.TriggerRestoreCleanupRequest): + The request object. Request message for triggering a + restore cleanup. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7002,22 +13064,23 @@ def __call__( be of type `bytes`. Returns: - ~.backupdr.ListManagementServersResponse: - Response message for listing - management servers. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseListManagementServers._get_http_options() - request, metadata = self._interceptor.pre_list_management_servers( + http_options = _BaseBackupDRRestTransport._BaseTriggerRestoreCleanup._get_http_options() + request, metadata = self._interceptor.pre_trigger_restore_cleanup( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListManagementServers, - "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseTriggerRestoreCleanup, + "_BaseTriggerRestoreCleanup__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7041,23 +13104,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.ListManagementServers", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.TriggerRestoreCleanup", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListManagementServers", + "rpcName": "TriggerRestoreCleanup", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListManagementServers._get_response( + response = BackupDRRestTransport._TriggerRestoreCleanup._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -7066,23 +13130,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupdr.ListManagementServersResponse() - pb_resp = backupdr.ListManagementServersResponse.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_management_servers(resp) + resp = self._interceptor.post_trigger_restore_cleanup(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_management_servers_with_metadata( + resp, _ = self._interceptor.post_trigger_restore_cleanup_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupdr.ListManagementServersResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -7091,21 +13151,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.list_management_servers", + "Received response for google.cloud.backupdr_v1.BackupDRClient.trigger_restore_cleanup", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "ListManagementServers", + "rpcName": "TriggerRestoreCleanup", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _RestoreBackup( - _BaseBackupDRRestTransport._BaseRestoreBackup, BackupDRRestStub + class _TriggerRestoreVerification( + _BaseBackupDRRestTransport._BaseTriggerRestoreVerification, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.RestoreBackup") + return hash("BackupDRRestTransport.TriggerRestoreVerification") @staticmethod def _get_response( @@ -7132,44 +13192,45 @@ def _get_response( def __call__( self, - request: backupvault.RestoreBackupRequest, + request: restore_verification_plan_association.TriggerRestoreVerificationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the restore backup method over HTTP. + r"""Call the trigger restore + verification method over HTTP. - Args: - request (~.backupvault.RestoreBackupRequest): - The request object. Request message for restoring from a - Backup. - 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 (~.restore_verification_plan_association.TriggerRestoreVerificationRequest): + The request object. Request message for + TriggerRestoreVerification. + 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. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseBackupDRRestTransport._BaseRestoreBackup._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseTriggerRestoreVerification._get_http_options() + request, metadata = self._interceptor.pre_trigger_restore_verification( + request, metadata ) - request, metadata = self._interceptor.pre_restore_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseRestoreBackup, - "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseTriggerRestoreVerification, + "_BaseTriggerRestoreVerification__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7193,17 +13254,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.RestoreBackup", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.TriggerRestoreVerification", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "RestoreBackup", + "rpcName": "TriggerRestoreVerification", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._RestoreBackup._get_response( + response = BackupDRRestTransport._TriggerRestoreVerification._get_response( self._host, metadata, query_params, @@ -7222,9 +13283,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_restore_backup(resp) + resp = self._interceptor.post_trigger_restore_verification(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_restore_backup_with_metadata( + resp, _ = self._interceptor.post_trigger_restore_verification_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -7240,21 +13301,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.restore_backup", + "Received response for google.cloud.backupdr_v1.BackupDRClient.trigger_restore_verification", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "RestoreBackup", + "rpcName": "TriggerRestoreVerification", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _TriggerBackup( - _BaseBackupDRRestTransport._BaseTriggerBackup, BackupDRRestStub + class _UpdateAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseUpdateAutoProtectionPolicy, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.TriggerBackup") + return hash("BackupDRRestTransport.UpdateAutoProtectionPolicy") @staticmethod def _get_response( @@ -7281,44 +13342,45 @@ def _get_response( def __call__( self, - request: backupplanassociation.TriggerBackupRequest, + request: autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the trigger backup method over HTTP. + r"""Call the update auto protection + policy method over HTTP. - Args: - request (~.backupplanassociation.TriggerBackupRequest): - The request object. Request message for triggering a - backup. - 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 (~.autoprotectionpolicy.UpdateAutoProtectionPolicyRequest): + The request object. Request message for updating an + AutoProtectionPolicy. + 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. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseBackupDRRestTransport._BaseTriggerBackup._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseUpdateAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_update_auto_protection_policy( + request, metadata ) - request, metadata = self._interceptor.pre_trigger_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseTriggerBackup, - "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseUpdateAutoProtectionPolicy, + "_BaseUpdateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7342,17 +13404,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1.BackupDRClient.TriggerBackup", + f"Sending request for google.cloud.backupdr_v1.BackupDRClient.UpdateAutoProtectionPolicy", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "TriggerBackup", + "rpcName": "UpdateAutoProtectionPolicy", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._TriggerBackup._get_response( + response = BackupDRRestTransport._UpdateAutoProtectionPolicy._get_response( self._host, metadata, query_params, @@ -7371,10 +13433,12 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_trigger_backup(resp) + resp = self._interceptor.post_update_auto_protection_policy(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_trigger_backup_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_update_auto_protection_policy_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -7389,10 +13453,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1.BackupDRClient.trigger_backup", + "Received response for google.cloud.backupdr_v1.BackupDRClient.update_auto_protection_policy", extra={ "serviceName": "google.cloud.backupdr.v1.BackupDR", - "rpcName": "TriggerBackup", + "rpcName": "UpdateAutoProtectionPolicy", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -8151,6 +14215,181 @@ def __call__( ) return resp + class _UpdateRestoreTemplate( + _BaseBackupDRRestTransport._BaseUpdateRestoreTemplate, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.UpdateRestoreTemplate") + + @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: gcb_restore_template.UpdateRestoreTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update restore template method over HTTP. + + Args: + request (~.gcb_restore_template.UpdateRestoreTemplateRequest): + The request object. Request message for updating a + RestoreTemplate instance. + 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 = _BaseBackupDRRestTransport._BaseUpdateRestoreTemplate._get_http_options() + request, metadata = self._interceptor.pre_update_restore_template( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseUpdateRestoreTemplate, + "_BaseUpdateRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1.BackupDRClient.UpdateRestoreTemplate", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "UpdateRestoreTemplate", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._UpdateRestoreTemplate._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_update_restore_template(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_restore_template_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.backupdr_v1.BackupDRClient.update_restore_template", + extra={ + "serviceName": "google.cloud.backupdr.v1.BackupDR", + "rpcName": "UpdateRestoreTemplate", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def create_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.CreateAutoProtectionPolicyRequest], + 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._CreateAutoProtectionPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest], + 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._CreateAutoProtectionPolicyBinding( + self._session, self._host, self._interceptor + ) # type: ignore + @property def create_backup_plan( self, @@ -8190,6 +14429,57 @@ def create_management_server( self._session, self._host, self._interceptor ) # type: ignore + @property + def create_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.CreateRestoreTemplateRequest], 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._CreateRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_restore_verification_plan( + self, + ) -> Callable[ + [gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest], + 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._CreateRestoreVerificationPlan( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_restore_verification_plan_association( + self, + ) -> Callable[ + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest + ], + 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._CreateRestoreVerificationPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.DeleteAutoProtectionPolicyRequest], + 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._DeleteAutoProtectionPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + @property def delete_backup( self, @@ -8237,6 +14527,44 @@ def delete_management_server( self._session, self._host, self._interceptor ) # type: ignore + @property + def delete_restore_template( + self, + ) -> Callable[ + [restore_template.DeleteRestoreTemplateRequest], 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._DeleteRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.DeleteRestoreVerificationPlanRequest], + 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._DeleteRestoreVerificationPlan( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest + ], + 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._DeleteRestoreVerificationPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + @property def fetch_backup_plan_associations_for_resource_type( self, @@ -8289,6 +14617,32 @@ def fetch_usable_backup_vaults( self._session, self._host, self._interceptor ) # type: ignore + @property + def get_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.GetAutoProtectionPolicyRequest], + autoprotectionpolicy.AutoProtectionPolicy, + ]: + # 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._GetAutoProtectionPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest], + autoprotectionpolicybinding.AutoProtectionPolicyBinding, + ]: + # 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._GetAutoProtectionPolicyBinding( + self._session, self._host, self._interceptor + ) # type: ignore + @property def get_backup( self, @@ -8365,6 +14719,57 @@ def get_management_server( # In C++ this would require a dynamic_cast return self._GetManagementServer(self._session, self._host, self._interceptor) # type: ignore + @property + def get_restore_template( + self, + ) -> Callable[ + [restore_template.GetRestoreTemplateRequest], restore_template.RestoreTemplate + ]: + # 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._GetRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_restore_template_execution( + self, + ) -> Callable[ + [restore_template_execution.GetRestoreTemplateExecutionRequest], + restore_template_execution.RestoreTemplateExecution, + ]: + # 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._GetRestoreTemplateExecution( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.GetRestoreVerificationPlanRequest], + restore_verification_plan.RestoreVerificationPlan, + ]: + # 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._GetRestoreVerificationPlan( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest + ], + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ]: + # 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._GetRestoreVerificationPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + @property def initialize_service( self, @@ -8373,6 +14778,58 @@ def initialize_service( # In C++ this would require a dynamic_cast return self._InitializeService(self._session, self._host, self._interceptor) # type: ignore + @property + def initiate_delete_auto_protection_policy_binding( + self, + ) -> Callable[ + [autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest], + 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._InitiateDeleteAutoProtectionPolicyBinding( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_applied_auto_protection_policies( + self, + ) -> Callable[ + [appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest], + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse, + ]: + # 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._ListAppliedAutoProtectionPolicies( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_auto_protection_policies( + self, + ) -> Callable[ + [autoprotectionpolicy.ListAutoProtectionPoliciesRequest], + autoprotectionpolicy.ListAutoProtectionPoliciesResponse, + ]: + # 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._ListAutoProtectionPolicies( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_auto_protection_policy_bindings( + self, + ) -> Callable[ + [autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest], + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse, + ]: + # 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._ListAutoProtectionPolicyBindings( + self._session, self._host, self._interceptor + ) # type: ignore + @property def list_backup_plan_associations( self, @@ -8427,6 +14884,19 @@ def list_backup_vaults( # In C++ this would require a dynamic_cast return self._ListBackupVaults(self._session, self._host, self._interceptor) # type: ignore + @property + def list_binding_matching_resources( + self, + ) -> Callable[ + [bindingmatchingresource.ListBindingMatchingResourcesRequest], + bindingmatchingresource.ListBindingMatchingResourcesResponse, + ]: + # 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._ListBindingMatchingResources( + self._session, self._host, self._interceptor + ) # type: ignore + @property def list_data_source_references( self, @@ -8460,6 +14930,58 @@ def list_management_servers( # In C++ this would require a dynamic_cast return self._ListManagementServers(self._session, self._host, self._interceptor) # type: ignore + @property + def list_restore_template_executions( + self, + ) -> Callable[ + [restore_template_execution.ListRestoreTemplateExecutionsRequest], + restore_template_execution.ListRestoreTemplateExecutionsResponse, + ]: + # 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._ListRestoreTemplateExecutions( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_restore_templates( + self, + ) -> Callable[ + [restore_template.ListRestoreTemplatesRequest], + restore_template.ListRestoreTemplatesResponse, + ]: + # 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._ListRestoreTemplates(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_restore_verification_plan_associations( + self, + ) -> Callable[ + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest + ], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + ]: + # 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._ListRestoreVerificationPlanAssociations( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_restore_verification_plans( + self, + ) -> Callable[ + [restore_verification_plan.ListRestoreVerificationPlansRequest], + restore_verification_plan.ListRestoreVerificationPlansResponse, + ]: + # 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._ListRestoreVerificationPlans( + self._session, self._host, self._interceptor + ) # type: ignore + @property def restore_backup( self, @@ -8468,6 +14990,16 @@ def restore_backup( # In C++ this would require a dynamic_cast return self._RestoreBackup(self._session, self._host, self._interceptor) # type: ignore + @property + def run_restore_template( + self, + ) -> Callable[ + [restore_template.RunRestoreTemplateRequest], 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._RunRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + @property def trigger_backup( self, @@ -8478,6 +15010,43 @@ def trigger_backup( # In C++ this would require a dynamic_cast return self._TriggerBackup(self._session, self._host, self._interceptor) # type: ignore + @property + def trigger_restore_cleanup( + self, + ) -> Callable[ + [restore_template_execution.TriggerRestoreCleanupRequest], + 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._TriggerRestoreCleanup(self._session, self._host, self._interceptor) # type: ignore + + @property + def trigger_restore_verification( + self, + ) -> Callable[ + [restore_verification_plan_association.TriggerRestoreVerificationRequest], + 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._TriggerRestoreVerification( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def update_auto_protection_policy( + self, + ) -> Callable[ + [autoprotectionpolicy.UpdateAutoProtectionPolicyRequest], + 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._UpdateAutoProtectionPolicy( + self._session, self._host, self._interceptor + ) # type: ignore + @property def update_backup( self, @@ -8523,6 +15092,16 @@ def update_data_source( # In C++ this would require a dynamic_cast return self._UpdateDataSource(self._session, self._host, self._interceptor) # type: ignore + @property + def update_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.UpdateRestoreTemplateRequest], 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._UpdateRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest_base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest_base.py index e5257d0312a2..f2d8fbc4c387 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest_base.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/services/backup_dr/transports/rest_base.py @@ -27,11 +27,26 @@ from google.protobuf import json_format from google.cloud.backupdr_v1.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, backupdr, backupplan, backupplanassociation, backupvault, + bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .base import DEFAULT_CLIENT_INFO, BackupDRTransport @@ -99,6 +114,44 @@ def __init__( api_audience=api_audience, ) + class _BaseCreateAutoProtectionPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "autoProtectionPolicyId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/autoProtectionPolicies", + "body": "auto_protection_policy", + }, + ] + return http_options + + class _BaseCreateAutoProtectionPolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "autoProtectionPolicyBindingId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/autoProtectionPolicies/*}/bindings", + "body": "auto_protection_policy_binding", + }, + ] + return http_options + class _BaseCreateBackupPlan: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -175,6 +228,79 @@ def _get_http_options(): ] return http_options + class _BaseCreateRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "restoreTemplateId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/restoreTemplates", + "body": "restore_template", + }, + ] + return http_options + + class _BaseCreateRestoreVerificationPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "restoreVerificationPlanId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/restoreVerificationPlans", + "body": "restore_verification_plan", + }, + ] + return http_options + + class _BaseCreateRestoreVerificationPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "restoreVerificationPlanAssociationId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/restoreVerificationPlans/*}/associations", + "body": "restore_verification_plan_association", + }, + ] + return http_options + + class _BaseDeleteAutoProtectionPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/autoProtectionPolicies/*}", + }, + ] + return http_options + class _BaseDeleteBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -255,6 +381,54 @@ def _get_http_options(): ] return http_options + class _BaseDeleteRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/restoreTemplates/*}", + }, + ] + return http_options + + class _BaseDeleteRestoreVerificationPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/restoreVerificationPlans/*}", + }, + ] + return http_options + + class _BaseDeleteRestoreVerificationPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/restoreVerificationPlans/*/associations/*}", + }, + ] + return http_options + class _BaseFetchBackupPlanAssociationsForResourceType: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -325,6 +499,38 @@ def _get_http_options(): ] return http_options + class _BaseGetAutoProtectionPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/autoProtectionPolicies/*}", + }, + ] + return http_options + + class _BaseGetAutoProtectionPolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}", + }, + ] + return http_options + class _BaseGetBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -453,6 +659,70 @@ def _get_http_options(): ] return http_options + class _BaseGetRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/restoreTemplates/*}", + }, + ] + return http_options + + class _BaseGetRestoreTemplateExecution: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/restoreTemplates/*/executions/*}", + }, + ] + return http_options + + class _BaseGetRestoreVerificationPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/restoreVerificationPlans/*}", + }, + ] + return http_options + + class _BaseGetRestoreVerificationPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/restoreVerificationPlans/*/associations/*}", + }, + ] + return http_options + class _BaseInitializeService: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -470,6 +740,71 @@ def _get_http_options(): ] return http_options + class _BaseInitiateDeleteAutoProtectionPolicyBinding: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}:initiateDelete", + "body": "*", + }, + ] + return http_options + + class _BaseListAppliedAutoProtectionPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/appliedAutoProtectionPolicies", + }, + ] + return http_options + + class _BaseListAutoProtectionPolicies: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/autoProtectionPolicies", + }, + ] + return http_options + + class _BaseListAutoProtectionPolicyBindings: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/autoProtectionPolicies/*}/bindings", + }, + ] + return http_options + class _BaseListBackupPlanAssociations: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -550,6 +885,22 @@ def _get_http_options(): ] return http_options + class _BaseListBindingMatchingResources: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}/matchingResources", + }, + ] + return http_options + class _BaseListDataSourceReferences: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -598,6 +949,70 @@ def _get_http_options(): ] return http_options + class _BaseListRestoreTemplateExecutions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/restoreTemplates/*}/executions", + }, + ] + return http_options + + class _BaseListRestoreTemplates: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/restoreTemplates", + }, + ] + return http_options + + class _BaseListRestoreVerificationPlanAssociations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/restoreVerificationPlans/*}/associations", + }, + ] + return http_options + + class _BaseListRestoreVerificationPlans: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/restoreVerificationPlans", + }, + ] + return http_options + class _BaseRestoreBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -615,6 +1030,23 @@ def _get_http_options(): ] return http_options + class _BaseRunRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/restoreTemplates/*}:run", + "body": "*", + }, + ] + return http_options + class _BaseTriggerBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -632,6 +1064,57 @@ def _get_http_options(): ] return http_options + class _BaseTriggerRestoreCleanup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/restoreTemplates/*/executions/*}:triggerRestoreCleanup", + "body": "*", + }, + ] + return http_options + + class _BaseTriggerRestoreVerification: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/restoreVerificationPlans/*/associations/*}:triggerRestoreVerification", + "body": "*", + }, + ] + return http_options + + class _BaseUpdateAutoProtectionPolicy: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{auto_protection_policy.name=projects/*/locations/*/autoProtectionPolicies/*}", + "body": "auto_protection_policy", + }, + ] + return http_options + class _BaseUpdateBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -727,6 +1210,23 @@ def _get_http_options(): ] return http_options + class _BaseUpdateRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{restore_template.name=projects/*/locations/*/restoreTemplates/*}", + "body": "restore_template", + }, + ] + return http_options + class _BaseGetLocation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/__init__.py index 382b5e7e0551..b6105a8ce250 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/__init__.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/__init__.py @@ -13,6 +13,35 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .appliedautoprotectionpolicy import ( + AppliedAutoProtectionPolicy, + ListAppliedAutoProtectionPoliciesRequest, + ListAppliedAutoProtectionPoliciesResponse, +) +from .autoprotectionpolicy import ( + AutoProtectionPolicy, + BackupPlanDetail, + BindingSummary, + CreateAutoProtectionPolicyRequest, + Criteria, + DeleteAutoProtectionPolicyRequest, + GetAutoProtectionPolicyRequest, + KeyValuePair, + ListAutoProtectionPoliciesRequest, + ListAutoProtectionPoliciesResponse, + MatchingCondition, + PolicyEvaluationSummary, + UpdateAutoProtectionPolicyRequest, +) +from .autoprotectionpolicybinding import ( + AutoProtectionPolicyBinding, + BindingEvaluationSummary, + CreateAutoProtectionPolicyBindingRequest, + GetAutoProtectionPolicyBindingRequest, + InitiateDeleteAutoProtectionPolicyBindingRequest, + ListAutoProtectionPolicyBindingsRequest, + ListAutoProtectionPolicyBindingsResponse, +) from .backupdr import ( CreateManagementServerRequest, DeleteManagementServerRequest, @@ -97,6 +126,7 @@ UpdateBackupRequest, UpdateBackupVaultRequest, UpdateDataSourceRequest, + VerificationSummary, ) from .backupvault_alloydb import ( AlloyDBClusterBackupPlanAssociationProperties, @@ -146,6 +176,12 @@ ServiceAccount, Tags, ) +from .bindingmatchingresource import ( + AutoProtectionDetails, + BindingMatchingResource, + ListBindingMatchingResourcesRequest, + ListBindingMatchingResourcesResponse, +) from .datasourcereference import ( DataSourceBackupConfigInfo, DataSourceGcpResourceInfo, @@ -167,8 +203,83 @@ PitrSettings, ResourceBackupConfig, ) +from .restore_template import ( + CreateRestoreTemplateRequest, + DeleteRestoreTemplateRequest, + ExecutionSummary, + GetRestoreTemplateRequest, + ListRestoreTemplatesRequest, + ListRestoreTemplatesResponse, + RestoreTemplate, + RunRestoreTemplateRequest, + RunRestoreTemplateResponse, + UpdateRestoreTemplateRequest, +) +from .restore_template_common import ( + BackupSelectionConfig, + PostRestoreConfig, + PreRestoreConfig, + VerificationConfig, +) +from .restore_template_execution import ( + CleanupPhaseInfo, + GetRestoreTemplateExecutionRequest, + ListRestoreTemplateExecutionsRequest, + ListRestoreTemplateExecutionsResponse, + PhaseState, + PostRestorePhaseInfo, + PreparePhaseInfo, + PreRestorePhaseInfo, + RestorePhaseInfo, + RestoreTemplateExecution, + TriggerRestoreCleanupRequest, + VerificationPhaseInfo, +) +from .restore_verification_plan import ( + CreateRestoreVerificationPlanRequest, + DeleteRestoreVerificationPlanRequest, + GetRestoreVerificationPlanRequest, + ListRestoreVerificationPlansRequest, + ListRestoreVerificationPlansResponse, + RestoreVerificationCleanupRule, + RestoreVerificationPlan, +) +from .restore_verification_plan_association import ( + CreateRestoreVerificationPlanAssociationRequest, + DeleteRestoreVerificationPlanAssociationRequest, + GetRestoreVerificationPlanAssociationRequest, + ListRestoreVerificationPlanAssociationsRequest, + ListRestoreVerificationPlanAssociationsResponse, + RestoreVerificationPlanAssociation, + TriggerRestoreVerificationRequest, + TriggerRestoreVerificationResponse, + TriggerSummary, +) __all__ = ( + "AppliedAutoProtectionPolicy", + "ListAppliedAutoProtectionPoliciesRequest", + "ListAppliedAutoProtectionPoliciesResponse", + "AutoProtectionPolicy", + "BackupPlanDetail", + "BindingSummary", + "CreateAutoProtectionPolicyRequest", + "Criteria", + "DeleteAutoProtectionPolicyRequest", + "GetAutoProtectionPolicyRequest", + "KeyValuePair", + "ListAutoProtectionPoliciesRequest", + "ListAutoProtectionPoliciesResponse", + "MatchingCondition", + "PolicyEvaluationSummary", + "UpdateAutoProtectionPolicyRequest", + "AutoProtectionPolicyBinding", + "BindingEvaluationSummary", + "CreateAutoProtectionPolicyBindingRequest", + "GetAutoProtectionPolicyBindingRequest", + "InitiateDeleteAutoProtectionPolicyBindingRequest", + "ListAutoProtectionPolicyBindingsRequest", + "ListAutoProtectionPolicyBindingsResponse", "CreateManagementServerRequest", "DeleteManagementServerRequest", "GetManagementServerRequest", @@ -243,6 +354,7 @@ "UpdateBackupRequest", "UpdateBackupVaultRequest", "UpdateDataSourceRequest", + "VerificationSummary", "BackupConfigState", "BackupVaultView", "BackupView", @@ -284,6 +396,10 @@ "ServiceAccount", "Tags", "KeyRevocationActionType", + "AutoProtectionDetails", + "BindingMatchingResource", + "ListBindingMatchingResourcesRequest", + "ListBindingMatchingResourcesResponse", "DataSourceBackupConfigInfo", "DataSourceGcpResourceInfo", "DataSourceReference", @@ -301,4 +417,46 @@ "ListResourceBackupConfigsResponse", "PitrSettings", "ResourceBackupConfig", + "CreateRestoreTemplateRequest", + "DeleteRestoreTemplateRequest", + "ExecutionSummary", + "GetRestoreTemplateRequest", + "ListRestoreTemplatesRequest", + "ListRestoreTemplatesResponse", + "RestoreTemplate", + "RunRestoreTemplateRequest", + "RunRestoreTemplateResponse", + "UpdateRestoreTemplateRequest", + "BackupSelectionConfig", + "PostRestoreConfig", + "PreRestoreConfig", + "VerificationConfig", + "CleanupPhaseInfo", + "GetRestoreTemplateExecutionRequest", + "ListRestoreTemplateExecutionsRequest", + "ListRestoreTemplateExecutionsResponse", + "PostRestorePhaseInfo", + "PreparePhaseInfo", + "PreRestorePhaseInfo", + "RestorePhaseInfo", + "RestoreTemplateExecution", + "TriggerRestoreCleanupRequest", + "VerificationPhaseInfo", + "PhaseState", + "CreateRestoreVerificationPlanRequest", + "DeleteRestoreVerificationPlanRequest", + "GetRestoreVerificationPlanRequest", + "ListRestoreVerificationPlansRequest", + "ListRestoreVerificationPlansResponse", + "RestoreVerificationCleanupRule", + "RestoreVerificationPlan", + "CreateRestoreVerificationPlanAssociationRequest", + "DeleteRestoreVerificationPlanAssociationRequest", + "GetRestoreVerificationPlanAssociationRequest", + "ListRestoreVerificationPlanAssociationsRequest", + "ListRestoreVerificationPlanAssociationsResponse", + "RestoreVerificationPlanAssociation", + "TriggerRestoreVerificationRequest", + "TriggerRestoreVerificationResponse", + "TriggerSummary", ) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/appliedautoprotectionpolicy.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/appliedautoprotectionpolicy.py new file mode 100644 index 000000000000..ca63d0573bb3 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/appliedautoprotectionpolicy.py @@ -0,0 +1,227 @@ +# -*- 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 google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.backupdr_v1.types import ( + autoprotectionpolicy, + autoprotectionpolicybinding, +) + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1", + manifest={ + "AppliedAutoProtectionPolicy", + "ListAppliedAutoProtectionPoliciesRequest", + "ListAppliedAutoProtectionPoliciesResponse", + }, +) + + +class AppliedAutoProtectionPolicy(proto.Message): + r"""AppliedAutoProtectionPolicy is a read-only view of + AutoProtectionPolicy and AutoProtectionPolicyBinding resources + that apply to a given workload project. + + Attributes: + name (str): + Identifier. Canonical resource name. + Format: + + projects/{workload-project-number}/locations/{location}/appliedAutoProtectionPolicies/{id}. + source_binding (str): + Output only. The full resource name of the + AutoProtectionPolicyBinding that applies the source policy + to a scope including this workload project. e.g., + projects/{admin-project}/locations/{location}/autoProtectionPolicies/{policy_id}/autoProtectionPolicyBindings/{binding_id}. + criteria (google.cloud.backupdr_v1.types.Criteria): + Output only. The criteria resources must meet + for this rule to apply. From + AutoProtectionPolicy.criteria. + backup_plan_details (MutableSequence[google.cloud.backupdr_v1.types.BackupPlanDetail]): + Output only. The set of backup plan configurations, + mirroring the backup_plan_details from the source + AutoProtectionPolicy. Each element specifies a backup plan + for a given resource type. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp indicating when the + binding was last modified. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Timestamp indicating when the + binding was last created. + binding_evaluation_summary (google.cloud.backupdr_v1.types.BindingEvaluationSummary): + Output only. The summary of the last policy + application when the job has run. + status (google.cloud.backupdr_v1.types.AppliedAutoProtectionPolicy.State): + Output only. The status of the applied auto + protection policy. + """ + + class State(proto.Enum): + r"""Represents the various states an applied auto protection + policy can be in. + + Values: + STATE_UNSPECIFIED (0): + State is not specified. + CREATING (1): + The policy is in the process of being + applied. + ACTIVE (2): + The policy has been applied and is active. + DELETION_INITIATED (3): + The policy is in the process of being + removed. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETION_INITIATED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + source_binding: str = proto.Field( + proto.STRING, + number=2, + ) + criteria: autoprotectionpolicy.Criteria = proto.Field( + proto.MESSAGE, + number=3, + message=autoprotectionpolicy.Criteria, + ) + backup_plan_details: MutableSequence[autoprotectionpolicy.BackupPlanDetail] = ( + proto.RepeatedField( + proto.MESSAGE, + number=4, + message=autoprotectionpolicy.BackupPlanDetail, + ) + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + binding_evaluation_summary: autoprotectionpolicybinding.BindingEvaluationSummary = ( + proto.Field( + proto.MESSAGE, + number=7, + message=autoprotectionpolicybinding.BindingEvaluationSummary, + ) + ) + status: State = proto.Field( + proto.ENUM, + number=8, + enum=State, + ) + + +class ListAppliedAutoProtectionPoliciesRequest(proto.Message): + r"""Request message for listing AppliedAutoProtectionPolicies. + + Attributes: + parent (str): + Required. The project and location for which + to retrieve the list of applied policies. + Format: projects/{project}/locations/{location} + page_size (int): + Optional. The maximum number of applied + policies to return in a single page. The maximum + value is 1000; values above 1000 will be coerced + to + 1000. If unspecified or set to 0, a default page + size of 500 will be used. + page_token (str): + Optional. A page token, received from a previous + ``ListAppliedAutoProtectionPolicies`` call. + filter (str): + Optional. A filter expression that filters + resources listed in the response. + order_by (str): + Optional. An expression that sorts the + results in the response. + """ + + 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 ListAppliedAutoProtectionPoliciesResponse(proto.Message): + r"""Response message for ListAppliedAutoProtectionPolicies. + + Attributes: + applied_auto_protection_policies (MutableSequence[google.cloud.backupdr_v1.types.AppliedAutoProtectionPolicy]): + A list of the AppliedAutoProtectionPolicy + resources found. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. + unreachable (MutableSequence[str]): + Unordered list. Locations that could not be reached. For + example, "projects/my-project/locations/us-east1"]. + """ + + @property + def raw_page(self): + return self + + applied_auto_protection_policies: MutableSequence["AppliedAutoProtectionPolicy"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AppliedAutoProtectionPolicy", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/autoprotectionpolicy.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/autoprotectionpolicy.py new file mode 100644 index 000000000000..a470818f7ddf --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/autoprotectionpolicy.py @@ -0,0 +1,532 @@ +# -*- 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 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 + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1", + manifest={ + "AutoProtectionPolicy", + "BackupPlanDetail", + "Criteria", + "MatchingCondition", + "PolicyEvaluationSummary", + "BindingSummary", + "KeyValuePair", + "CreateAutoProtectionPolicyRequest", + "GetAutoProtectionPolicyRequest", + "UpdateAutoProtectionPolicyRequest", + "DeleteAutoProtectionPolicyRequest", + "ListAutoProtectionPoliciesRequest", + "ListAutoProtectionPoliciesResponse", + }, +) + + +class AutoProtectionPolicy(proto.Message): + r"""An AutoprotectionPolicy is a policy resource designed to + automate backup management, moving from manual per-resource + protection to a bulk approach. The policy dynamically discovers + and applies a specified backup plan to all eligible resources + that match its defined scope and criteria. + + Attributes: + name (str): + Output only. Identifier. The resource name of the + AutoProtectionPolicy. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}`` + description (str): + Optional. A description of the policy. The + description must be at most 2048 characters. + backup_plan_details (MutableSequence[google.cloud.backupdr_v1.types.BackupPlanDetail]): + Required. The backup plan details for + matching resources. + criteria (google.cloud.backupdr_v1.types.Criteria): + Required. The criteria for matching + resources. + state (google.cloud.backupdr_v1.types.AutoProtectionPolicy.State): + Output only. The current state of the + AutoProtectionPolicy. + etag (str): + Output only. The etag for the policy. + If this is provided on update, it must match the + server's etag. + binding_summary (google.cloud.backupdr_v1.types.BindingSummary): + Output only. Summary of total count of + different containers covered through this + policy. + policy_evaluation_summary (google.cloud.backupdr_v1.types.PolicyEvaluationSummary): + Output only. Summary of last policy + evaluation when job was run per workload type. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the policy + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the policy + was last updated. + """ + + class State(proto.Enum): + r"""The state of an AutoProtectionPolicy. + + Values: + STATE_UNSPECIFIED (0): + The state of the policy is unspecified. + CREATING (1): + The policy is being created. + ACTIVE (2): + The policy is active and protecting matching + resources. + UPDATING (3): + The policy is being updated. + DELETING (4): + The policy is being deleted. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + UPDATING = 3 + DELETING = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + backup_plan_details: MutableSequence["BackupPlanDetail"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="BackupPlanDetail", + ) + criteria: "Criteria" = proto.Field( + proto.MESSAGE, + number=4, + message="Criteria", + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + etag: str = proto.Field( + proto.STRING, + number=6, + ) + binding_summary: "BindingSummary" = proto.Field( + proto.MESSAGE, + number=7, + message="BindingSummary", + ) + policy_evaluation_summary: "PolicyEvaluationSummary" = proto.Field( + proto.MESSAGE, + number=8, + message="PolicyEvaluationSummary", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + + +class BackupPlanDetail(proto.Message): + r"""BackupPlanDetail defines configuration of protection. + + Attributes: + resource_type (str): + Required. The type of resource that this policy will + automatically protect. Allowed values are, + ``compute.googleapis.com/Instance`` and + ``compute.googleapis.com/Disk`` are supported. + backup_plan (str): + Required. The resource name of the BackupPlan + to apply to resources that match the policy's + criteria. This backup plan must be in the same + location as AutoProtectionPolicy. Format: + + projects/{project}/locations/{location}/backupPlans/{backupPlanId} + """ + + resource_type: str = proto.Field( + proto.STRING, + number=1, + ) + backup_plan: str = proto.Field( + proto.STRING, + number=2, + ) + + +class Criteria(proto.Message): + r"""Criteria specifies a set of criteria for matching resources. + + Attributes: + matching_conditions (MutableSequence[google.cloud.backupdr_v1.types.MatchingCondition]): + Required. A list of matching conditions that + a resource must meet to be protected by the + policy. + """ + + matching_conditions: MutableSequence["MatchingCondition"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="MatchingCondition", + ) + + +class MatchingCondition(proto.Message): + r"""MatchingCondition specifies a set of conditions for matching + resources. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + label_condition (google.cloud.backupdr_v1.types.KeyValuePair): + Optional. A condition that matches resources + based on their labels. For MVP, this is limited + to a single label match. + + This field is a member of `oneof`_ ``condition``. + """ + + label_condition: "KeyValuePair" = proto.Field( + proto.MESSAGE, + number=1, + oneof="condition", + message="KeyValuePair", + ) + + +class PolicyEvaluationSummary(proto.Message): + r"""PolicyEvaluationSummary contains the summary of the last run + of job that applies policy to matching resources. + + Attributes: + matching_resource_count (int): + Output only. The number of resources that + currently match the policy's criteria. + protected_resource_count (int): + Output only. The number of matching resources + that are successfully protected. + failed_resource_count (int): + Output only. The number of matching resources + whose protection failed during job run. + """ + + matching_resource_count: int = proto.Field( + proto.INT64, + number=1, + ) + protected_resource_count: int = proto.Field( + proto.INT64, + number=2, + ) + failed_resource_count: int = proto.Field( + proto.INT64, + number=3, + ) + + +class BindingSummary(proto.Message): + r"""BindingSummary contains count of different containers covered + through this policy. + + Attributes: + project_count (int): + Output only. Total count of Projects + protected with this policy. + """ + + project_count: int = proto.Field( + proto.INT64, + number=1, + ) + + +class KeyValuePair(proto.Message): + r"""KeyValuePair defines a key-value pair for matching resource + labels. + + Attributes: + key (str): + Required. The key of the label to match. This must be in the + format ``{label_key}``. The key must match the regex + Format:``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}``. + values (MutableSequence[str]): + Required. The values of the label to match. There will be + explicit "OR" between values of array. Each value must be in + the format ``{label_value}``. The value must match the regex + Format: ``[\\p{Ll}\\p{Lo}\\p{N}_-]{1,63}``. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + values: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + +class CreateAutoProtectionPolicyRequest(proto.Message): + r"""Request message for creating an AutoProtectionPolicy. + + Attributes: + parent (str): + Required. The parent resource where this + policy will be created. Format: + projects/{project}/locations/{location} + auto_protection_policy_id (str): + Required. The ID to use for the policy. + This will become the final component of the + policy's resource name. + + This value must start with a lowercase letter + followed by up to 62 lowercase letters, numbers, + or hyphens, and cannot end with a hyphen. + auto_protection_policy (google.cloud.backupdr_v1.types.AutoProtectionPolicy): + Required. The AutoProtectionPolicy resource + 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. + + 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, + ) + auto_protection_policy_id: str = proto.Field( + proto.STRING, + number=2, + ) + auto_protection_policy: "AutoProtectionPolicy" = proto.Field( + proto.MESSAGE, + number=3, + message="AutoProtectionPolicy", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetAutoProtectionPolicyRequest(proto.Message): + r"""Request message for getting an AutoProtectionPolicy. + + Attributes: + name (str): + Required. The name of the policy to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateAutoProtectionPolicyRequest(proto.Message): + r"""Request message for updating an AutoProtectionPolicy. + + Attributes: + auto_protection_policy (google.cloud.backupdr_v1.types.AutoProtectionPolicy): + Required. The policy to update. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. Field mask is used to specify the fields to be + overwritten in the AutoProtectionPolicy resource by the + update. The fields specified in the update_mask are relative + to the resource, not the full request. A field will be + overwritten if it is in the mask. If the user does not + provide a mask then all fields will be overwritten. + 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. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + auto_protection_policy: "AutoProtectionPolicy" = proto.Field( + proto.MESSAGE, + number=1, + message="AutoProtectionPolicy", + ) + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=2, + message=field_mask_pb2.FieldMask, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteAutoProtectionPolicyRequest(proto.Message): + r"""Request message for deleting an AutoProtectionPolicy. + + Attributes: + name (str): + Required. The name of the policy to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + etag (str): + Optional. The current etag of the + autoprotectionpolicy. If an etag is provided and + does not match the current etag of the + connection, deletion will be blocked. + 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. + + 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, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListAutoProtectionPoliciesRequest(proto.Message): + r"""Request message for ListAutoProtectionPolicies. + + Attributes: + parent (str): + Required. The project and location for which + to retrieve the list of policies. Format: + projects/{project}/locations/{location} + page_size (int): + Optional. The maximum number of policies to + return in a single page. If unspecified, a + server-default value will be used. + page_token (str): + Optional. A page token, received from a previous + ``ListAutoProtectionPolicies`` call. Provide this to + retrieve the subsequent page. + filter (str): + Optional. A filter expression that filters + resources listed in the response. The following + fields are filterable: + order_by (str): + Optional. An expression that sorts the + results in the response. The following fields + are sortable: + """ + + 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 ListAutoProtectionPoliciesResponse(proto.Message): + r"""Response message for ListAutoProtectionPolicies. + + Attributes: + auto_protection_policies (MutableSequence[google.cloud.backupdr_v1.types.AutoProtectionPolicy]): + A list of the AutoProtectionPolicy resources + found. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Unordered list. Locations that could not be + reached. + """ + + @property + def raw_page(self): + return self + + auto_protection_policies: MutableSequence["AutoProtectionPolicy"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AutoProtectionPolicy", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/autoprotectionpolicybinding.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/autoprotectionpolicybinding.py new file mode 100644 index 000000000000..f1cf2f4d52a0 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/autoprotectionpolicybinding.py @@ -0,0 +1,353 @@ +# -*- 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 google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1", + manifest={ + "AutoProtectionPolicyBinding", + "BindingEvaluationSummary", + "CreateAutoProtectionPolicyBindingRequest", + "GetAutoProtectionPolicyBindingRequest", + "ListAutoProtectionPolicyBindingsRequest", + "ListAutoProtectionPolicyBindingsResponse", + "InitiateDeleteAutoProtectionPolicyBindingRequest", + }, +) + + +class AutoProtectionPolicyBinding(proto.Message): + r"""An AutoProtectionPolicyBinding (APPA) acts as the bridge + between an AutoProtectionPolicy and the scope (Project) where + the policy should be applied. + + Attributes: + name (str): + Output only. Identifier. The resource name of the + AutoProtectionPolicyBinding. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}`` + description (str): + Optional. A description of the binding. The + description must be at most 2048 characters. + state (google.cloud.backupdr_v1.types.AutoProtectionPolicyBinding.State): + Output only. The current state of the + AutoProtectionPolicyBinding. + scope (str): + Required. Immutable. Resource Id of target container on + which policy will be applied. Format: projects/{project_id} + binding_evaluation_summary (google.cloud.backupdr_v1.types.BindingEvaluationSummary): + Output only. Summaries of the last policy + application when the job has run, with one entry + per resource type specified in the + AutoProtectionPolicy. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the binding + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the binding + was last updated. + etag (str): + Output only. The etag for the binding. + If this is provided on update, it must match the + server's etag. + """ + + class State(proto.Enum): + r"""The state of an AutoProtectionPolicyBinding. + + Values: + STATE_UNSPECIFIED (0): + The state of the binding is unspecified. + CREATING (1): + The binding is being created. + ACTIVE (2): + The binding is active. + DELETION_INITIATED (3): + The binding deletion is initiated. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETION_INITIATED = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + scope: str = proto.Field( + proto.STRING, + number=4, + ) + binding_evaluation_summary: "BindingEvaluationSummary" = proto.Field( + proto.MESSAGE, + number=5, + message="BindingEvaluationSummary", + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + etag: str = proto.Field( + proto.STRING, + number=8, + ) + + +class BindingEvaluationSummary(proto.Message): + r"""BindingEvaluationSummary contains the summary of the last run + of job that applies policy to matching resources for a given + binding. + + Attributes: + matching_resource_count (int): + Output only. The number of resources that + currently match the policy's criteria. + protected_resource_count (int): + Output only. The number of matching resources + that are successfully protected. + failed_resource_count (int): + Output only. The number of matching resources + whose protection failed during job run. + """ + + matching_resource_count: int = proto.Field( + proto.INT64, + number=1, + ) + protected_resource_count: int = proto.Field( + proto.INT64, + number=2, + ) + failed_resource_count: int = proto.Field( + proto.INT64, + number=3, + ) + + +class CreateAutoProtectionPolicyBindingRequest(proto.Message): + r"""Request message for creating an AutoProtectionPolicyBinding. + + Attributes: + parent (str): + Required. The parent resource where this binding will be + created. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} + auto_protection_policy_binding_id (str): + Required. The ID to use for the binding. + This will become the final component of the + binding's resource name. + + This value must start with a lowercase letter + followed by up to 62 lowercase letters, numbers, + or hyphens, and cannot end with a hyphen. + auto_protection_policy_binding (google.cloud.backupdr_v1.types.AutoProtectionPolicyBinding): + Required. The AutoProtectionPolicyBinding + resource 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. + + 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, + ) + auto_protection_policy_binding_id: str = proto.Field( + proto.STRING, + number=2, + ) + auto_protection_policy_binding: "AutoProtectionPolicyBinding" = proto.Field( + proto.MESSAGE, + number=3, + message="AutoProtectionPolicyBinding", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetAutoProtectionPolicyBindingRequest(proto.Message): + r"""Request message for getting an AutoProtectionPolicyBinding. + + Attributes: + name (str): + Required. The name of the binding to retrieve. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListAutoProtectionPolicyBindingsRequest(proto.Message): + r"""Request message for ListAutoProtectionPolicyBindings. + + Attributes: + parent (str): + Required. The project and location for which + to retrieve the list of policies. Format: + projects/{project}/locations/{location} + page_size (int): + Optional. The maximum number of policies to + return in a single page is 500. If unspecified, + a server-default value will be used. + page_token (str): + Optional. A page token, received from a previous + ``ListAutoProtectionPolicies`` call. Provide this to + retrieve the subsequent page. + filter (str): + Optional. A filter expression that filters + resources listed in the response. The following + fields are filterable: + order_by (str): + Optional. An expression that sorts the + results in the response. The following fields + are sortable: + """ + + 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 ListAutoProtectionPolicyBindingsResponse(proto.Message): + r"""Response message for ListAutoProtectionPolicyBindings. + + Attributes: + auto_protection_policy_bindings (MutableSequence[google.cloud.backupdr_v1.types.AutoProtectionPolicyBinding]): + A list of the AutoProtectionPolicyBindings + resources found. + next_page_token (str): + A token that can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Unordered list. Locations that could not be + reached. + """ + + @property + def raw_page(self): + return self + + auto_protection_policy_bindings: MutableSequence["AutoProtectionPolicyBinding"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AutoProtectionPolicyBinding", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class InitiateDeleteAutoProtectionPolicyBindingRequest(proto.Message): + r"""Request message for initiating delete of an + AutoProtectionPolicyBinding. + + Attributes: + name (str): + Required. The name of the binding to delete. Format: + projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + etag (str): + Optional. The current etag of the + AutoProtectionPolicyBinding. If an etag is + provided and does not match the current etag of + the binding, deletion will be blocked and an + ABORTED error will be returned. + 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. + + 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, + ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplanassociation.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplanassociation.py index b3337c7ba6fb..d5c24db63c81 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplanassociation.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupplanassociation.py @@ -57,7 +57,7 @@ class BackupPlanAssociation(proto.Message): Attributes: name (str): Output only. Identifier. The resource name of - BackupPlanAssociation in below format Format : + BackupPlanAssociation in below format Format: projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId} resource_type (str): @@ -115,6 +115,11 @@ class BackupPlanAssociation(proto.Message): Format: ``projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision_id}`` + auto_protection_policy_binding (str): + Output only. The resource name of the + ``AutoProtectionPolicyBinding`` that manages this + association, if any. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{policy}/bindings/{binding}``. """ class State(proto.Enum): @@ -204,6 +209,10 @@ class State(proto.Enum): proto.STRING, number=12, ) + auto_protection_policy_binding: str = proto.Field( + proto.STRING, + number=16, + ) class RuleConfigInfo(proto.Message): @@ -555,6 +564,12 @@ class DeleteBackupPlanAssociationRequest(proto.Message): The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). + auto_protection_policy_binding (str): + Optional. This field is exclusively used by Backup and DR's + auto-protection feature. The resource name of the + ``AutoProtectionPolicyBinding`` that triggered the deletion + of this association. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{policy}/bindings/{binding}``. """ name: str = proto.Field( @@ -565,6 +580,10 @@ class DeleteBackupPlanAssociationRequest(proto.Message): proto.STRING, number=2, ) + auto_protection_policy_binding: str = proto.Field( + proto.STRING, + number=3, + ) class UpdateBackupPlanAssociationRequest(proto.Message): diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupvault.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupvault.py index 55f0729083dc..e468c4595387 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupvault.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/backupvault.py @@ -48,6 +48,7 @@ "BackupApplianceLockInfo", "BackupLock", "Backup", + "VerificationSummary", "CreateBackupVaultRequest", "ListBackupVaultsRequest", "ListBackupVaultsResponse", @@ -713,6 +714,11 @@ class GcpBackupConfig(proto.Message): backup_plan_revision_id (str): The user friendly id of the backup plan revision. E.g. v0, v1 etc. + auto_protection_policy_binding (str): + Output only. The resource name of the + ``AutoProtectionPolicyBinding`` that manages this + datasource, if any. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{policy}/bindings/{binding}``. """ backup_plan: str = proto.Field( @@ -739,6 +745,10 @@ class GcpBackupConfig(proto.Message): proto.STRING, number=6, ) + auto_protection_policy_binding: str = proto.Field( + proto.STRING, + number=7, + ) class BackupApplianceBackupConfig(proto.Message): @@ -1197,6 +1207,9 @@ class Backup(proto.Message): kms_key_versions (MutableSequence[str]): Optional. Output only. The list of KMS key versions used to encrypt the backup. + verification_summary (google.cloud.backupdr_v1.types.VerificationSummary): + Output only. The restore verification status + of the backup. """ class State(proto.Enum): @@ -1428,6 +1441,59 @@ class GCPBackupPlanInfo(proto.Message): proto.STRING, number=33, ) + verification_summary: "VerificationSummary" = proto.Field( + proto.MESSAGE, + number=37, + message="VerificationSummary", + ) + + +class VerificationSummary(proto.Message): + r"""VerificationSummary contains the status and timestamp of the + latest Automated Verification test. + + Attributes: + last_verification_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup was + last verified. + last_verification_state (google.cloud.backupdr_v1.types.VerificationSummary.LastVerificationState): + Output only. The state of the last + verification. + last_verification_execution (str): + Output only. The last verification execution. + """ + + class LastVerificationState(proto.Enum): + r"""LastVerificationState represents the state of the + verification. + + Values: + STATE_UNSPECIFIED (0): + Verification state is unspecified. + SUCCEEDED (1): + Verification succeeded. + FAILED (2): + Verification failed. + """ + + STATE_UNSPECIFIED = 0 + SUCCEEDED = 1 + FAILED = 2 + + last_verification_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + last_verification_state: LastVerificationState = proto.Field( + proto.ENUM, + number=2, + enum=LastVerificationState, + ) + last_verification_execution: str = proto.Field( + proto.STRING, + number=3, + ) class CreateBackupVaultRequest(proto.Message): diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/bindingmatchingresource.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/bindingmatchingresource.py new file mode 100644 index 000000000000..a5f5b3640be3 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/bindingmatchingresource.py @@ -0,0 +1,237 @@ +# -*- 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 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( + package="google.cloud.backupdr.v1", + manifest={ + "ListBindingMatchingResourcesRequest", + "ListBindingMatchingResourcesResponse", + "BindingMatchingResource", + "AutoProtectionDetails", + }, +) + + +class ListBindingMatchingResourcesRequest(proto.Message): + r"""Request message for List BindingMatchingResources. + + Attributes: + parent (str): + Required. The project, location, auto protection policy and + binding for which to retrieve ``BindingMatchingResources`` + information. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}``. + In Google Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. + page_size (int): + Optional. The maximum number of ``BindingMatchingResources`` + to return in a single response. The default page size is 100 + and maximum page size is 200. Note that the response may + include a partial list and a caller should only rely on the + response's + [next_page_token][google.cloud.backupdr.v1.ListBindingMatchingResourcesResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + Optional. The value of + [next_page_token][google.cloud.backupdr.v1.ListBindingMatchingResourcesResponse.next_page_token] + received from a previous ``ListBindingMatchingResources`` + call. Provide this to retrieve the subsequent page in a + multi-page list of results. When paginating, all other + parameters provided to ``ListBindingMatchingResources`` must + match the call that provided the page token. + filter (str): + Optional. Field match expression used to + filter the results. + order_by (str): + Optional. Field by which to sort the results. + """ + + 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 ListBindingMatchingResourcesResponse(proto.Message): + r"""The response message for getting a list of + ``BindingMatchingResources``. + + Attributes: + matching_resources (MutableSequence[google.cloud.backupdr_v1.types.BindingMatchingResource]): + The list of ``BindingMatchingResources`` in the + project,location for the specified binding. + next_page_token (str): + A token which may be sent as + [page_token][google.cloud.backupdr.v1.ListBindingMatchingResourcesRequest.page_token] + in a subsequent ``ListBindingMatchingResources`` call to + retrieve the next page of results. If this field is omitted + or empty, then there are no more results to return. + """ + + @property + def raw_page(self): + return self + + matching_resources: MutableSequence["BindingMatchingResource"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BindingMatchingResource", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class BindingMatchingResource(proto.Message): + r"""BindingMatchingResource contains the details of a resource + that matches the criteria of a binding. + + Attributes: + name (str): + Output only. Identifier. The resource name of the + ``BindingMatchingResource``. Format: + ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource}`` + resource (str): + Output only. Resource name of the workload that matches the + criteria of the binding. + + The format can be either a relative resource name (e.g., + ``projects/my-project/zones/us-central1-a/instances/my-instance``) + or a schemeless full resource name (e.g., + ``//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance``). + last_evaluation_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The timestamp when the resource + was last evaluated for protection. + auto_protection_details (google.cloud.backupdr_v1.types.AutoProtectionDetails): + Output only. The auto protection details of + the resource from the current binding's + perspective. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource: str = proto.Field( + proto.STRING, + number=2, + ) + last_evaluation_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + auto_protection_details: "AutoProtectionDetails" = proto.Field( + proto.MESSAGE, + number=4, + message="AutoProtectionDetails", + ) + + +class AutoProtectionDetails(proto.Message): + r"""AutoProtectionDetails contains the protection details of a + resource from the current binding's perspective. + + Attributes: + state (google.cloud.backupdr_v1.types.AutoProtectionDetails.State): + Output only. Protection state of the resource + from the current binding's perspective. Output + only. + backup_plan_association (str): + Output only. Resource name of backup plan + association linked to the resource, if any. + Format: + + projects/{project}/locations/{location}/backupPlanAssociations/{backupPlanAssociationId} + data_source (str): + Output only. Resource name of the datasource + linked to the resource, if any. Format: + + projects/{project}/locations/{location}/backupVaults/{backupVaultId}/dataSources/{dataSourceId} + error (google.rpc.status_pb2.Status): + Output only. Error during last sync for + protection/unprotection, if any. + """ + + class State(proto.Enum): + r"""Enum for protection state of the resource. + + Values: + STATE_UNSPECIFIED (0): + State unspecified. + PROTECTED (1): + Resource is protected. + PROTECTION_FAILED (2): + Resource protection failed. + UNPROTECTING (3): + Resource is being unprotected. + UNPROTECTION_FAILED (4): + Resource unprotection failed. + """ + + STATE_UNSPECIFIED = 0 + PROTECTED = 1 + PROTECTION_FAILED = 2 + UNPROTECTING = 3 + UNPROTECTION_FAILED = 4 + + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + backup_plan_association: str = proto.Field( + proto.STRING, + number=2, + ) + data_source: str = proto.Field( + proto.STRING, + number=3, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=4, + message=status_pb2.Status, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_template.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_template.py new file mode 100644 index 000000000000..4e8a88c6ce57 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_template.py @@ -0,0 +1,493 @@ +# -*- 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 google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.backupdr_v1.types import restore_template_common +from google.cloud.backupdr_v1.types import ( + restore_template_execution as gcb_restore_template_execution, +) + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1", + manifest={ + "RestoreTemplate", + "ExecutionSummary", + "CreateRestoreTemplateRequest", + "GetRestoreTemplateRequest", + "UpdateRestoreTemplateRequest", + "DeleteRestoreTemplateRequest", + "RunRestoreTemplateRequest", + "RunRestoreTemplateResponse", + "ListRestoreTemplatesRequest", + "ListRestoreTemplatesResponse", + }, +) + + +class RestoreTemplate(proto.Message): + r"""A ``RestoreTemplate`` encapsulates DR readiness configurations for + validating backups. + + Attributes: + name (str): + Identifier. The resource name of the + RestoreTemplate. + description (str): + Optional. User-provided description of the + restore template. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore + template was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore + template was last updated. + resource_type (str): + Required. Immutable. The specific type of the workload being + restored. The format is "{service_name}/{resource_kind}", + for example, "compute.googleapis.com/Instance". + labels (MutableMapping[str, str]): + Optional. User-defined labels. + backup_selection_config (google.cloud.backupdr_v1.types.BackupSelectionConfig): + Required. Backup selection configuration. + pre_restore_config (google.cloud.backupdr_v1.types.PreRestoreConfig): + Optional. Pre-restore configuration. + post_restore_config (google.cloud.backupdr_v1.types.PostRestoreConfig): + Optional. Post-restore configuration. + verification_config (google.cloud.backupdr_v1.types.VerificationConfig): + Optional. Verification configuration. + restore_properties (google.protobuf.struct_pb2.Struct): + Required. Defines target environments where the resource + will be restored. + + The target resource name in ``restore_properties`` supports + the ``{EXECUTION_ID}`` token to dynamically generate unique + resource names for each execution. During restore execution, + every occurrence of ``{EXECUTION_ID}`` in the target + resource name is replaced with the 8-character + ``RestoreTemplateExecution`` ID (for example, + ``"restored-resource-{EXECUTION_ID}"`` or + ``"restored-{EXECUTION_ID}-resource"`` resolves to + ``"restored-resource-5d437b06"`` or + ``"restored-5d437b06-resource"``). + state (google.cloud.backupdr_v1.types.RestoreTemplate.State): + Output only. The state of the restore + template. + execution_summary (google.cloud.backupdr_v1.types.ExecutionSummary): + Output only. Summary of the last execution. + etag (str): + Optional. Etag for concurrency control. + """ + + class State(proto.Enum): + r"""The state of the RestoreTemplate. + + Values: + STATE_UNSPECIFIED (0): + State not specified. + CREATING (1): + The template is being created. + ACTIVE (2): + The template is active and ready to use. + UPDATING (3): + The template is being updated. + DELETING (4): + The template is being deleted. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + UPDATING = 3 + DELETING = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + resource_type: str = proto.Field( + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + backup_selection_config: restore_template_common.BackupSelectionConfig = ( + proto.Field( + proto.MESSAGE, + number=7, + message=restore_template_common.BackupSelectionConfig, + ) + ) + pre_restore_config: restore_template_common.PreRestoreConfig = proto.Field( + proto.MESSAGE, + number=8, + message=restore_template_common.PreRestoreConfig, + ) + post_restore_config: restore_template_common.PostRestoreConfig = proto.Field( + proto.MESSAGE, + number=9, + message=restore_template_common.PostRestoreConfig, + ) + verification_config: restore_template_common.VerificationConfig = proto.Field( + proto.MESSAGE, + number=10, + message=restore_template_common.VerificationConfig, + ) + restore_properties: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=11, + message=struct_pb2.Struct, + ) + state: State = proto.Field( + proto.ENUM, + number=12, + enum=State, + ) + execution_summary: "ExecutionSummary" = proto.Field( + proto.MESSAGE, + number=13, + message="ExecutionSummary", + ) + etag: str = proto.Field( + proto.STRING, + number=14, + ) + + +class ExecutionSummary(proto.Message): + r"""Summary of the last execution. + + Attributes: + last_execution (str): + Output only. The resource name of the last execution. + Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}`` + last_execution_state (google.cloud.backupdr_v1.types.RestoreTemplateExecution.ExecutionState): + Output only. The state of the last execution. + """ + + last_execution: str = proto.Field( + proto.STRING, + number=1, + ) + last_execution_state: gcb_restore_template_execution.RestoreTemplateExecution.ExecutionState = proto.Field( + proto.ENUM, + number=2, + enum=gcb_restore_template_execution.RestoreTemplateExecution.ExecutionState, + ) + + +class CreateRestoreTemplateRequest(proto.Message): + r"""Request message for creating a RestoreTemplate instance. + + Attributes: + parent (str): + Required. The restore template project and location in the + format 'projects/{project_id}/locations/{location}'. + restore_template_id (str): + Required. The ID of the restore template to + create. The ID must be unique for the specified + project and location. + restore_template (google.cloud.backupdr_v1.types.RestoreTemplate): + Required. A RestoreTemplate resource. + 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 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, + ) + restore_template_id: str = proto.Field( + proto.STRING, + number=2, + ) + restore_template: "RestoreTemplate" = proto.Field( + proto.MESSAGE, + number=3, + message="RestoreTemplate", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetRestoreTemplateRequest(proto.Message): + r"""Request message for getting a RestoreTemplate instance. + + Attributes: + name (str): + Required. The name of the restore template to retrieve. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}' + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateRestoreTemplateRequest(proto.Message): + r"""Request message for updating a RestoreTemplate instance. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. Field mask is used + to specify the fields to be overwritten in the + RestoreTemplate resource by the update. The fields specified + in the update_mask are relative to the resource, not the + full request. A field will be overwritten if it is in the + mask. + restore_template (google.cloud.backupdr_v1.types.RestoreTemplate): + Required. The restore template 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 request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. Only validate the request, but do + not perform mutations. The default is 'false'. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + restore_template: "RestoreTemplate" = proto.Field( + proto.MESSAGE, + number=2, + message="RestoreTemplate", + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteRestoreTemplateRequest(proto.Message): + r"""Request message for deleting a RestoreTemplate instance. + + Attributes: + name (str): + Required. The name of the restore template to delete. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}' + 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 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 child + RestoreTemplateExecutions will also be deleted. + If false and the RestoreTemplate has any child + executions, the request will fail. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class RunRestoreTemplateRequest(proto.Message): + r"""Request message for running a RestoreTemplate. + + Attributes: + name (str): + Required. The name of the restore template to run. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}' + backup (str): + Optional. The resource name of the Backup to restore from. + If not specified, the latest backup matching the backup + selection configuration in the RestoreTemplate will be used. + Format: + 'projects/{project}/locations/{location}/backupVaults/{backup_vault}/dataSources/{data_source}/backups/{backup}' + 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 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, + ) + backup: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class RunRestoreTemplateResponse(proto.Message): + r"""Response message for RunRestoreTemplate. + + Attributes: + restore_template_execution (str): + Output only. The resource name of the initiated + RestoreTemplateExecution. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}`` + """ + + restore_template_execution: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRestoreTemplatesRequest(proto.Message): + r"""Request message for listing RestoreTemplates. + + Attributes: + parent (str): + Required. The project and location from which to list the + restore templates. Format: + ``projects/{project}/locations/{location}``. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. A page token, received from a previous + ``ListRestoreTemplates`` call. + filter (str): + Optional. Field match expression used to + filter the results. + order_by (str): + Optional. Field by which to sort the results. + """ + + 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 ListRestoreTemplatesResponse(proto.Message): + r"""Response message for listing RestoreTemplates. + + Attributes: + restore_templates (MutableSequence[google.cloud.backupdr_v1.types.RestoreTemplate]): + The list of RestoreTemplates. + next_page_token (str): + A token which may be sent as ``page_token`` in a subsequent + ``ListRestoreTemplates`` call. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + restore_templates: MutableSequence["RestoreTemplate"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="RestoreTemplate", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_template_common.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_template_common.py new file mode 100644 index 000000000000..e32f4b2cd385 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_template_common.py @@ -0,0 +1,141 @@ +# -*- 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 google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1", + manifest={ + "BackupSelectionConfig", + "PreRestoreConfig", + "PostRestoreConfig", + "VerificationConfig", + }, +) + + +class BackupSelectionConfig(proto.Message): + r"""Configuration for selecting a backup. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + data_source (str): + Required. Immutable. The fully qualified URI + of the backupdr data source. + + This field is a member of `oneof`_ ``source``. + """ + + data_source: str = proto.Field( + proto.STRING, + number=1, + oneof="source", + ) + + +class PreRestoreConfig(proto.Message): + r"""Configuration for Pre-Restore. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + timeout (google.protobuf.duration_pb2.Duration): + Optional. The ``timeout`` for this phase. If set, the + ``timeout`` must be positive and less than or equal to 24 + hours (86400s). + cloud_run_job (str): + Cloud Run job action to execute. Format: + ``projects/{project}/locations/{location}/jobs/{job}`` + + This field is a member of `oneof`_ ``pre_restore_action``. + """ + + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + cloud_run_job: str = proto.Field( + proto.STRING, + number=2, + oneof="pre_restore_action", + ) + + +class PostRestoreConfig(proto.Message): + r"""Configuration for Post-Restore. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + timeout (google.protobuf.duration_pb2.Duration): + Optional. The ``timeout`` for this phase. If set, the + ``timeout`` must be positive and less than or equal to 24 + hours (86400s). + cloud_run_job (str): + Cloud Run job action to execute. Format: + ``projects/{project}/locations/{location}/jobs/{job}`` + + This field is a member of `oneof`_ ``post_restore_action``. + """ + + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + cloud_run_job: str = proto.Field( + proto.STRING, + number=2, + oneof="post_restore_action", + ) + + +class VerificationConfig(proto.Message): + r"""Configuration for Verification. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + timeout (google.protobuf.duration_pb2.Duration): + Optional. The ``timeout`` for this phase. If set, the + ``timeout`` must be positive and less than or equal to 24 + hours (86400s). + cloud_run_job (str): + Cloud Run job action to execute. Format: + ``projects/{project}/locations/{location}/jobs/{job}`` + + This field is a member of `oneof`_ ``verification_action``. + """ + + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + cloud_run_job: str = proto.Field( + proto.STRING, + number=2, + oneof="verification_action", + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_template_execution.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_template_execution.py new file mode 100644 index 000000000000..9e90e046047a --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_template_execution.py @@ -0,0 +1,753 @@ +# -*- 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 google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_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 + +from google.cloud.backupdr_v1.types import ( + restore_template_common, + restore_verification_plan, +) + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1", + manifest={ + "PhaseState", + "RestoreTemplateExecution", + "PreparePhaseInfo", + "PreRestorePhaseInfo", + "RestorePhaseInfo", + "PostRestorePhaseInfo", + "VerificationPhaseInfo", + "CleanupPhaseInfo", + "GetRestoreTemplateExecutionRequest", + "TriggerRestoreCleanupRequest", + "ListRestoreTemplateExecutionsRequest", + "ListRestoreTemplateExecutionsResponse", + }, +) + + +class PhaseState(proto.Enum): + r"""Represents the state of a specific phase (RUNNING, SUCCEEDED, + FAILED, etc.). + + Values: + PHASE_STATE_UNSPECIFIED (0): + Phase state is not set. + PENDING (1): + This phase is pending execution. + RUNNING (2): + The phase is actively executing. + SUCCEEDED (3): + The phase completed successfully. + FAILED (4): + The phase encountered an error and failed. + TIMED_OUT (5): + The phase timed out. + SKIPPED (6): + The phase was skipped. + WAITING (7): + The phase is waiting to be executed. + """ + + PHASE_STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + SUCCEEDED = 3 + FAILED = 4 + TIMED_OUT = 5 + SKIPPED = 6 + WAITING = 7 + + +class RestoreTemplateExecution(proto.Message): + r"""A ``RestoreTemplateExecution`` represents a single historical or + active execution run. + + Attributes: + name (str): + Identifier. Resource name of the execution. + resource_type (str): + Output only. The workload resource type being restored. The + format is "{service_name}/{resource_kind}", for example, + "compute.googleapis.com/Instance". + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time of the execution. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time of the execution. + type_ (google.cloud.backupdr_v1.types.RestoreTemplateExecution.ExecutionType): + Output only. The type of the execution. + phase (google.cloud.backupdr_v1.types.RestoreTemplateExecution.ExecutionPhase): + Output only. The current active phase. + state (google.cloud.backupdr_v1.types.RestoreTemplateExecution.ExecutionState): + Output only. State of the execution. + prepare_phase_info (google.cloud.backupdr_v1.types.PreparePhaseInfo): + Output only. Info for the prepare phase. + pre_restore_phase_info (google.cloud.backupdr_v1.types.PreRestorePhaseInfo): + Output only. Info for the pre-restore phase. + restore_phase_info (google.cloud.backupdr_v1.types.RestorePhaseInfo): + Output only. Info for the restore phase. + post_restore_phase_info (google.cloud.backupdr_v1.types.PostRestorePhaseInfo): + Output only. Info for the post-restore phase. + verification_phase_info (google.cloud.backupdr_v1.types.VerificationPhaseInfo): + Output only. Info for the verification phase. + cleanup_phase_info (google.cloud.backupdr_v1.types.CleanupPhaseInfo): + Output only. Info for the cleanup phase. + """ + + class ExecutionType(proto.Enum): + r"""The type of execution. + + Values: + EXECUTION_TYPE_UNSPECIFIED (0): + Execution type not specified. + SCHEDULED (1): + Scheduled execution. + ON_DEMAND (2): + On-demand execution. + """ + + EXECUTION_TYPE_UNSPECIFIED = 0 + SCHEDULED = 1 + ON_DEMAND = 2 + + class ExecutionPhase(proto.Enum): + r"""The phase of execution. + + Values: + EXECUTION_PHASE_UNSPECIFIED (0): + Execution phase not specified. + PREPARING (1): + Preparing for execution. + EXECUTING_PRE_RESTORE_ACTION (2): + Executing pre-restore action. + RESTORING (3): + Restoring the resource. + EXECUTING_POST_RESTORE_ACTION (4): + Executing post-restore action. + VERIFYING (5): + Verifying the restored resource. + CLEANING_UP (6): + Cleaning up resources. + COMPLETED (7): + Execution completed. + """ + + EXECUTION_PHASE_UNSPECIFIED = 0 + PREPARING = 1 + EXECUTING_PRE_RESTORE_ACTION = 2 + RESTORING = 3 + EXECUTING_POST_RESTORE_ACTION = 4 + VERIFYING = 5 + CLEANING_UP = 6 + COMPLETED = 7 + + class ExecutionState(proto.Enum): + r"""State of the execution. + + Values: + EXECUTION_STATE_UNSPECIFIED (0): + State not set. + RUNNING (1): + Execution is running. + SUCCEEDED (2): + Execution succeeded. + FAILED (3): + Execution failed. + DELETING (4): + Resources are being deleted (cleanup). + """ + + EXECUTION_STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + DELETING = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + type_: ExecutionType = proto.Field( + proto.ENUM, + number=5, + enum=ExecutionType, + ) + phase: ExecutionPhase = proto.Field( + proto.ENUM, + number=6, + enum=ExecutionPhase, + ) + state: ExecutionState = proto.Field( + proto.ENUM, + number=7, + enum=ExecutionState, + ) + prepare_phase_info: "PreparePhaseInfo" = proto.Field( + proto.MESSAGE, + number=8, + message="PreparePhaseInfo", + ) + pre_restore_phase_info: "PreRestorePhaseInfo" = proto.Field( + proto.MESSAGE, + number=9, + message="PreRestorePhaseInfo", + ) + restore_phase_info: "RestorePhaseInfo" = proto.Field( + proto.MESSAGE, + number=10, + message="RestorePhaseInfo", + ) + post_restore_phase_info: "PostRestorePhaseInfo" = proto.Field( + proto.MESSAGE, + number=11, + message="PostRestorePhaseInfo", + ) + verification_phase_info: "VerificationPhaseInfo" = proto.Field( + proto.MESSAGE, + number=12, + message="VerificationPhaseInfo", + ) + cleanup_phase_info: "CleanupPhaseInfo" = proto.Field( + proto.MESSAGE, + number=13, + message="CleanupPhaseInfo", + ) + + +class PreparePhaseInfo(proto.Message): + r"""Info for Prepare phase execution. + + Attributes: + phase_state (google.cloud.backupdr_v1.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + backup_selection_config (google.cloud.backupdr_v1.types.BackupSelectionConfig): + Output only. Snapshot of config used in this + execution. + backup (str): + Output only. The source backup used for the + restore. The fully qualified URI of the backupdr + backup. + is_backup_explicitly_passed (bool): + Output only. Indicates whether the backup was + explicitly passed in the request. + restore_verification_plan_association (str): + Output only. The restore verification plan + association associated with the execution. + """ + + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + backup_selection_config: restore_template_common.BackupSelectionConfig = ( + proto.Field( + proto.MESSAGE, + number=5, + message=restore_template_common.BackupSelectionConfig, + ) + ) + backup: str = proto.Field( + proto.STRING, + number=6, + ) + is_backup_explicitly_passed: bool = proto.Field( + proto.BOOL, + number=7, + ) + restore_verification_plan_association: str = proto.Field( + proto.STRING, + number=8, + ) + + +class PreRestorePhaseInfo(proto.Message): + r"""Info for Pre-Restore phase execution. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + phase_state (google.cloud.backupdr_v1.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + pre_restore_config (google.cloud.backupdr_v1.types.PreRestoreConfig): + Output only. Snapshot of config that will be + executed before restore operation. + cloud_run_execution (str): + Output only. The fully qualified URI of the + Cloud Run Execution triggered for pre-restore + actions. + + This field is a member of `oneof`_ ``result``. + """ + + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + pre_restore_config: restore_template_common.PreRestoreConfig = proto.Field( + proto.MESSAGE, + number=5, + message=restore_template_common.PreRestoreConfig, + ) + cloud_run_execution: str = proto.Field( + proto.STRING, + number=6, + oneof="result", + ) + + +class RestorePhaseInfo(proto.Message): + r"""Info for Restore phase execution. + + Attributes: + phase_state (google.cloud.backupdr_v1.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + restore_properties (google.protobuf.struct_pb2.Struct): + Output only. Snapshot of environment config + used during restore of this + RestoreTemplateExecution. + restore_resource (str): + Output only. The resource created or restored + by this execution. + restore_duration (google.protobuf.duration_pb2.Duration): + Output only. Time taken to restore the + resource. + """ + + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + restore_properties: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + restore_resource: str = proto.Field( + proto.STRING, + number=7, + ) + restore_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class PostRestorePhaseInfo(proto.Message): + r"""Info for Post-Restore phase execution. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + phase_state (google.cloud.backupdr_v1.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + post_restore_config (google.cloud.backupdr_v1.types.PostRestoreConfig): + Output only. Snapshot of config that will be + executed after successful restore operation. + cloud_run_execution (str): + Output only. The fully qualified URI of the + Cloud Run Execution triggered for post-restore + actions. + + This field is a member of `oneof`_ ``result``. + """ + + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + post_restore_config: restore_template_common.PostRestoreConfig = proto.Field( + proto.MESSAGE, + number=5, + message=restore_template_common.PostRestoreConfig, + ) + cloud_run_execution: str = proto.Field( + proto.STRING, + number=6, + oneof="result", + ) + + +class VerificationPhaseInfo(proto.Message): + r"""Info for Verification phase execution. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + phase_state (google.cloud.backupdr_v1.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + verification_config (google.cloud.backupdr_v1.types.VerificationConfig): + Output only. Snapshot of config that will be + executed after successful post restore + validation. + cloud_run_execution (str): + Output only. The fully qualified URI of the + Cloud Run Execution triggered for verification. + + This field is a member of `oneof`_ ``result``. + """ + + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + verification_config: restore_template_common.VerificationConfig = proto.Field( + proto.MESSAGE, + number=5, + message=restore_template_common.VerificationConfig, + ) + cloud_run_execution: str = proto.Field( + proto.STRING, + number=6, + oneof="result", + ) + + +class CleanupPhaseInfo(proto.Message): + r"""Info for Cleanup phase execution. + + Attributes: + phase_state (google.cloud.backupdr_v1.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + cleanup_duration (google.protobuf.duration_pb2.Duration): + Output only. Time taken to perform the + cleanup of restored resource. + success_cleanup_rule (google.cloud.backupdr_v1.types.RestoreVerificationCleanupRule): + Output only. Snapshot of cleanup rule + provided for this execution when execution is + successful. + failure_cleanup_rule (google.cloud.backupdr_v1.types.RestoreVerificationCleanupRule): + Output only. Snapshot of cleanup rule + provided for this execution when execution is + failed. + cleanup_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the resources will + be cleaned up. + """ + + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + cleanup_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + success_cleanup_rule: restore_verification_plan.RestoreVerificationCleanupRule = ( + proto.Field( + proto.MESSAGE, + number=6, + message=restore_verification_plan.RestoreVerificationCleanupRule, + ) + ) + failure_cleanup_rule: restore_verification_plan.RestoreVerificationCleanupRule = ( + proto.Field( + proto.MESSAGE, + number=7, + message=restore_verification_plan.RestoreVerificationCleanupRule, + ) + ) + cleanup_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +class GetRestoreTemplateExecutionRequest(proto.Message): + r"""Request message for getting a RestoreTemplateExecution + instance. + + Attributes: + name (str): + Required. The name of the restore template execution to + retrieve. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_id}' + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TriggerRestoreCleanupRequest(proto.Message): + r"""Request message for triggering a restore cleanup. + + Attributes: + name (str): + Required. Name of the restore template execution. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_id}' + 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. + + 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 ListRestoreTemplateExecutionsRequest(proto.Message): + r"""Request message for listing RestoreTemplateExecutions. + + Attributes: + parent (str): + Required. The project, location, and restore template for + which to retrieve executions information. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}``. + page_size (int): + Optional. Requested page size. + page_token (str): + Optional. A token identifying a page of + results. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + 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 ListRestoreTemplateExecutionsResponse(proto.Message): + r"""Response message for listing RestoreTemplateExecutions. + + Attributes: + restore_template_executions (MutableSequence[google.cloud.backupdr_v1.types.RestoreTemplateExecution]): + The list of RestoreTemplateExecution + instances. + next_page_token (str): + A token identifying a page of results. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + restore_template_executions: MutableSequence["RestoreTemplateExecution"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="RestoreTemplateExecution", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_verification_plan.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_verification_plan.py new file mode 100644 index 000000000000..67daeac77b1a --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_verification_plan.py @@ -0,0 +1,438 @@ +# -*- 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 google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1", + manifest={ + "RestoreVerificationPlan", + "RestoreVerificationCleanupRule", + "CreateRestoreVerificationPlanRequest", + "GetRestoreVerificationPlanRequest", + "ListRestoreVerificationPlansRequest", + "ListRestoreVerificationPlansResponse", + "DeleteRestoreVerificationPlanRequest", + }, +) + + +class RestoreVerificationPlan(proto.Message): + r"""A ``RestoreVerificationPlan`` specifies the scheduling and clean-up + template for automated restore verification. It contains a + ``schedule`` to dictate when the verifications should run, and a + ``RestoreVerificationCleanupRule`` for post-verification resource + deletion. + + Attributes: + name (str): + Output only. Identifier. The resource name of the + ``RestoreVerificationPlan``. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + description (str): + Optional. The description of the ``RestoreVerificationPlan`` + resource. + + The description allows for additional details about + ``RestoreVerificationPlan`` and its use cases to be + provided. An example description is the following: "This is + a restore verification plan that performs a daily + verification and cleans up the resources immediately after." + The description must be at most 2048 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the ``RestoreVerificationPlan`` was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the ``RestoreVerificationPlan`` was last + updated. + labels (MutableMapping[str, str]): + Optional. User-defined labels. + state (google.cloud.backupdr_v1.types.RestoreVerificationPlan.State): + Output only. The ``State`` for the + ``RestoreVerificationPlan``. + schedule (str): + Required. Describes the schedule on which the restore + verification will be executed. + + The schedule is specified as a + `Crontab `__ + string. + time_zone (str): + Optional. Specifies the time zone to be used in interpreting + [schedule][google.cloud.backupdr.v1.RestoreVerificationPlan.schedule]. + The value of this field must be a time zone name from the + `tz database `__, + like "America/New_York" or "UTC". Defaults to ``UTC`` if not + specified. + success_cleanup_rule (google.cloud.backupdr_v1.types.RestoreVerificationCleanupRule): + Optional. The cleanup rule to apply if the + restore verification succeeds. + failure_cleanup_rule (google.cloud.backupdr_v1.types.RestoreVerificationCleanupRule): + Optional. The cleanup rule to apply if the + restore verification fails. + """ + + class State(proto.Enum): + r"""``State`` enumerates the possible states for a + ``RestoreVerificationPlan``. + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The resource is being created. + ACTIVE (2): + The resource has been created and is fully + usable. + DELETING (3): + The resource is being deleted. + INACTIVE (4): + The resource has been created but is not + usable. + UPDATING (5): + The resource is being updated. + ERROR (6): + The resource is in an error state due to a + configuration issue. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + INACTIVE = 4 + UPDATING = 5 + ERROR = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + state: State = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + schedule: str = proto.Field( + proto.STRING, + number=7, + ) + time_zone: str = proto.Field( + proto.STRING, + number=8, + ) + success_cleanup_rule: "RestoreVerificationCleanupRule" = proto.Field( + proto.MESSAGE, + number=9, + message="RestoreVerificationCleanupRule", + ) + failure_cleanup_rule: "RestoreVerificationCleanupRule" = proto.Field( + proto.MESSAGE, + number=10, + message="RestoreVerificationCleanupRule", + ) + + +class RestoreVerificationCleanupRule(proto.Message): + r"""Defines the specific cleanup action. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cleanup_delay (google.protobuf.duration_pb2.Duration): + Optional. Duration after restore finishes + when cleanup triggers. Delay must be + non-negative and at most 30 days (2592000 + seconds). + skip_cleanup (bool): + Optional. If set to true, the restored + resource will not be cleaned up. + + This field is a member of `oneof`_ ``_skip_cleanup``. + """ + + cleanup_delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + skip_cleanup: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + +class CreateRestoreVerificationPlanRequest(proto.Message): + r"""The request message for creating a ``RestoreVerificationPlan``. + + Attributes: + parent (str): + Required. The ``RestoreVerificationPlan`` project and + location in the format + ``projects/{project}/locations/{location}``. In Google Cloud + Backup and DR locations map to Google Cloud regions, for + example **us-central1**. + restore_verification_plan_id (str): + Required. The name of the ``RestoreVerificationPlan`` to + create. The name must be unique for the specified project + and location. The name must start with a lowercase letter + followed by up to 62 lowercase letters, numbers, or hyphens. + Pattern, ``^[a-z]([-a-z0-9]*[a-z0-9])?$``. + restore_verification_plan (google.cloud.backupdr_v1.types.RestoreVerificationPlan): + Required. The ``RestoreVerificationPlan`` resource object 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, + ) + restore_verification_plan_id: str = proto.Field( + proto.STRING, + number=2, + ) + restore_verification_plan: "RestoreVerificationPlan" = proto.Field( + proto.MESSAGE, + number=3, + message="RestoreVerificationPlan", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetRestoreVerificationPlanRequest(proto.Message): + r"""The request message for getting a ``RestoreVerificationPlan``. + + Attributes: + name (str): + Required. The resource name of the + ``RestoreVerificationPlan`` to retrieve. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRestoreVerificationPlansRequest(proto.Message): + r"""The request message for getting a list of + ``RestoreVerificationPlans``. + + Attributes: + parent (str): + Required. The project and location for which to retrieve + ``RestoreVerificationPlans`` information. Format: + ``projects/{project}/locations/{location}``. In Google Cloud + Backup and DR, locations map to Google Cloud regions, for + example **us-central1**. To retrieve restore verification + plans for all locations, use "-" for the ``{location}`` + value. + page_size (int): + Optional. The maximum number of ``RestoreVerificationPlans`` + to return in a single response. If not specified, a default + value will be chosen by the service. Note that the response + may include a partial list and a caller should only rely on + the response's + [next_page_token][google.cloud.backupdr.v1.ListRestoreVerificationPlansResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + Optional. The value of + [next_page_token][google.cloud.backupdr.v1.ListRestoreVerificationPlansResponse.next_page_token] + received from a previous ``ListRestoreVerificationPlans`` + call. Provide this to retrieve the subsequent page in a + multi-page list of results. When paginating, all other + parameters provided to ``ListRestoreVerificationPlans`` must + match the call that provided the page token. + filter (str): + Optional. Field match expression used to + filter the results. + order_by (str): + Optional. Field by which to sort the results. + """ + + 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 ListRestoreVerificationPlansResponse(proto.Message): + r"""The response message for getting a list of + ``RestoreVerificationPlans``. + + Attributes: + restore_verification_plans (MutableSequence[google.cloud.backupdr_v1.types.RestoreVerificationPlan]): + The list of ``RestoreVerificationPlans`` in the project for + the specified location. + + If the ``{location}`` value in the request is "-", the + response contains a list of resources from all locations. In + case any location is unreachable, the response will only + return restore verification plans in reachable locations and + the 'unreachable' field will be populated with a list of + unreachable locations. + next_page_token (str): + A token which may be sent as + [page_token][google.cloud.backupdr.v1.ListRestoreVerificationPlansRequest.page_token] + in a subsequent ``ListRestoreVerificationPlans`` call to + retrieve the next page of results. If this field is omitted + or empty, then there are no more results to return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + restore_verification_plans: MutableSequence["RestoreVerificationPlan"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="RestoreVerificationPlan", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DeleteRestoreVerificationPlanRequest(proto.Message): + r"""The request message for deleting a ``RestoreVerificationPlan``. + + Attributes: + name (str): + Required. The resource name of the + ``RestoreVerificationPlan`` to delete. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + 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). + force (bool): + Optional. If set to true, any + RestoreVerificationPlanAssociations linked to + this RestoreVerificationPlan will also be + deleted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_verification_plan_association.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_verification_plan_association.py new file mode 100644 index 000000000000..6e5f18212c8a --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1/types/restore_verification_plan_association.py @@ -0,0 +1,431 @@ +# -*- 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 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( + package="google.cloud.backupdr.v1", + manifest={ + "RestoreVerificationPlanAssociation", + "TriggerSummary", + "CreateRestoreVerificationPlanAssociationRequest", + "GetRestoreVerificationPlanAssociationRequest", + "ListRestoreVerificationPlanAssociationsRequest", + "ListRestoreVerificationPlanAssociationsResponse", + "DeleteRestoreVerificationPlanAssociationRequest", + "TriggerRestoreVerificationRequest", + "TriggerRestoreVerificationResponse", + }, +) + + +class RestoreVerificationPlanAssociation(proto.Message): + r"""A ``RestoreVerificationPlanAssociation`` binds a specific workload + to a ``RestoreVerificationPlan``. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Output only. Identifier. The resource name of the + ``RestoreVerificationPlanAssociation``. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + description (str): + Optional. The description of the + ``RestoreVerificationPlanAssociation`` resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the association + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the association + was updated. + state (google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation.State): + Output only. The ``State`` for the + ``RestoreVerificationPlanAssociation``. + trigger_summary (google.cloud.backupdr_v1.types.TriggerSummary): + Output only. Results of the most recent + automated restore initiation and the next + scheduled execution time. + resource_type (str): + Required. Immutable. The type of the Google Cloud resource + (e.g., ``compute.googleapis.com/Instance``, + ``sqladmin.googleapis.com/Instance``). + restore_template (str): + Required. Immutable. The canonical name of + the RestoreTemplate to trigger. + + This field is a member of `oneof`_ ``association``. + labels (MutableMapping[str, str]): + Optional. User-defined labels. + """ + + class State(proto.Enum): + r"""``State`` enumerates the possible states for a + ``RestoreVerificationPlanAssociation``. + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The resource is being created. + ACTIVE (2): + The resource has been created and is fully + usable. + DELETING (3): + The resource is being deleted. + INACTIVE (4): + The resource has been created but is not + usable. + UPDATING (5): + The resource is being updated. + ERROR (6): + The resource is in an error state due to a + configuration issue. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + INACTIVE = 4 + UPDATING = 5 + ERROR = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + trigger_summary: "TriggerSummary" = proto.Field( + proto.MESSAGE, + number=6, + message="TriggerSummary", + ) + resource_type: str = proto.Field( + proto.STRING, + number=7, + ) + restore_template: str = proto.Field( + proto.STRING, + number=8, + oneof="association", + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + + +class TriggerSummary(proto.Message): + r"""``TriggerSummary`` contains the results of the most recent automated + restore initiation and the next scheduled execution time. + + Attributes: + last_trigger_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time of the most recent + trigger initiation. + next_trigger_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The scheduled time of the next + trigger initiation. + last_trigger_error (google.rpc.status_pb2.Status): + Output only. The error status of the most + recent failed trigger. + last_verification_execution (str): + Output only. The resource name of the most recent initiated + RestoreTemplateExecution. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}`` + """ + + last_trigger_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + next_trigger_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + last_trigger_error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + last_verification_execution: str = proto.Field( + proto.STRING, + number=4, + ) + + +class CreateRestoreVerificationPlanAssociationRequest(proto.Message): + r"""Request message for CreateRestoreVerificationPlanAssociation. + + Attributes: + parent (str): + Required. The parent resource where this association will be + created. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + restore_verification_plan_association_id (str): + Required. The ID to use for the association, which will + become the final component of the association's resource + name. + + This value should be 1-63 characters, and valid characters + are /[a-z0-9\_-]/. + restore_verification_plan_association (google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation): + Required. The + RestoreVerificationPlanAssociation resource 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 that the server has already received the + duplicate request and can avoid responding with + an error. 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, + ) + restore_verification_plan_association_id: str = proto.Field( + proto.STRING, + number=2, + ) + restore_verification_plan_association: "RestoreVerificationPlanAssociation" = ( + proto.Field( + proto.MESSAGE, + number=3, + message="RestoreVerificationPlanAssociation", + ) + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetRestoreVerificationPlanAssociationRequest(proto.Message): + r"""Request message for GetRestoreVerificationPlanAssociation. + + Attributes: + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to retrieve. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRestoreVerificationPlanAssociationsRequest(proto.Message): + r"""Request message for ListRestoreVerificationPlanAssociations. + + Attributes: + parent (str): + Required. The parent RestoreVerificationPlan name. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + page_size (int): + Optional. The maximum number of associations + to return. The service may return fewer than + this value. If unspecified, at most 500 + associations will be returned. The maximum value + is 1000; values above 1000 will be coerced to + 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListRestoreVerificationPlanAssociations`` call. Provide + this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListRestoreVerificationPlanAssociations`` must match the + call that provided the page token. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + 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 ListRestoreVerificationPlanAssociationsResponse(proto.Message): + r"""Response message for ListRestoreVerificationPlanAssociations. + + Attributes: + restore_verification_plan_associations (MutableSequence[google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation]): + The list of + RestoreVerificationPlanAssociations. + 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]): + Unordered list. Locations that could not be + reached. + """ + + @property + def raw_page(self): + return self + + restore_verification_plan_associations: MutableSequence[ + "RestoreVerificationPlanAssociation" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="RestoreVerificationPlanAssociation", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DeleteRestoreVerificationPlanAssociationRequest(proto.Message): + r"""Request message for DeleteRestoreVerificationPlanAssociation. + + Attributes: + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to delete. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + 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 that the server has already received the + duplicate request and can avoid responding with + an error. 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 TriggerRestoreVerificationRequest(proto.Message): + r"""Request message for TriggerRestoreVerification. + + Attributes: + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to trigger. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + 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 that the server has already received the + duplicate request and can avoid responding with + an error. 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 TriggerRestoreVerificationResponse(proto.Message): + r"""Response message for TriggerRestoreVerification. + + Attributes: + restore_template_execution (str): + Output only. The resource name of the initiated + RestoreTemplateExecution. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}`` + """ + + restore_template_execution: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/__init__.py index 932b3142187c..289fad1dae4b 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/__init__.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/__init__.py @@ -43,6 +43,11 @@ "google.cloud.backupdr_v1beta.types.bindingmatchingresource", "google.cloud.backupdr_v1beta.types.datasourcereference", "google.cloud.backupdr_v1beta.types.protection_summary", + "google.cloud.backupdr_v1beta.types.restore_template", + "google.cloud.backupdr_v1beta.types.restore_template_common", + "google.cloud.backupdr_v1beta.types.restore_template_execution", + "google.cloud.backupdr_v1beta.types.restore_verification_plan", + "google.cloud.backupdr_v1beta.types.restore_verification_plan_association", } @@ -166,6 +171,7 @@ UpdateBackupRequest, UpdateBackupVaultRequest, UpdateDataSourceRequest, + VerificationSummary, ) from .types.backupvault_alloydb import ( AlloyDBClusterBackupPlanAssociationProperties, @@ -244,6 +250,58 @@ PitrSettings, ResourceBackupConfig, ) +from .types.restore_template import ( + CreateRestoreTemplateRequest, + DeleteRestoreTemplateRequest, + ExecutionSummary, + GetRestoreTemplateRequest, + ListRestoreTemplatesRequest, + ListRestoreTemplatesResponse, + RestoreTemplate, + RunRestoreTemplateRequest, + RunRestoreTemplateResponse, + UpdateRestoreTemplateRequest, +) +from .types.restore_template_common import ( + BackupSelectionConfig, + PostRestoreConfig, + PreRestoreConfig, + VerificationConfig, +) +from .types.restore_template_execution import ( + CleanupPhaseInfo, + GetRestoreTemplateExecutionRequest, + ListRestoreTemplateExecutionsRequest, + ListRestoreTemplateExecutionsResponse, + PhaseState, + PostRestorePhaseInfo, + PreparePhaseInfo, + PreRestorePhaseInfo, + RestorePhaseInfo, + RestoreTemplateExecution, + TriggerRestoreCleanupRequest, + VerificationPhaseInfo, +) +from .types.restore_verification_plan import ( + CreateRestoreVerificationPlanRequest, + DeleteRestoreVerificationPlanRequest, + GetRestoreVerificationPlanRequest, + ListRestoreVerificationPlansRequest, + ListRestoreVerificationPlansResponse, + RestoreVerificationCleanupRule, + RestoreVerificationPlan, +) +from .types.restore_verification_plan_association import ( + CreateRestoreVerificationPlanAssociationRequest, + DeleteRestoreVerificationPlanAssociationRequest, + GetRestoreVerificationPlanAssociationRequest, + ListRestoreVerificationPlanAssociationsRequest, + ListRestoreVerificationPlanAssociationsResponse, + RestoreVerificationPlanAssociation, + TriggerRestoreVerificationRequest, + TriggerRestoreVerificationResponse, + TriggerSummary, +) __all__ = ( "BackupDRAsyncClient", @@ -283,6 +341,7 @@ "BackupPlanDetail", "BackupPlanRevision", "BackupRule", + "BackupSelectionConfig", "BackupVault", "BackupVaultView", "BackupView", @@ -290,6 +349,7 @@ "BindingEvaluationSummary", "BindingMatchingResource", "BindingSummary", + "CleanupPhaseInfo", "CloudSqlInstanceBackupPlanAssociationProperties", "CloudSqlInstanceBackupProperties", "CloudSqlInstanceDataSourceProperties", @@ -307,6 +367,9 @@ "CreateBackupPlanRequest", "CreateBackupVaultRequest", "CreateManagementServerRequest", + "CreateRestoreTemplateRequest", + "CreateRestoreVerificationPlanAssociationRequest", + "CreateRestoreVerificationPlanRequest", "Criteria", "CustomerEncryptionKey", "DataSource", @@ -321,6 +384,9 @@ "DeleteBackupRequest", "DeleteBackupVaultRequest", "DeleteManagementServerRequest", + "DeleteRestoreTemplateRequest", + "DeleteRestoreVerificationPlanAssociationRequest", + "DeleteRestoreVerificationPlanRequest", "DiskBackupPlanProperties", "DiskBackupProperties", "DiskDataSourceProperties", @@ -328,6 +394,7 @@ "DiskTargetEnvironment", "DisplayDevice", "Entry", + "ExecutionSummary", "FetchBackupPlanAssociationsForResourceTypeRequest", "FetchBackupPlanAssociationsForResourceTypeResponse", "FetchBackupsForResourceTypeRequest", @@ -349,6 +416,10 @@ "GetDataSourceReferenceRequest", "GetDataSourceRequest", "GetManagementServerRequest", + "GetRestoreTemplateExecutionRequest", + "GetRestoreTemplateRequest", + "GetRestoreVerificationPlanAssociationRequest", + "GetRestoreVerificationPlanRequest", "GuestOsFeature", "InitializeServiceRequest", "InitializeServiceResponse", @@ -382,6 +453,14 @@ "ListManagementServersResponse", "ListResourceBackupConfigsRequest", "ListResourceBackupConfigsResponse", + "ListRestoreTemplateExecutionsRequest", + "ListRestoreTemplateExecutionsResponse", + "ListRestoreTemplatesRequest", + "ListRestoreTemplatesResponse", + "ListRestoreVerificationPlanAssociationsRequest", + "ListRestoreVerificationPlanAssociationsResponse", + "ListRestoreVerificationPlansRequest", + "ListRestoreVerificationPlansResponse", "ManagementServer", "ManagementURI", "MatchingCondition", @@ -390,14 +469,28 @@ "NetworkInterface", "NetworkPerformanceConfig", "OperationMetadata", + "PhaseState", "PitrSettings", "PolicyEvaluationSummary", + "PostRestoreConfig", + "PostRestorePhaseInfo", + "PreRestoreConfig", + "PreRestorePhaseInfo", + "PreparePhaseInfo", "RegionDiskTargetEnvironment", "ResourceBackupConfig", "RestoreBackupRequest", "RestoreBackupResponse", "RestoreDiskFromInstanceOptions", + "RestorePhaseInfo", + "RestoreTemplate", + "RestoreTemplateExecution", + "RestoreVerificationCleanupRule", + "RestoreVerificationPlan", + "RestoreVerificationPlanAssociation", "RuleConfigInfo", + "RunRestoreTemplateRequest", + "RunRestoreTemplateResponse", "Scheduling", "SchedulingDuration", "ServiceAccount", @@ -406,12 +499,20 @@ "Tags", "TargetResource", "TriggerBackupRequest", + "TriggerRestoreCleanupRequest", + "TriggerRestoreVerificationRequest", + "TriggerRestoreVerificationResponse", + "TriggerSummary", "UpdateAutoProtectionPolicyRequest", "UpdateBackupPlanAssociationRequest", "UpdateBackupPlanRequest", "UpdateBackupRequest", "UpdateBackupVaultRequest", "UpdateDataSourceRequest", + "UpdateRestoreTemplateRequest", + "VerificationConfig", + "VerificationPhaseInfo", + "VerificationSummary", "WeekDayOfMonth", "WorkforceIdentityBasedManagementURI", "WorkforceIdentityBasedOAuth2ClientID", diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_metadata.json b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_metadata.json index 2edda320fbff..247f319266b6 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_metadata.json +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/gapic_metadata.json @@ -40,6 +40,21 @@ "create_management_server" ] }, + "CreateRestoreTemplate": { + "methods": [ + "create_restore_template" + ] + }, + "CreateRestoreVerificationPlan": { + "methods": [ + "create_restore_verification_plan" + ] + }, + "CreateRestoreVerificationPlanAssociation": { + "methods": [ + "create_restore_verification_plan_association" + ] + }, "DeleteAutoProtectionPolicy": { "methods": [ "delete_auto_protection_policy" @@ -70,6 +85,21 @@ "delete_management_server" ] }, + "DeleteRestoreTemplate": { + "methods": [ + "delete_restore_template" + ] + }, + "DeleteRestoreVerificationPlan": { + "methods": [ + "delete_restore_verification_plan" + ] + }, + "DeleteRestoreVerificationPlanAssociation": { + "methods": [ + "delete_restore_verification_plan_association" + ] + }, "FetchBackupPlanAssociationsForResourceType": { "methods": [ "fetch_backup_plan_associations_for_resource_type" @@ -145,6 +175,26 @@ "get_management_server" ] }, + "GetRestoreTemplate": { + "methods": [ + "get_restore_template" + ] + }, + "GetRestoreTemplateExecution": { + "methods": [ + "get_restore_template_execution" + ] + }, + "GetRestoreVerificationPlan": { + "methods": [ + "get_restore_verification_plan" + ] + }, + "GetRestoreVerificationPlanAssociation": { + "methods": [ + "get_restore_verification_plan_association" + ] + }, "InitializeService": { "methods": [ "initialize_service" @@ -215,16 +265,51 @@ "list_management_servers" ] }, + "ListRestoreTemplateExecutions": { + "methods": [ + "list_restore_template_executions" + ] + }, + "ListRestoreTemplates": { + "methods": [ + "list_restore_templates" + ] + }, + "ListRestoreVerificationPlanAssociations": { + "methods": [ + "list_restore_verification_plan_associations" + ] + }, + "ListRestoreVerificationPlans": { + "methods": [ + "list_restore_verification_plans" + ] + }, "RestoreBackup": { "methods": [ "restore_backup" ] }, + "RunRestoreTemplate": { + "methods": [ + "run_restore_template" + ] + }, "TriggerBackup": { "methods": [ "trigger_backup" ] }, + "TriggerRestoreCleanup": { + "methods": [ + "trigger_restore_cleanup" + ] + }, + "TriggerRestoreVerification": { + "methods": [ + "trigger_restore_verification" + ] + }, "UpdateAutoProtectionPolicy": { "methods": [ "update_auto_protection_policy" @@ -254,6 +339,11 @@ "methods": [ "update_data_source" ] + }, + "UpdateRestoreTemplate": { + "methods": [ + "update_restore_template" + ] } } }, @@ -290,6 +380,21 @@ "create_management_server" ] }, + "CreateRestoreTemplate": { + "methods": [ + "create_restore_template" + ] + }, + "CreateRestoreVerificationPlan": { + "methods": [ + "create_restore_verification_plan" + ] + }, + "CreateRestoreVerificationPlanAssociation": { + "methods": [ + "create_restore_verification_plan_association" + ] + }, "DeleteAutoProtectionPolicy": { "methods": [ "delete_auto_protection_policy" @@ -320,6 +425,21 @@ "delete_management_server" ] }, + "DeleteRestoreTemplate": { + "methods": [ + "delete_restore_template" + ] + }, + "DeleteRestoreVerificationPlan": { + "methods": [ + "delete_restore_verification_plan" + ] + }, + "DeleteRestoreVerificationPlanAssociation": { + "methods": [ + "delete_restore_verification_plan_association" + ] + }, "FetchBackupPlanAssociationsForResourceType": { "methods": [ "fetch_backup_plan_associations_for_resource_type" @@ -395,6 +515,26 @@ "get_management_server" ] }, + "GetRestoreTemplate": { + "methods": [ + "get_restore_template" + ] + }, + "GetRestoreTemplateExecution": { + "methods": [ + "get_restore_template_execution" + ] + }, + "GetRestoreVerificationPlan": { + "methods": [ + "get_restore_verification_plan" + ] + }, + "GetRestoreVerificationPlanAssociation": { + "methods": [ + "get_restore_verification_plan_association" + ] + }, "InitializeService": { "methods": [ "initialize_service" @@ -465,16 +605,51 @@ "list_management_servers" ] }, + "ListRestoreTemplateExecutions": { + "methods": [ + "list_restore_template_executions" + ] + }, + "ListRestoreTemplates": { + "methods": [ + "list_restore_templates" + ] + }, + "ListRestoreVerificationPlanAssociations": { + "methods": [ + "list_restore_verification_plan_associations" + ] + }, + "ListRestoreVerificationPlans": { + "methods": [ + "list_restore_verification_plans" + ] + }, "RestoreBackup": { "methods": [ "restore_backup" ] }, + "RunRestoreTemplate": { + "methods": [ + "run_restore_template" + ] + }, "TriggerBackup": { "methods": [ "trigger_backup" ] }, + "TriggerRestoreCleanup": { + "methods": [ + "trigger_restore_cleanup" + ] + }, + "TriggerRestoreVerification": { + "methods": [ + "trigger_restore_verification" + ] + }, "UpdateAutoProtectionPolicy": { "methods": [ "update_auto_protection_policy" @@ -504,6 +679,11 @@ "methods": [ "update_data_source" ] + }, + "UpdateRestoreTemplate": { + "methods": [ + "update_restore_template" + ] } } }, @@ -540,6 +720,21 @@ "create_management_server" ] }, + "CreateRestoreTemplate": { + "methods": [ + "create_restore_template" + ] + }, + "CreateRestoreVerificationPlan": { + "methods": [ + "create_restore_verification_plan" + ] + }, + "CreateRestoreVerificationPlanAssociation": { + "methods": [ + "create_restore_verification_plan_association" + ] + }, "DeleteAutoProtectionPolicy": { "methods": [ "delete_auto_protection_policy" @@ -570,6 +765,21 @@ "delete_management_server" ] }, + "DeleteRestoreTemplate": { + "methods": [ + "delete_restore_template" + ] + }, + "DeleteRestoreVerificationPlan": { + "methods": [ + "delete_restore_verification_plan" + ] + }, + "DeleteRestoreVerificationPlanAssociation": { + "methods": [ + "delete_restore_verification_plan_association" + ] + }, "FetchBackupPlanAssociationsForResourceType": { "methods": [ "fetch_backup_plan_associations_for_resource_type" @@ -645,6 +855,26 @@ "get_management_server" ] }, + "GetRestoreTemplate": { + "methods": [ + "get_restore_template" + ] + }, + "GetRestoreTemplateExecution": { + "methods": [ + "get_restore_template_execution" + ] + }, + "GetRestoreVerificationPlan": { + "methods": [ + "get_restore_verification_plan" + ] + }, + "GetRestoreVerificationPlanAssociation": { + "methods": [ + "get_restore_verification_plan_association" + ] + }, "InitializeService": { "methods": [ "initialize_service" @@ -715,16 +945,51 @@ "list_management_servers" ] }, + "ListRestoreTemplateExecutions": { + "methods": [ + "list_restore_template_executions" + ] + }, + "ListRestoreTemplates": { + "methods": [ + "list_restore_templates" + ] + }, + "ListRestoreVerificationPlanAssociations": { + "methods": [ + "list_restore_verification_plan_associations" + ] + }, + "ListRestoreVerificationPlans": { + "methods": [ + "list_restore_verification_plans" + ] + }, "RestoreBackup": { "methods": [ "restore_backup" ] }, + "RunRestoreTemplate": { + "methods": [ + "run_restore_template" + ] + }, "TriggerBackup": { "methods": [ "trigger_backup" ] }, + "TriggerRestoreCleanup": { + "methods": [ + "trigger_restore_cleanup" + ] + }, + "TriggerRestoreVerification": { + "methods": [ + "trigger_restore_verification" + ] + }, "UpdateAutoProtectionPolicy": { "methods": [ "update_auto_protection_policy" @@ -754,6 +1019,11 @@ "methods": [ "update_data_source" ] + }, + "UpdateRestoreTemplate": { + "methods": [ + "update_restore_template" + ] } } } diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/async_client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/async_client.py index 9faa0fc739d4..f845e85ed18c 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/async_client.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/async_client.py @@ -49,6 +49,7 @@ 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.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -74,6 +75,18 @@ backupvault_gce, bindingmatchingresource, datasourcereference, + restore_template, + restore_template_common, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1beta.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .client import BackupDRClient @@ -156,12 +169,38 @@ class BackupDRAsyncClient: parse_data_source_reference_path = staticmethod( BackupDRClient.parse_data_source_reference_path ) + execution_path = staticmethod(BackupDRClient.execution_path) + parse_execution_path = staticmethod(BackupDRClient.parse_execution_path) instance_path = staticmethod(BackupDRClient.instance_path) parse_instance_path = staticmethod(BackupDRClient.parse_instance_path) + job_path = staticmethod(BackupDRClient.job_path) + parse_job_path = staticmethod(BackupDRClient.parse_job_path) management_server_path = staticmethod(BackupDRClient.management_server_path) parse_management_server_path = staticmethod( BackupDRClient.parse_management_server_path ) + restore_template_path = staticmethod(BackupDRClient.restore_template_path) + parse_restore_template_path = staticmethod( + BackupDRClient.parse_restore_template_path + ) + restore_template_execution_path = staticmethod( + BackupDRClient.restore_template_execution_path + ) + parse_restore_template_execution_path = staticmethod( + BackupDRClient.parse_restore_template_execution_path + ) + restore_verification_plan_path = staticmethod( + BackupDRClient.restore_verification_plan_path + ) + parse_restore_verification_plan_path = staticmethod( + BackupDRClient.parse_restore_verification_plan_path + ) + restore_verification_plan_association_path = staticmethod( + BackupDRClient.restore_verification_plan_association_path + ) + parse_restore_verification_plan_association_path = staticmethod( + BackupDRClient.parse_restore_verification_plan_association_path + ) storage_pool_path = staticmethod(BackupDRClient.storage_pool_path) parse_storage_pool_path = staticmethod(BackupDRClient.parse_storage_pool_path) common_billing_account_path = staticmethod( @@ -352,39 +391,2527 @@ def __init__( client_info=client_info, ) - if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( - std_logging.DEBUG - ): # pragma: NO COVER - _LOGGER.debug( - "Created client `google.cloud.backupdr_v1beta.BackupDRAsyncClient`.", - extra={ - "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "universeDomain": getattr( - self._client._transport._credentials, "universe_domain", "" - ), - "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", - "credentialsInfo": getattr( - self.transport._credentials, "get_cred_info", lambda: None - )(), - } - if hasattr(self._client._transport, "_credentials") - else { - "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "credentialsType": None, - }, - ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.backupdr_v1beta.BackupDRAsyncClient`.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "credentialsType": None, + }, + ) + + async def list_management_servers( + self, + request: Optional[Union[backupdr.ListManagementServersRequest, 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.ListManagementServersAsyncPager: + r"""Lists ManagementServers in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_management_servers(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListManagementServersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_management_servers(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListManagementServersRequest, dict]]): + The request object. Request message for listing + management servers. + parent (:class:`str`): + Required. The project and location for which to retrieve + management servers information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + management servers for all locations, use "-" for the + '{location}' value. + + 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.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersAsyncPager: + Response message for listing + management servers. + 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, backupdr.ListManagementServersRequest): + request = backupdr.ListManagementServersRequest(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_management_servers + ] + + # 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.ListManagementServersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_management_server( + self, + request: Optional[Union[backupdr.GetManagementServerRequest, 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]]] = (), + ) -> backupdr.ManagementServer: + r"""Gets details of a single ManagementServer. + + .. 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 backupdr_v1beta + + async def sample_get_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetManagementServerRequest( + name="name_value", + ) + + # Make the request + response = await client.get_management_server(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetManagementServerRequest, dict]]): + The request object. Request message for getting a + management server instance. + name (:class:`str`): + Required. Name of the management server resource name, + in the format + 'projects/{project_id}/locations/{location}/managementServers/{resource_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.cloud.backupdr_v1beta.types.ManagementServer: + ManagementServer describes a single + BackupDR ManagementServer 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, backupdr.GetManagementServerRequest): + request = backupdr.GetManagementServerRequest(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_management_server + ] + + # 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_management_server( + self, + request: Optional[Union[backupdr.CreateManagementServerRequest, dict]] = None, + *, + parent: Optional[str] = None, + management_server: Optional[backupdr.ManagementServer] = None, + management_server_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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new ManagementServer in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_create_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateManagementServerRequest( + parent="parent_value", + management_server_id="management_server_id_value", + ) + + # Make the request + operation = await client.create_management_server(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateManagementServerRequest, dict]]): + The request object. Request message for creating a + management server instance. + parent (:class:`str`): + Required. The management server project and location in + the format 'projects/{project_id}/locations/{location}'. + In Google Cloud Backup and DR locations map to Google + Cloud regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + management_server (:class:`google.cloud.backupdr_v1beta.types.ManagementServer`): + Required. A [management server + resource][google.cloud.backupdr.v1.ManagementServer] + + This corresponds to the ``management_server`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + management_server_id (:class:`str`): + Required. The name of the management + server to create. The name must be + unique for the specified project and + location. + + This corresponds to the ``management_server_id`` 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.backupdr_v1beta.types.ManagementServer` + ManagementServer describes a single BackupDR + ManagementServer 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 = [parent, management_server, management_server_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, backupdr.CreateManagementServerRequest): + request = backupdr.CreateManagementServerRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if management_server is not None: + request.management_server = management_server + if management_server_id is not None: + request.management_server_id = management_server_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_management_server + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + backupdr.ManagementServer, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_management_server( + self, + request: Optional[Union[backupdr.DeleteManagementServerRequest, 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 single ManagementServer. + + .. 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 backupdr_v1beta + + async def sample_delete_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteManagementServerRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_management_server(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest, dict]]): + The request object. Request message for deleting a + management server instance. + name (:class:`str`): + Required. Name of the resource + 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, backupdr.DeleteManagementServerRequest): + request = backupdr.DeleteManagementServerRequest(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_management_server + ] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_restore_template( + self, + request: Optional[ + Union[gcb_restore_template.CreateRestoreTemplateRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + restore_template: Optional[gcb_restore_template.RestoreTemplate] = None, + restore_template_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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new RestoreTemplate in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_create_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_template = backupdr_v1beta.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1beta.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + restore_template=restore_template, + ) + + # Make the request + operation = await client.create_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateRestoreTemplateRequest, dict]]): + The request object. Request message for creating a + RestoreTemplate instance. + parent (:class:`str`): + Required. The restore template project and location in + the format 'projects/{project_id}/locations/{location}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_template (:class:`google.cloud.backupdr_v1beta.types.RestoreTemplate`): + Required. A RestoreTemplate resource. + This corresponds to the ``restore_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_template_id (:class:`str`): + Required. The ID of the restore + template to create. The ID must be + unique for the specified project and + location. + + This corresponds to the ``restore_template_id`` 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.backupdr_v1beta.types.RestoreTemplate` A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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, restore_template, restore_template_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, gcb_restore_template.CreateRestoreTemplateRequest): + request = gcb_restore_template.CreateRestoreTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_template is not None: + request.restore_template = restore_template + if restore_template_id is not None: + request.restore_template_id = restore_template_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_restore_template + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcb_restore_template.RestoreTemplate, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_restore_template( + self, + request: Optional[ + Union[restore_template.GetRestoreTemplateRequest, 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]]] = (), + ) -> restore_template.RestoreTemplate: + r"""Gets details of a RestoreTemplate. + + .. 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 backupdr_v1beta + + async def sample_get_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_template(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetRestoreTemplateRequest, dict]]): + The request object. Request message for getting a + RestoreTemplate instance. + name (:class:`str`): + Required. The name of the restore template to retrieve. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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.backupdr_v1beta.types.RestoreTemplate: + A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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, restore_template.GetRestoreTemplateRequest): + request = restore_template.GetRestoreTemplateRequest(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_restore_template + ] + + # 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_restore_templates( + self, + request: Optional[ + Union[restore_template.ListRestoreTemplatesRequest, 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.ListRestoreTemplatesAsyncPager: + r"""Lists RestoreTemplates in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_list_restore_templates(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreTemplatesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_templates(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListRestoreTemplatesRequest, dict]]): + The request object. Request message for listing + RestoreTemplates. + parent (:class:`str`): + Required. The project and location from which to list + the restore templates. Format: + ``projects/{project}/locations/{location}``. + + 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.backupdr_v1beta.services.backup_dr.pagers.ListRestoreTemplatesAsyncPager: + Response message for listing + RestoreTemplates. + 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, restore_template.ListRestoreTemplatesRequest): + request = restore_template.ListRestoreTemplatesRequest(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_restore_templates + ] + + # 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.ListRestoreTemplatesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def update_restore_template( + self, + request: Optional[ + Union[gcb_restore_template.UpdateRestoreTemplateRequest, dict] + ] = None, + *, + restore_template: Optional[gcb_restore_template.RestoreTemplate] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates the settings of a RestoreTemplate. + + .. 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 backupdr_v1beta + + async def sample_update_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_template = backupdr_v1beta.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1beta.UpdateRestoreTemplateRequest( + restore_template=restore_template, + ) + + # Make the request + operation = await client.update_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.UpdateRestoreTemplateRequest, dict]]): + The request object. Request message for updating a + RestoreTemplate instance. + restore_template (:class:`google.cloud.backupdr_v1beta.types.RestoreTemplate`): + Required. The restore template to + update. + + This corresponds to the ``restore_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + Optional. The list of fields to update. Field mask is + used to specify the fields to be overwritten in the + RestoreTemplate resource by the update. The fields + specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. + + This corresponds to the ``update_mask`` 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.backupdr_v1beta.types.RestoreTemplate` A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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 = [restore_template, update_mask] + 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, gcb_restore_template.UpdateRestoreTemplateRequest): + request = gcb_restore_template.UpdateRestoreTemplateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if restore_template is not None: + request.restore_template = restore_template + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_restore_template + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("restore_template.name", request.restore_template.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, + gcb_restore_template.RestoreTemplate, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_restore_template( + self, + request: Optional[ + Union[restore_template.DeleteRestoreTemplateRequest, 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 RestoreTemplate. + + .. 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 backupdr_v1beta + + async def sample_delete_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteRestoreTemplateRequest, dict]]): + The request object. Request message for deleting a + RestoreTemplate instance. + name (:class:`str`): + Required. The name of the restore template to delete. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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, restore_template.DeleteRestoreTemplateRequest): + request = restore_template.DeleteRestoreTemplateRequest(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_restore_template + ] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def run_restore_template( + self, + request: Optional[ + Union[restore_template.RunRestoreTemplateRequest, 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"""Runs a RestoreTemplate. + + .. 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 backupdr_v1beta + + async def sample_run_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.RunRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = await client.run_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.RunRestoreTemplateRequest, dict]]): + The request object. Request message for running a + RestoreTemplate. + name (:class:`str`): + Required. The name of the restore template to run. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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.cloud.backupdr_v1beta.types.RunRestoreTemplateResponse` + Response message for RunRestoreTemplate. + + """ + # 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, restore_template.RunRestoreTemplateRequest): + request = restore_template.RunRestoreTemplateRequest(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.run_restore_template + ] + + # 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, + restore_template.RunRestoreTemplateResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_restore_template_execution( + self, + request: Optional[ + Union[restore_template_execution.GetRestoreTemplateExecutionRequest, 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]]] = (), + ) -> restore_template_execution.RestoreTemplateExecution: + r"""Gets details of a RestoreTemplateExecution. + + .. 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 backupdr_v1beta + + async def sample_get_restore_template_execution(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_template_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetRestoreTemplateExecutionRequest, dict]]): + The request object. Request message for getting a + RestoreTemplateExecution instance. + name (:class:`str`): + Required. The name of the restore template execution to + retrieve. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_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.backupdr_v1beta.types.RestoreTemplateExecution: + A RestoreTemplateExecution represents a single historical or active + execution run. + + """ + # 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, restore_template_execution.GetRestoreTemplateExecutionRequest + ): + request = restore_template_execution.GetRestoreTemplateExecutionRequest( + 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_restore_template_execution + ] + + # 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_restore_template_executions( + self, + request: Optional[ + Union[restore_template_execution.ListRestoreTemplateExecutionsRequest, 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.ListRestoreTemplateExecutionsAsyncPager: + r"""Lists RestoreTemplateExecutions in a given project, + location and restore template. + + .. 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 backupdr_v1beta + + async def sample_list_restore_template_executions(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_template_executions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsRequest, dict]]): + The request object. Request message for listing + RestoreTemplateExecutions. + parent (:class:`str`): + Required. The project, location, and restore template + for which to retrieve executions information. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}``. + + 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.backupdr_v1beta.services.backup_dr.pagers.ListRestoreTemplateExecutionsAsyncPager: + Response message for listing + RestoreTemplateExecutions. + 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, restore_template_execution.ListRestoreTemplateExecutionsRequest + ): + request = restore_template_execution.ListRestoreTemplateExecutionsRequest( + 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_restore_template_executions + ] + + # 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.ListRestoreTemplateExecutionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def trigger_restore_cleanup( + self, + request: Optional[ + Union[restore_template_execution.TriggerRestoreCleanupRequest, 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"""Triggers cleanup of restored resources created during + execution. + + .. 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 backupdr_v1beta + + async def sample_trigger_restore_cleanup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerRestoreCleanupRequest( + name="name_value", + ) + + # Make the request + operation = await client.trigger_restore_cleanup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.TriggerRestoreCleanupRequest, dict]]): + The request object. Request message for triggering a + restore cleanup. + name (:class:`str`): + Required. Name of the restore template execution. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_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.cloud.backupdr_v1beta.types.RestoreTemplateExecution` A RestoreTemplateExecution represents a single historical or active + execution run. + + """ + # 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, restore_template_execution.TriggerRestoreCleanupRequest + ): + request = restore_template_execution.TriggerRestoreCleanupRequest(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.trigger_restore_cleanup + ] + + # 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, + restore_template_execution.RestoreTemplateExecution, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_restore_verification_plan( + self, + request: Optional[ + Union[ + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, dict + ] + ] = None, + *, + parent: Optional[str] = None, + restore_verification_plan: Optional[ + gcb_restore_verification_plan.RestoreVerificationPlan + ] = None, + restore_verification_plan_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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new RestoreVerificationPlan in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + async def sample_create_restore_verification_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_verification_plan = backupdr_v1beta.RestoreVerificationPlan() + restore_verification_plan.schedule = "schedule_value" + + request = backupdr_v1beta.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + restore_verification_plan=restore_verification_plan, + ) + + # Make the request + operation = await client.create_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateRestoreVerificationPlanRequest, dict]]): + The request object. The request message for creating a + ``RestoreVerificationPlan``. + parent (:class:`str`): + Required. The ``RestoreVerificationPlan`` project and + location in the format + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR locations map to Google Cloud + regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan (:class:`google.cloud.backupdr_v1beta.types.RestoreVerificationPlan`): + Required. The ``RestoreVerificationPlan`` resource + object to create. + + This corresponds to the ``restore_verification_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_id (:class:`str`): + Required. The name of the ``RestoreVerificationPlan`` to + create. The name must be unique for the specified + project and location. The name must start with a + lowercase letter followed by up to 62 lowercase letters, + numbers, or hyphens. Pattern, + ``^[a-z]([-a-z0-9]*[a-z0-9])?$``. + + This corresponds to the ``restore_verification_plan_id`` 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.backupdr_v1beta.types.RestoreVerificationPlan` A RestoreVerificationPlan specifies the scheduling and clean-up template + for automated restore verification. It contains a + schedule to dictate when the verifications should + run, and a RestoreVerificationCleanupRule for + post-verification resource deletion. + + """ + # 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, + restore_verification_plan, + restore_verification_plan_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, gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest + ): + request = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_verification_plan is not None: + request.restore_verification_plan = restore_verification_plan + if restore_verification_plan_id is not None: + request.restore_verification_plan_id = restore_verification_plan_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_restore_verification_plan + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcb_restore_verification_plan.RestoreVerificationPlan, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def create_restore_verification_plan_association( + self, + request: Optional[ + Union[ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + restore_verification_plan_association: Optional[ + gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation + ] = None, + restore_verification_plan_association_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]]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new RestoreVerificationPlanAssociation in a + given RestoreVerificationPlan. + + .. 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 backupdr_v1beta + + async def sample_create_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_verification_plan_association = backupdr_v1beta.RestoreVerificationPlanAssociation() + restore_verification_plan_association.restore_template = "restore_template_value" + restore_verification_plan_association.resource_type = "resource_type_value" + + request = backupdr_v1beta.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + restore_verification_plan_association=restore_verification_plan_association, + ) + + # Make the request + operation = await client.create_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateRestoreVerificationPlanAssociationRequest, dict]]): + The request object. Request message for + CreateRestoreVerificationPlanAssociation. + parent (:class:`str`): + Required. The parent resource where this association + will be created. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_association (:class:`google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation`): + Required. The + RestoreVerificationPlanAssociation + resource to create. + + This corresponds to the ``restore_verification_plan_association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_association_id (:class:`str`): + Required. The ID to use for the association, which will + become the final component of the association's resource + name. + + This value should be 1-63 characters, and valid + characters are /[a-z0-9\_-]/. + + This corresponds to the ``restore_verification_plan_association_id`` 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.backupdr_v1beta.types.RestoreVerificationPlanAssociation` A RestoreVerificationPlanAssociation binds a specific workload to a + RestoreVerificationPlan. + + """ + # 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, + restore_verification_plan_association, + restore_verification_plan_association_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, + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + ): + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_verification_plan_association is not None: + request.restore_verification_plan_association = ( + restore_verification_plan_association + ) + if restore_verification_plan_association_id is not None: + request.restore_verification_plan_association_id = ( + restore_verification_plan_association_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_restore_verification_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_restore_verification_plan_association( + self, + request: Optional[ + Union[ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + 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]]] = (), + ) -> restore_verification_plan_association.RestoreVerificationPlanAssociation: + r"""Gets details of a single + RestoreVerificationPlanAssociation in a given + RestoreVerificationPlan. + + .. 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 backupdr_v1beta + + async def sample_get_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_verification_plan_association(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetRestoreVerificationPlanAssociationRequest, dict]]): + The request object. Request message for + GetRestoreVerificationPlanAssociation. + name (:class:`str`): + Required. The resource name of the + RestoreVerificationPlanAssociation to retrieve. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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.backupdr_v1beta.types.RestoreVerificationPlanAssociation: + A RestoreVerificationPlanAssociation binds a specific workload to a + RestoreVerificationPlan. + + """ + # 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, + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + ): + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest( + 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_restore_verification_plan_association + ] + + # 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_restore_verification_plan_associations( + self, + request: Optional[ + Union[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + 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.ListRestoreVerificationPlanAssociationsAsyncPager: + r"""Lists RestoreVerificationPlanAssociations in a given + RestoreVerificationPlan. + + .. 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 backupdr_v1beta + + async def sample_list_restore_verification_plan_associations(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plan_associations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsRequest, dict]]): + The request object. Request message for + ListRestoreVerificationPlanAssociations. + parent (:class:`str`): + Required. The parent RestoreVerificationPlan name. + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + + 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.backupdr_v1beta.services.backup_dr.pagers.ListRestoreVerificationPlanAssociationsAsyncPager: + Response message for + ListRestoreVerificationPlanAssociations. + 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, + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + ): + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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_restore_verification_plan_associations + ] + + # 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.ListRestoreVerificationPlanAssociationsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_restore_verification_plan_association( + self, + request: Optional[ + Union[ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + 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 single RestoreVerificationPlanAssociation + in a given RestoreVerificationPlan. + + .. 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 backupdr_v1beta + + async def sample_delete_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteRestoreVerificationPlanAssociationRequest, dict]]): + The request object. Request message for + DeleteRestoreVerificationPlanAssociation. + name (:class:`str`): + Required. The resource name of the + RestoreVerificationPlanAssociation to delete. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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, + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + ): + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest( + 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_restore_verification_plan_association + ] + + # 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=backupdr.OperationMetadata, + ) - async def list_management_servers( + # Done; return the response. + return response + + async def trigger_restore_verification( self, - request: Optional[Union[backupdr.ListManagementServersRequest, dict]] = None, + request: Optional[ + Union[ + restore_verification_plan_association.TriggerRestoreVerificationRequest, + dict, + ] + ] = None, *, - parent: Optional[str] = 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]]] = (), - ) -> pagers.ListManagementServersAsyncPager: - r"""Lists ManagementServers in a given project and - location. + ) -> operation_async.AsyncOperation: + r"""Triggers a new Restore Verification for the + association in a given RestoreVerificationPlan. .. code-block:: python @@ -397,36 +2924,35 @@ async def list_management_servers( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import backupdr_v1beta - async def sample_list_management_servers(): + async def sample_trigger_restore_verification(): # Create a client client = backupdr_v1beta.BackupDRAsyncClient() # Initialize request argument(s) - request = backupdr_v1beta.ListManagementServersRequest( - parent="parent_value", + request = backupdr_v1beta.TriggerRestoreVerificationRequest( + name="name_value", ) # Make the request - page_result = client.list_management_servers(request=request) + operation = await client.trigger_restore_verification(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() # Handle the response - async for response in page_result: - print(response) + print(response) Args: - request (Optional[Union[google.cloud.backupdr_v1beta.types.ListManagementServersRequest, dict]]): - The request object. Request message for listing - management servers. - parent (:class:`str`): - Required. The project and location for which to retrieve - management servers information, in the format - 'projects/{project_id}/locations/{location}'. In Google - Cloud Backup and DR, locations map to Google Cloud - regions, for example **us-central1**. To retrieve - management servers for all locations, use "-" for the - '{location}' value. + request (Optional[Union[google.cloud.backupdr_v1beta.types.TriggerRestoreVerificationRequest, dict]]): + The request object. Request message for + TriggerRestoreVerification. + name (:class:`str`): + Required. The resource name of the + RestoreVerificationPlanAssociation to trigger. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` - This corresponds to the ``parent`` field + 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, @@ -438,18 +2964,18 @@ async def sample_list_management_servers(): be of type `bytes`. Returns: - google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersAsyncPager: - Response message for listing - management servers. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.TriggerRestoreVerificationResponse` + Response message for TriggerRestoreVerification. """ # 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] + flattened_params = [name] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -461,24 +2987,31 @@ async def sample_list_management_servers(): # - 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, backupdr.ListManagementServersRequest): - request = backupdr.ListManagementServersRequest(request) + if not isinstance( + request, + restore_verification_plan_association.TriggerRestoreVerificationRequest, + ): + request = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest( + request + ) + ) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + 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.list_management_servers + self._client._transport.trigger_restore_verification ] # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -492,30 +3025,30 @@ async def sample_list_management_servers(): metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListManagementServersAsyncPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + restore_verification_plan_association.TriggerRestoreVerificationResponse, + metadata_type=backupdr.OperationMetadata, ) # Done; return the response. return response - async def get_management_server( + async def get_restore_verification_plan( self, - request: Optional[Union[backupdr.GetManagementServerRequest, dict]] = None, + request: Optional[ + Union[restore_verification_plan.GetRestoreVerificationPlanRequest, 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]]] = (), - ) -> backupdr.ManagementServer: - r"""Gets details of a single ManagementServer. + ) -> restore_verification_plan.RestoreVerificationPlan: + r"""Gets details of a single RestoreVerificationPlan. + Returns the requested RestoreVerificationPlan. .. code-block:: python @@ -528,29 +3061,31 @@ async def get_management_server( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import backupdr_v1beta - async def sample_get_management_server(): + async def sample_get_restore_verification_plan(): # Create a client client = backupdr_v1beta.BackupDRAsyncClient() # Initialize request argument(s) - request = backupdr_v1beta.GetManagementServerRequest( + request = backupdr_v1beta.GetRestoreVerificationPlanRequest( name="name_value", ) # Make the request - response = await client.get_management_server(request=request) + response = await client.get_restore_verification_plan(request=request) # Handle the response print(response) Args: - request (Optional[Union[google.cloud.backupdr_v1beta.types.GetManagementServerRequest, dict]]): - The request object. Request message for getting a - management server instance. + request (Optional[Union[google.cloud.backupdr_v1beta.types.GetRestoreVerificationPlanRequest, dict]]): + The request object. The request message for getting a + ``RestoreVerificationPlan``. name (:class:`str`): - Required. Name of the management server resource name, - in the format - 'projects/{project_id}/locations/{location}/managementServers/{resource_name}' + Required. The resource name of the + ``RestoreVerificationPlan`` to retrieve. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -564,9 +3099,12 @@ async def sample_get_management_server(): be of type `bytes`. Returns: - google.cloud.backupdr_v1beta.types.ManagementServer: - ManagementServer describes a single - BackupDR ManagementServer instance. + google.cloud.backupdr_v1beta.types.RestoreVerificationPlan: + A RestoreVerificationPlan specifies the scheduling and clean-up template + for automated restore verification. It contains a + schedule to dictate when the verifications should + run, and a RestoreVerificationCleanupRule for + post-verification resource deletion. """ # Create or coerce a protobuf request object. @@ -584,8 +3122,12 @@ async def sample_get_management_server(): # - 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, backupdr.GetManagementServerRequest): - request = backupdr.GetManagementServerRequest(request) + if not isinstance( + request, restore_verification_plan.GetRestoreVerificationPlanRequest + ): + request = restore_verification_plan.GetRestoreVerificationPlanRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -595,7 +3137,7 @@ async def sample_get_management_server(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.get_management_server + self._client._transport.get_restore_verification_plan ] # Certain fields should be provided within the metadata header; @@ -618,18 +3160,18 @@ async def sample_get_management_server(): # Done; return the response. return response - async def create_management_server( + async def list_restore_verification_plans( self, - request: Optional[Union[backupdr.CreateManagementServerRequest, dict]] = None, + request: Optional[ + Union[restore_verification_plan.ListRestoreVerificationPlansRequest, dict] + ] = None, *, parent: Optional[str] = None, - management_server: Optional[backupdr.ManagementServer] = None, - management_server_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]]] = (), - ) -> operation_async.AsyncOperation: - r"""Creates a new ManagementServer in a given project and + ) -> pagers.ListRestoreVerificationPlansAsyncPager: + r"""Lists RestoreVerificationPlans in a given project and location. .. code-block:: python @@ -643,55 +3185,38 @@ async def create_management_server( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import backupdr_v1beta - async def sample_create_management_server(): + async def sample_list_restore_verification_plans(): # Create a client client = backupdr_v1beta.BackupDRAsyncClient() # Initialize request argument(s) - request = backupdr_v1beta.CreateManagementServerRequest( + request = backupdr_v1beta.ListRestoreVerificationPlansRequest( parent="parent_value", - management_server_id="management_server_id_value", ) # Make the request - operation = await client.create_management_server(request=request) - - print("Waiting for operation to complete...") - - response = await operation.result() + page_result = client.list_restore_verification_plans(request=request) # Handle the response - print(response) + async for response in page_result: + print(response) Args: - request (Optional[Union[google.cloud.backupdr_v1beta.types.CreateManagementServerRequest, dict]]): - The request object. Request message for creating a - management server instance. + request (Optional[Union[google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansRequest, dict]]): + The request object. The request message for getting a list of + ``RestoreVerificationPlans``. parent (:class:`str`): - Required. The management server project and location in - the format 'projects/{project_id}/locations/{location}'. - In Google Cloud Backup and DR locations map to Google - Cloud regions, for example **us-central1**. + Required. The project and location for which to retrieve + ``RestoreVerificationPlans`` information. Format: + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + restore verification plans for all locations, use "-" + for the ``{location}`` value. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - management_server (:class:`google.cloud.backupdr_v1beta.types.ManagementServer`): - Required. A [management server - resource][google.cloud.backupdr.v1.ManagementServer] - - This corresponds to the ``management_server`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - management_server_id (:class:`str`): - Required. The name of the management - server to create. The name must be - unique for the specified project and - location. - - This corresponds to the ``management_server_id`` 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. @@ -701,19 +3226,18 @@ async def sample_create_management_server(): be of type `bytes`. Returns: - google.api_core.operation_async.AsyncOperation: - An object representing a long-running operation. + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreVerificationPlansAsyncPager: + The response message for getting a list of + RestoreVerificationPlans. - The result type for the operation will be - :class:`google.cloud.backupdr_v1beta.types.ManagementServer` - ManagementServer describes a single BackupDR - ManagementServer instance. + 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, management_server, management_server_id] + flattened_params = [parent] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -725,22 +3249,22 @@ async def sample_create_management_server(): # - 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, backupdr.CreateManagementServerRequest): - request = backupdr.CreateManagementServerRequest(request) + if not isinstance( + request, restore_verification_plan.ListRestoreVerificationPlansRequest + ): + request = restore_verification_plan.ListRestoreVerificationPlansRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if management_server is not None: - request.management_server = management_server - if management_server_id is not None: - request.management_server_id = management_server_id # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.create_management_server + self._client._transport.list_restore_verification_plans ] # Certain fields should be provided within the metadata header; @@ -760,27 +3284,34 @@ async def sample_create_management_server(): metadata=metadata, ) - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - backupdr.ManagementServer, - metadata_type=backupdr.OperationMetadata, + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRestoreVerificationPlansAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. return response - async def delete_management_server( + async def delete_restore_verification_plan( self, - request: Optional[Union[backupdr.DeleteManagementServerRequest, dict]] = None, + request: Optional[ + Union[restore_verification_plan.DeleteRestoreVerificationPlanRequest, 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 single ManagementServer. + r"""Deletes a single RestoreVerificationPlan. If the ``force`` flag + is set to ``true``, any RestoreVerificationPlanAssociations + linked to this RestoreVerificationPlan will also be deleted. .. code-block:: python @@ -793,17 +3324,17 @@ async def delete_management_server( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import backupdr_v1beta - async def sample_delete_management_server(): + async def sample_delete_restore_verification_plan(): # Create a client client = backupdr_v1beta.BackupDRAsyncClient() # Initialize request argument(s) - request = backupdr_v1beta.DeleteManagementServerRequest( + request = backupdr_v1beta.DeleteRestoreVerificationPlanRequest( name="name_value", ) # Make the request - operation = await client.delete_management_server(request=request) + operation = await client.delete_restore_verification_plan(request=request) print("Waiting for operation to complete...") @@ -813,11 +3344,16 @@ async def sample_delete_management_server(): print(response) Args: - request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest, dict]]): - The request object. Request message for deleting a - management server instance. + request (Optional[Union[google.cloud.backupdr_v1beta.types.DeleteRestoreVerificationPlanRequest, dict]]): + The request object. The request message for deleting a + ``RestoreVerificationPlan``. name (:class:`str`): - Required. Name of the resource + Required. The resource name of the + ``RestoreVerificationPlan`` to delete. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -860,8 +3396,12 @@ async def sample_delete_management_server(): # - 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, backupdr.DeleteManagementServerRequest): - request = backupdr.DeleteManagementServerRequest(request) + if not isinstance( + request, restore_verification_plan.DeleteRestoreVerificationPlanRequest + ): + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -871,7 +3411,7 @@ async def sample_delete_management_server(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = self._client._transport._wrapped_methods[ - self._client._transport.delete_management_server + self._client._transport.delete_restore_verification_plan ] # Certain fields should be provided within the metadata header; @@ -5365,6 +7905,11 @@ async def sample_create_auto_protection_policy(): policy. This will become the final component of the policy's resource name. + This value must start with a lowercase + letter followed by up to 62 lowercase + letters, numbers, or hyphens, and cannot + end with a hyphen. + This corresponds to the ``auto_protection_policy_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -5766,7 +8311,7 @@ async def sample_update_auto_protection_policy(): on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): - Required. Field mask is used to specify the fields to be + Optional. Field mask is used to specify the fields to be overwritten in the AutoProtectionPolicy resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field @@ -6079,6 +8624,11 @@ async def sample_create_auto_protection_policy_binding(): component of the binding's resource name. + This value must start with a lowercase + letter followed by up to 62 lowercase + letters, numbers, or hyphens, and cannot + end with a hyphen. + This corresponds to the ``auto_protection_policy_binding_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/client.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/client.py index 057a8812394e..f002af5d0a21 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/client.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/client.py @@ -73,6 +73,7 @@ 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.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore @@ -98,6 +99,18 @@ backupvault_gce, bindingmatchingresource, datasourcereference, + restore_template, + restore_template_common, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1beta.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .transports.base import DEFAULT_CLIENT_INFO, BackupDRTransport @@ -530,6 +543,30 @@ def parse_data_source_reference_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def execution_path( + project: str, + location: str, + job: str, + execution: str, + ) -> str: + """Returns a fully-qualified execution string.""" + return "projects/{project}/locations/{location}/jobs/{job}/executions/{execution}".format( + project=project, + location=location, + job=job, + execution=execution, + ) + + @staticmethod + def parse_execution_path(path: str) -> Dict[str, str]: + """Parses a execution path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)/executions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def instance_path( project: str, @@ -547,6 +584,28 @@ def parse_instance_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/instances/(?P.+?)$", path) return m.groupdict() if m else {} + @staticmethod + def job_path( + project: str, + location: str, + job: str, + ) -> str: + """Returns a fully-qualified job string.""" + return "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, + location=location, + job=job, + ) + + @staticmethod + def parse_job_path(path: str) -> Dict[str, str]: + """Parses a job path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/jobs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def management_server_path( project: str, @@ -569,6 +628,98 @@ def parse_management_server_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def restore_template_path( + project: str, + location: str, + restore_template: str, + ) -> str: + """Returns a fully-qualified restore_template string.""" + return "projects/{project}/locations/{location}/restoreTemplates/{restore_template}".format( + project=project, + location=location, + restore_template=restore_template, + ) + + @staticmethod + def parse_restore_template_path(path: str) -> Dict[str, str]: + """Parses a restore_template path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/restoreTemplates/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def restore_template_execution_path( + project: str, + location: str, + restore_template: str, + execution: str, + ) -> str: + """Returns a fully-qualified restore_template_execution string.""" + return "projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}".format( + project=project, + location=location, + restore_template=restore_template, + execution=execution, + ) + + @staticmethod + def parse_restore_template_execution_path(path: str) -> Dict[str, str]: + """Parses a restore_template_execution path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/restoreTemplates/(?P.+?)/executions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def restore_verification_plan_path( + project: str, + location: str, + restoreVerificationPlan: str, + ) -> str: + """Returns a fully-qualified restore_verification_plan string.""" + return "projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}".format( + project=project, + location=location, + restoreVerificationPlan=restoreVerificationPlan, + ) + + @staticmethod + def parse_restore_verification_plan_path(path: str) -> Dict[str, str]: + """Parses a restore_verification_plan path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/restoreVerificationPlans/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def restore_verification_plan_association_path( + project: str, + location: str, + restore_verification_plan: str, + association: str, + ) -> str: + """Returns a fully-qualified restore_verification_plan_association string.""" + return "projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}".format( + project=project, + location=location, + restore_verification_plan=restore_verification_plan, + association=association, + ) + + @staticmethod + def parse_restore_verification_plan_association_path(path: str) -> Dict[str, str]: + """Parses a restore_verification_plan_association path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/restoreVerificationPlans/(?P.+?)/associations/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def storage_pool_path( project: str, @@ -967,40 +1118,2488 @@ def __init__( 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.backupdr_v1beta.BackupDRClient`.", - extra={ - "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "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.backupdr.v1beta.BackupDR", - "credentialsType": None, - }, - ) + 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.backupdr_v1beta.BackupDRClient`.", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "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.backupdr.v1beta.BackupDR", + "credentialsType": None, + }, + ) + + def list_management_servers( + self, + request: Optional[Union[backupdr.ListManagementServersRequest, 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.ListManagementServersPager: + r"""Lists ManagementServers in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_management_servers(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListManagementServersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_management_servers(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListManagementServersRequest, dict]): + The request object. Request message for listing + management servers. + parent (str): + Required. The project and location for which to retrieve + management servers information, in the format + 'projects/{project_id}/locations/{location}'. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + management servers for all locations, use "-" for the + '{location}' value. + + 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.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersPager: + Response message for listing + management servers. + 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, backupdr.ListManagementServersRequest): + request = backupdr.ListManagementServersRequest(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_management_servers] + + # 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.ListManagementServersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_management_server( + self, + request: Optional[Union[backupdr.GetManagementServerRequest, 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]]] = (), + ) -> backupdr.ManagementServer: + r"""Gets details of a single ManagementServer. + + .. 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 backupdr_v1beta + + def sample_get_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetManagementServerRequest( + name="name_value", + ) + + # Make the request + response = client.get_management_server(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetManagementServerRequest, dict]): + The request object. Request message for getting a + management server instance. + name (str): + Required. Name of the management server resource name, + in the format + 'projects/{project_id}/locations/{location}/managementServers/{resource_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.cloud.backupdr_v1beta.types.ManagementServer: + ManagementServer describes a single + BackupDR ManagementServer 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, backupdr.GetManagementServerRequest): + request = backupdr.GetManagementServerRequest(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_management_server] + + # 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_management_server( + self, + request: Optional[Union[backupdr.CreateManagementServerRequest, dict]] = None, + *, + parent: Optional[str] = None, + management_server: Optional[backupdr.ManagementServer] = None, + management_server_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]]] = (), + ) -> operation.Operation: + r"""Creates a new ManagementServer in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_create_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.CreateManagementServerRequest( + parent="parent_value", + management_server_id="management_server_id_value", + ) + + # Make the request + operation = client.create_management_server(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateManagementServerRequest, dict]): + The request object. Request message for creating a + management server instance. + parent (str): + Required. The management server project and location in + the format 'projects/{project_id}/locations/{location}'. + In Google Cloud Backup and DR locations map to Google + Cloud regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + management_server (google.cloud.backupdr_v1beta.types.ManagementServer): + Required. A [management server + resource][google.cloud.backupdr.v1.ManagementServer] + + This corresponds to the ``management_server`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + management_server_id (str): + Required. The name of the management + server to create. The name must be + unique for the specified project and + location. + + This corresponds to the ``management_server_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.ManagementServer` + ManagementServer describes a single BackupDR + ManagementServer 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 = [parent, management_server, management_server_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, backupdr.CreateManagementServerRequest): + request = backupdr.CreateManagementServerRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if management_server is not None: + request.management_server = management_server + if management_server_id is not None: + request.management_server_id = management_server_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_management_server] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + backupdr.ManagementServer, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_management_server( + self, + request: Optional[Union[backupdr.DeleteManagementServerRequest, 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 single ManagementServer. + + .. 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 backupdr_v1beta + + def sample_delete_management_server(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteManagementServerRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_management_server(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest, dict]): + The request object. Request message for deleting a + management server instance. + name (str): + Required. Name of the resource + 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, backupdr.DeleteManagementServerRequest): + request = backupdr.DeleteManagementServerRequest(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_management_server] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_restore_template( + self, + request: Optional[ + Union[gcb_restore_template.CreateRestoreTemplateRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + restore_template: Optional[gcb_restore_template.RestoreTemplate] = None, + restore_template_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]]] = (), + ) -> operation.Operation: + r"""Creates a new RestoreTemplate in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_create_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + restore_template = backupdr_v1beta.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1beta.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + restore_template=restore_template, + ) + + # Make the request + operation = client.create_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateRestoreTemplateRequest, dict]): + The request object. Request message for creating a + RestoreTemplate instance. + parent (str): + Required. The restore template project and location in + the format 'projects/{project_id}/locations/{location}'. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_template (google.cloud.backupdr_v1beta.types.RestoreTemplate): + Required. A RestoreTemplate resource. + This corresponds to the ``restore_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_template_id (str): + Required. The ID of the restore + template to create. The ID must be + unique for the specified project and + location. + + This corresponds to the ``restore_template_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.RestoreTemplate` A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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, restore_template, restore_template_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, gcb_restore_template.CreateRestoreTemplateRequest): + request = gcb_restore_template.CreateRestoreTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_template is not None: + request.restore_template = restore_template + if restore_template_id is not None: + request.restore_template_id = restore_template_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_restore_template] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcb_restore_template.RestoreTemplate, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_restore_template( + self, + request: Optional[ + Union[restore_template.GetRestoreTemplateRequest, 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]]] = (), + ) -> restore_template.RestoreTemplate: + r"""Gets details of a RestoreTemplate. + + .. 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 backupdr_v1beta + + def sample_get_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_template(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetRestoreTemplateRequest, dict]): + The request object. Request message for getting a + RestoreTemplate instance. + name (str): + Required. The name of the restore template to retrieve. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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.backupdr_v1beta.types.RestoreTemplate: + A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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, restore_template.GetRestoreTemplateRequest): + request = restore_template.GetRestoreTemplateRequest(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_restore_template] + + # 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_restore_templates( + self, + request: Optional[ + Union[restore_template.ListRestoreTemplatesRequest, 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.ListRestoreTemplatesPager: + r"""Lists RestoreTemplates in a given project and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_list_restore_templates(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreTemplatesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_templates(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListRestoreTemplatesRequest, dict]): + The request object. Request message for listing + RestoreTemplates. + parent (str): + Required. The project and location from which to list + the restore templates. Format: + ``projects/{project}/locations/{location}``. + + 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.backupdr_v1beta.services.backup_dr.pagers.ListRestoreTemplatesPager: + Response message for listing + RestoreTemplates. + 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, restore_template.ListRestoreTemplatesRequest): + request = restore_template.ListRestoreTemplatesRequest(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_restore_templates] + + # 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.ListRestoreTemplatesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def update_restore_template( + self, + request: Optional[ + Union[gcb_restore_template.UpdateRestoreTemplateRequest, dict] + ] = None, + *, + restore_template: Optional[gcb_restore_template.RestoreTemplate] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = 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"""Updates the settings of a RestoreTemplate. + + .. 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 backupdr_v1beta + + def sample_update_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + restore_template = backupdr_v1beta.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1beta.UpdateRestoreTemplateRequest( + restore_template=restore_template, + ) + + # Make the request + operation = client.update_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.UpdateRestoreTemplateRequest, dict]): + The request object. Request message for updating a + RestoreTemplate instance. + restore_template (google.cloud.backupdr_v1beta.types.RestoreTemplate): + Required. The restore template to + update. + + This corresponds to the ``restore_template`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. Field mask is + used to specify the fields to be overwritten in the + RestoreTemplate resource by the update. The fields + specified in the update_mask are relative to the + resource, not the full request. A field will be + overwritten if it is in the mask. + + This corresponds to the ``update_mask`` 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.backupdr_v1beta.types.RestoreTemplate` A RestoreTemplate encapsulates DR readiness configurations for validating + backups. + + """ + # 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 = [restore_template, update_mask] + 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, gcb_restore_template.UpdateRestoreTemplateRequest): + request = gcb_restore_template.UpdateRestoreTemplateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if restore_template is not None: + request.restore_template = restore_template + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_restore_template] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("restore_template.name", request.restore_template.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, + gcb_restore_template.RestoreTemplate, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_restore_template( + self, + request: Optional[ + Union[restore_template.DeleteRestoreTemplateRequest, 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 RestoreTemplate. + + .. 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 backupdr_v1beta + + def sample_delete_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.DeleteRestoreTemplateRequest, dict]): + The request object. Request message for deleting a + RestoreTemplate instance. + name (str): + Required. The name of the restore template to delete. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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, restore_template.DeleteRestoreTemplateRequest): + request = restore_template.DeleteRestoreTemplateRequest(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_restore_template] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def run_restore_template( + self, + request: Optional[ + Union[restore_template.RunRestoreTemplateRequest, 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"""Runs a RestoreTemplate. + + .. 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 backupdr_v1beta + + def sample_run_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.RunRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = client.run_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.RunRestoreTemplateRequest, dict]): + The request object. Request message for running a + RestoreTemplate. + name (str): + Required. The name of the restore template to run. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_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.cloud.backupdr_v1beta.types.RunRestoreTemplateResponse` + Response message for RunRestoreTemplate. + + """ + # 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, restore_template.RunRestoreTemplateRequest): + request = restore_template.RunRestoreTemplateRequest(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.run_restore_template] + + # 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, + restore_template.RunRestoreTemplateResponse, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_restore_template_execution( + self, + request: Optional[ + Union[restore_template_execution.GetRestoreTemplateExecutionRequest, 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]]] = (), + ) -> restore_template_execution.RestoreTemplateExecution: + r"""Gets details of a RestoreTemplateExecution. + + .. 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 backupdr_v1beta + + def sample_get_restore_template_execution(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_template_execution(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetRestoreTemplateExecutionRequest, dict]): + The request object. Request message for getting a + RestoreTemplateExecution instance. + name (str): + Required. The name of the restore template execution to + retrieve. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_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.backupdr_v1beta.types.RestoreTemplateExecution: + A RestoreTemplateExecution represents a single historical or active + execution run. + + """ + # 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, restore_template_execution.GetRestoreTemplateExecutionRequest + ): + request = restore_template_execution.GetRestoreTemplateExecutionRequest( + 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_restore_template_execution + ] + + # 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_restore_template_executions( + self, + request: Optional[ + Union[restore_template_execution.ListRestoreTemplateExecutionsRequest, 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.ListRestoreTemplateExecutionsPager: + r"""Lists RestoreTemplateExecutions in a given project, + location and restore template. + + .. 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 backupdr_v1beta + + def sample_list_restore_template_executions(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_template_executions(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsRequest, dict]): + The request object. Request message for listing + RestoreTemplateExecutions. + parent (str): + Required. The project, location, and restore template + for which to retrieve executions information. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}``. + + 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.backupdr_v1beta.services.backup_dr.pagers.ListRestoreTemplateExecutionsPager: + Response message for listing + RestoreTemplateExecutions. + 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, restore_template_execution.ListRestoreTemplateExecutionsRequest + ): + request = restore_template_execution.ListRestoreTemplateExecutionsRequest( + 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_restore_template_executions + ] + + # 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.ListRestoreTemplateExecutionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def trigger_restore_cleanup( + self, + request: Optional[ + Union[restore_template_execution.TriggerRestoreCleanupRequest, 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"""Triggers cleanup of restored resources created during + execution. + + .. 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 backupdr_v1beta + + def sample_trigger_restore_cleanup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerRestoreCleanupRequest( + name="name_value", + ) + + # Make the request + operation = client.trigger_restore_cleanup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.TriggerRestoreCleanupRequest, dict]): + The request object. Request message for triggering a + restore cleanup. + name (str): + Required. Name of the restore template execution. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_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.cloud.backupdr_v1beta.types.RestoreTemplateExecution` A RestoreTemplateExecution represents a single historical or active + execution run. + + """ + # 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, restore_template_execution.TriggerRestoreCleanupRequest + ): + request = restore_template_execution.TriggerRestoreCleanupRequest(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.trigger_restore_cleanup] + + # 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, + restore_template_execution.RestoreTemplateExecution, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_restore_verification_plan( + self, + request: Optional[ + Union[ + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, dict + ] + ] = None, + *, + parent: Optional[str] = None, + restore_verification_plan: Optional[ + gcb_restore_verification_plan.RestoreVerificationPlan + ] = None, + restore_verification_plan_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]]] = (), + ) -> operation.Operation: + r"""Creates a new RestoreVerificationPlan in a given + project and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import backupdr_v1beta + + def sample_create_restore_verification_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + restore_verification_plan = backupdr_v1beta.RestoreVerificationPlan() + restore_verification_plan.schedule = "schedule_value" + + request = backupdr_v1beta.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + restore_verification_plan=restore_verification_plan, + ) + + # Make the request + operation = client.create_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateRestoreVerificationPlanRequest, dict]): + The request object. The request message for creating a + ``RestoreVerificationPlan``. + parent (str): + Required. The ``RestoreVerificationPlan`` project and + location in the format + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR locations map to Google Cloud + regions, for example **us-central1**. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan (google.cloud.backupdr_v1beta.types.RestoreVerificationPlan): + Required. The ``RestoreVerificationPlan`` resource + object to create. + + This corresponds to the ``restore_verification_plan`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_id (str): + Required. The name of the ``RestoreVerificationPlan`` to + create. The name must be unique for the specified + project and location. The name must start with a + lowercase letter followed by up to 62 lowercase letters, + numbers, or hyphens. Pattern, + ``^[a-z]([-a-z0-9]*[a-z0-9])?$``. + + This corresponds to the ``restore_verification_plan_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.RestoreVerificationPlan` A RestoreVerificationPlan specifies the scheduling and clean-up template + for automated restore verification. It contains a + schedule to dictate when the verifications should + run, and a RestoreVerificationCleanupRule for + post-verification resource deletion. + + """ + # 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, + restore_verification_plan, + restore_verification_plan_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, gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest + ): + request = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_verification_plan is not None: + request.restore_verification_plan = restore_verification_plan + if restore_verification_plan_id is not None: + request.restore_verification_plan_id = restore_verification_plan_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_restore_verification_plan + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcb_restore_verification_plan.RestoreVerificationPlan, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def create_restore_verification_plan_association( + self, + request: Optional[ + Union[ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + dict, + ] + ] = None, + *, + parent: Optional[str] = None, + restore_verification_plan_association: Optional[ + gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation + ] = None, + restore_verification_plan_association_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]]] = (), + ) -> operation.Operation: + r"""Creates a new RestoreVerificationPlanAssociation in a + given RestoreVerificationPlan. + + .. 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 backupdr_v1beta + + def sample_create_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + restore_verification_plan_association = backupdr_v1beta.RestoreVerificationPlanAssociation() + restore_verification_plan_association.restore_template = "restore_template_value" + restore_verification_plan_association.resource_type = "resource_type_value" + + request = backupdr_v1beta.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + restore_verification_plan_association=restore_verification_plan_association, + ) + + # Make the request + operation = client.create_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.CreateRestoreVerificationPlanAssociationRequest, dict]): + The request object. Request message for + CreateRestoreVerificationPlanAssociation. + parent (str): + Required. The parent resource where this association + will be created. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_association (google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation): + Required. The + RestoreVerificationPlanAssociation + resource to create. + + This corresponds to the ``restore_verification_plan_association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + restore_verification_plan_association_id (str): + Required. The ID to use for the association, which will + become the final component of the association's resource + name. + + This value should be 1-63 characters, and valid + characters are /[a-z0-9\_-]/. + + This corresponds to the ``restore_verification_plan_association_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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation` A RestoreVerificationPlanAssociation binds a specific workload to a + RestoreVerificationPlan. + + """ + # 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, + restore_verification_plan_association, + restore_verification_plan_association_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, + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + ): + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if restore_verification_plan_association is not None: + request.restore_verification_plan_association = ( + restore_verification_plan_association + ) + if restore_verification_plan_association_id is not None: + request.restore_verification_plan_association_id = ( + restore_verification_plan_association_id + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_restore_verification_plan_association + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation, + metadata_type=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_restore_verification_plan_association( + self, + request: Optional[ + Union[ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + 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]]] = (), + ) -> restore_verification_plan_association.RestoreVerificationPlanAssociation: + r"""Gets details of a single + RestoreVerificationPlanAssociation in a given + RestoreVerificationPlan. + + .. 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 backupdr_v1beta + + def sample_get_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_verification_plan_association(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.GetRestoreVerificationPlanAssociationRequest, dict]): + The request object. Request message for + GetRestoreVerificationPlanAssociation. + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to retrieve. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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.backupdr_v1beta.types.RestoreVerificationPlanAssociation: + A RestoreVerificationPlanAssociation binds a specific workload to a + RestoreVerificationPlan. + + """ + # 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, + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + ): + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest( + 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_restore_verification_plan_association + ] + + # 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_restore_verification_plan_associations( + self, + request: Optional[ + Union[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + 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.ListRestoreVerificationPlanAssociationsPager: + r"""Lists RestoreVerificationPlanAssociations in a given + RestoreVerificationPlan. + + .. 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 backupdr_v1beta + + def sample_list_restore_verification_plan_associations(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plan_associations(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsRequest, dict]): + The request object. Request message for + ListRestoreVerificationPlanAssociations. + parent (str): + Required. The parent RestoreVerificationPlan name. + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + + 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.backupdr_v1beta.services.backup_dr.pagers.ListRestoreVerificationPlanAssociationsPager: + Response message for + ListRestoreVerificationPlanAssociations. + 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, + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + ): + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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_restore_verification_plan_associations + ] + + # 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.ListRestoreVerificationPlanAssociationsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_restore_verification_plan_association( + self, + request: Optional[ + Union[ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + 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 single RestoreVerificationPlanAssociation + in a given RestoreVerificationPlan. + + .. 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 backupdr_v1beta + + def sample_delete_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.backupdr_v1beta.types.DeleteRestoreVerificationPlanAssociationRequest, dict]): + The request object. Request message for + DeleteRestoreVerificationPlanAssociation. + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to delete. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + + 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, + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + ): + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest( + 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_restore_verification_plan_association + ] + + # 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=backupdr.OperationMetadata, + ) + + # Done; return the response. + return response - def list_management_servers( + def trigger_restore_verification( self, - request: Optional[Union[backupdr.ListManagementServersRequest, dict]] = None, + request: Optional[ + Union[ + restore_verification_plan_association.TriggerRestoreVerificationRequest, + dict, + ] + ] = None, *, - parent: Optional[str] = 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]]] = (), - ) -> pagers.ListManagementServersPager: - r"""Lists ManagementServers in a given project and - location. + ) -> operation.Operation: + r"""Triggers a new Restore Verification for the + association in a given RestoreVerificationPlan. .. code-block:: python @@ -1013,36 +3612,35 @@ def list_management_servers( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import backupdr_v1beta - def sample_list_management_servers(): + def sample_trigger_restore_verification(): # Create a client client = backupdr_v1beta.BackupDRClient() # Initialize request argument(s) - request = backupdr_v1beta.ListManagementServersRequest( - parent="parent_value", + request = backupdr_v1beta.TriggerRestoreVerificationRequest( + name="name_value", ) # Make the request - page_result = client.list_management_servers(request=request) + operation = client.trigger_restore_verification(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() # Handle the response - for response in page_result: - print(response) + print(response) Args: - request (Union[google.cloud.backupdr_v1beta.types.ListManagementServersRequest, dict]): - The request object. Request message for listing - management servers. - parent (str): - Required. The project and location for which to retrieve - management servers information, in the format - 'projects/{project_id}/locations/{location}'. In Google - Cloud Backup and DR, locations map to Google Cloud - regions, for example **us-central1**. To retrieve - management servers for all locations, use "-" for the - '{location}' value. + request (Union[google.cloud.backupdr_v1beta.types.TriggerRestoreVerificationRequest, dict]): + The request object. Request message for + TriggerRestoreVerification. + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to trigger. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` - This corresponds to the ``parent`` field + 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, @@ -1054,18 +3652,18 @@ def sample_list_management_servers(): be of type `bytes`. Returns: - google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersPager: - Response message for listing - management servers. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.backupdr_v1beta.types.TriggerRestoreVerificationResponse` + Response message for TriggerRestoreVerification. """ # 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] + flattened_params = [name] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -1077,21 +3675,30 @@ def sample_list_management_servers(): # - 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, backupdr.ListManagementServersRequest): - request = backupdr.ListManagementServersRequest(request) + if not isinstance( + request, + restore_verification_plan_association.TriggerRestoreVerificationRequest, + ): + request = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest( + request + ) + ) # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: - request.parent = parent + 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.list_management_servers] + rpc = self._transport._wrapped_methods[ + self._transport.trigger_restore_verification + ] # 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),)), + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), ) # Validate the universe domain. @@ -1105,30 +3712,30 @@ def sample_list_management_servers(): metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListManagementServersPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + restore_verification_plan_association.TriggerRestoreVerificationResponse, + metadata_type=backupdr.OperationMetadata, ) # Done; return the response. return response - def get_management_server( + def get_restore_verification_plan( self, - request: Optional[Union[backupdr.GetManagementServerRequest, dict]] = None, + request: Optional[ + Union[restore_verification_plan.GetRestoreVerificationPlanRequest, 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]]] = (), - ) -> backupdr.ManagementServer: - r"""Gets details of a single ManagementServer. + ) -> restore_verification_plan.RestoreVerificationPlan: + r"""Gets details of a single RestoreVerificationPlan. + Returns the requested RestoreVerificationPlan. .. code-block:: python @@ -1141,29 +3748,31 @@ def get_management_server( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import backupdr_v1beta - def sample_get_management_server(): + def sample_get_restore_verification_plan(): # Create a client client = backupdr_v1beta.BackupDRClient() # Initialize request argument(s) - request = backupdr_v1beta.GetManagementServerRequest( + request = backupdr_v1beta.GetRestoreVerificationPlanRequest( name="name_value", ) # Make the request - response = client.get_management_server(request=request) + response = client.get_restore_verification_plan(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.backupdr_v1beta.types.GetManagementServerRequest, dict]): - The request object. Request message for getting a - management server instance. + request (Union[google.cloud.backupdr_v1beta.types.GetRestoreVerificationPlanRequest, dict]): + The request object. The request message for getting a + ``RestoreVerificationPlan``. name (str): - Required. Name of the management server resource name, - in the format - 'projects/{project_id}/locations/{location}/managementServers/{resource_name}' + Required. The resource name of the + ``RestoreVerificationPlan`` to retrieve. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this @@ -1177,9 +3786,12 @@ def sample_get_management_server(): be of type `bytes`. Returns: - google.cloud.backupdr_v1beta.types.ManagementServer: - ManagementServer describes a single - BackupDR ManagementServer instance. + google.cloud.backupdr_v1beta.types.RestoreVerificationPlan: + A RestoreVerificationPlan specifies the scheduling and clean-up template + for automated restore verification. It contains a + schedule to dictate when the verifications should + run, and a RestoreVerificationCleanupRule for + post-verification resource deletion. """ # Create or coerce a protobuf request object. @@ -1197,8 +3809,12 @@ def sample_get_management_server(): # - 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, backupdr.GetManagementServerRequest): - request = backupdr.GetManagementServerRequest(request) + if not isinstance( + request, restore_verification_plan.GetRestoreVerificationPlanRequest + ): + request = restore_verification_plan.GetRestoreVerificationPlanRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -1206,7 +3822,9 @@ def sample_get_management_server(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_management_server] + rpc = self._transport._wrapped_methods[ + self._transport.get_restore_verification_plan + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1228,18 +3846,18 @@ def sample_get_management_server(): # Done; return the response. return response - def create_management_server( + def list_restore_verification_plans( self, - request: Optional[Union[backupdr.CreateManagementServerRequest, dict]] = None, + request: Optional[ + Union[restore_verification_plan.ListRestoreVerificationPlansRequest, dict] + ] = None, *, parent: Optional[str] = None, - management_server: Optional[backupdr.ManagementServer] = None, - management_server_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]]] = (), - ) -> operation.Operation: - r"""Creates a new ManagementServer in a given project and + ) -> pagers.ListRestoreVerificationPlansPager: + r"""Lists RestoreVerificationPlans in a given project and location. .. code-block:: python @@ -1253,55 +3871,38 @@ def create_management_server( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import backupdr_v1beta - def sample_create_management_server(): + def sample_list_restore_verification_plans(): # Create a client client = backupdr_v1beta.BackupDRClient() # Initialize request argument(s) - request = backupdr_v1beta.CreateManagementServerRequest( + request = backupdr_v1beta.ListRestoreVerificationPlansRequest( parent="parent_value", - management_server_id="management_server_id_value", ) # Make the request - operation = client.create_management_server(request=request) - - print("Waiting for operation to complete...") - - response = operation.result() + page_result = client.list_restore_verification_plans(request=request) # Handle the response - print(response) + for response in page_result: + print(response) Args: - request (Union[google.cloud.backupdr_v1beta.types.CreateManagementServerRequest, dict]): - The request object. Request message for creating a - management server instance. + request (Union[google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansRequest, dict]): + The request object. The request message for getting a list of + ``RestoreVerificationPlans``. parent (str): - Required. The management server project and location in - the format 'projects/{project_id}/locations/{location}'. - In Google Cloud Backup and DR locations map to Google - Cloud regions, for example **us-central1**. + Required. The project and location for which to retrieve + ``RestoreVerificationPlans`` information. Format: + ``projects/{project}/locations/{location}``. In Google + Cloud Backup and DR, locations map to Google Cloud + regions, for example **us-central1**. To retrieve + restore verification plans for all locations, use "-" + for the ``{location}`` value. This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - management_server (google.cloud.backupdr_v1beta.types.ManagementServer): - Required. A [management server - resource][google.cloud.backupdr.v1.ManagementServer] - - This corresponds to the ``management_server`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - management_server_id (str): - Required. The name of the management - server to create. The name must be - unique for the specified project and - location. - - This corresponds to the ``management_server_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. @@ -1311,19 +3912,18 @@ def sample_create_management_server(): be of type `bytes`. Returns: - google.api_core.operation.Operation: - An object representing a long-running operation. + google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreVerificationPlansPager: + The response message for getting a list of + RestoreVerificationPlans. - The result type for the operation will be - :class:`google.cloud.backupdr_v1beta.types.ManagementServer` - ManagementServer describes a single BackupDR - ManagementServer instance. + 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, management_server, management_server_id] + flattened_params = [parent] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -1335,20 +3935,22 @@ def sample_create_management_server(): # - 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, backupdr.CreateManagementServerRequest): - request = backupdr.CreateManagementServerRequest(request) + if not isinstance( + request, restore_verification_plan.ListRestoreVerificationPlansRequest + ): + request = restore_verification_plan.ListRestoreVerificationPlansRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. if parent is not None: request.parent = parent - if management_server is not None: - request.management_server = management_server - if management_server_id is not None: - request.management_server_id = management_server_id # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_management_server] + rpc = self._transport._wrapped_methods[ + self._transport.list_restore_verification_plans + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1367,27 +3969,34 @@ def sample_create_management_server(): metadata=metadata, ) - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - backupdr.ManagementServer, - metadata_type=backupdr.OperationMetadata, + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRestoreVerificationPlansPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, ) # Done; return the response. return response - def delete_management_server( + def delete_restore_verification_plan( self, - request: Optional[Union[backupdr.DeleteManagementServerRequest, dict]] = None, + request: Optional[ + Union[restore_verification_plan.DeleteRestoreVerificationPlanRequest, 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 single ManagementServer. + r"""Deletes a single RestoreVerificationPlan. If the ``force`` flag + is set to ``true``, any RestoreVerificationPlanAssociations + linked to this RestoreVerificationPlan will also be deleted. .. code-block:: python @@ -1400,17 +4009,17 @@ def delete_management_server( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import backupdr_v1beta - def sample_delete_management_server(): + def sample_delete_restore_verification_plan(): # Create a client client = backupdr_v1beta.BackupDRClient() # Initialize request argument(s) - request = backupdr_v1beta.DeleteManagementServerRequest( + request = backupdr_v1beta.DeleteRestoreVerificationPlanRequest( name="name_value", ) # Make the request - operation = client.delete_management_server(request=request) + operation = client.delete_restore_verification_plan(request=request) print("Waiting for operation to complete...") @@ -1420,11 +4029,16 @@ def sample_delete_management_server(): print(response) Args: - request (Union[google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest, dict]): - The request object. Request message for deleting a - management server instance. + request (Union[google.cloud.backupdr_v1beta.types.DeleteRestoreVerificationPlanRequest, dict]): + The request object. The request message for deleting a + ``RestoreVerificationPlan``. name (str): - Required. Name of the resource + Required. The resource name of the + ``RestoreVerificationPlan`` to delete. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -1467,8 +4081,12 @@ def sample_delete_management_server(): # - 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, backupdr.DeleteManagementServerRequest): - request = backupdr.DeleteManagementServerRequest(request) + if not isinstance( + request, restore_verification_plan.DeleteRestoreVerificationPlanRequest + ): + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest( + request + ) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: @@ -1476,7 +4094,9 @@ def sample_delete_management_server(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_management_server] + rpc = self._transport._wrapped_methods[ + self._transport.delete_restore_verification_plan + ] # Certain fields should be provided within the metadata header; # add these here. @@ -5895,6 +8515,11 @@ def sample_create_auto_protection_policy(): policy. This will become the final component of the policy's resource name. + This value must start with a lowercase + letter followed by up to 62 lowercase + letters, numbers, or hyphens, and cannot + end with a hyphen. + This corresponds to the ``auto_protection_policy_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -6293,7 +8918,7 @@ def sample_update_auto_protection_policy(): on the ``request`` instance; if ``request`` is provided, this should not be set. update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Field mask is used to specify the fields to be + Optional. Field mask is used to specify the fields to be overwritten in the AutoProtectionPolicy resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field @@ -6604,6 +9229,11 @@ def sample_create_auto_protection_policy_binding(): component of the binding's resource name. + This value must start with a lowercase + letter followed by up to 62 lowercase + letters, numbers, or hyphens, and cannot + end with a hyphen. + This corresponds to the ``auto_protection_policy_binding_id`` field on the ``request`` instance; if ``request`` is provided, this should not be set. diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/pagers.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/pagers.py index cb5b304189cd..09cb1ce6df82 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/pagers.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/pagers.py @@ -48,6 +48,10 @@ backupvault, bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, ) @@ -207,6 +211,692 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListRestoreTemplatesPager: + """A pager for iterating through ``list_restore_templates`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListRestoreTemplatesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``restore_templates`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRestoreTemplates`` requests and continue to iterate + through the ``restore_templates`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListRestoreTemplatesResponse` + 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[..., restore_template.ListRestoreTemplatesResponse], + request: restore_template.ListRestoreTemplatesRequest, + response: restore_template.ListRestoreTemplatesResponse, + *, + 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.backupdr_v1beta.types.ListRestoreTemplatesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListRestoreTemplatesResponse): + 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 = restore_template.ListRestoreTemplatesRequest(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[restore_template.ListRestoreTemplatesResponse]: + 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[restore_template.RestoreTemplate]: + for page in self.pages: + yield from page.restore_templates + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreTemplatesAsyncPager: + """A pager for iterating through ``list_restore_templates`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListRestoreTemplatesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``restore_templates`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRestoreTemplates`` requests and continue to iterate + through the ``restore_templates`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListRestoreTemplatesResponse` + 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[restore_template.ListRestoreTemplatesResponse]], + request: restore_template.ListRestoreTemplatesRequest, + response: restore_template.ListRestoreTemplatesResponse, + *, + 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.backupdr_v1beta.types.ListRestoreTemplatesRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListRestoreTemplatesResponse): + 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 = restore_template.ListRestoreTemplatesRequest(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[restore_template.ListRestoreTemplatesResponse]: + 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[restore_template.RestoreTemplate]: + async def async_generator(): + async for page in self.pages: + for response in page.restore_templates: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreTemplateExecutionsPager: + """A pager for iterating through ``list_restore_template_executions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``restore_template_executions`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRestoreTemplateExecutions`` requests and continue to iterate + through the ``restore_template_executions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsResponse` + 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[ + ..., restore_template_execution.ListRestoreTemplateExecutionsResponse + ], + request: restore_template_execution.ListRestoreTemplateExecutionsRequest, + response: restore_template_execution.ListRestoreTemplateExecutionsResponse, + *, + 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.backupdr_v1beta.types.ListRestoreTemplateExecutionsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsResponse): + 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest( + 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[restore_template_execution.ListRestoreTemplateExecutionsResponse]: + 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[restore_template_execution.RestoreTemplateExecution]: + for page in self.pages: + yield from page.restore_template_executions + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreTemplateExecutionsAsyncPager: + """A pager for iterating through ``list_restore_template_executions`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``restore_template_executions`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRestoreTemplateExecutions`` requests and continue to iterate + through the ``restore_template_executions`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsResponse` + 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[restore_template_execution.ListRestoreTemplateExecutionsResponse], + ], + request: restore_template_execution.ListRestoreTemplateExecutionsRequest, + response: restore_template_execution.ListRestoreTemplateExecutionsResponse, + *, + 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.backupdr_v1beta.types.ListRestoreTemplateExecutionsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsResponse): + 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest( + 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[ + restore_template_execution.ListRestoreTemplateExecutionsResponse + ]: + 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[restore_template_execution.RestoreTemplateExecution]: + async def async_generator(): + async for page in self.pages: + for response in page.restore_template_executions: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreVerificationPlanAssociationsPager: + """A pager for iterating through ``list_restore_verification_plan_associations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``restore_verification_plan_associations`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRestoreVerificationPlanAssociations`` requests and continue to iterate + through the ``restore_verification_plan_associations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsResponse` + 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[ + ..., + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + ], + request: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + response: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + *, + 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.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsResponse): + 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ]: + 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[ + restore_verification_plan_association.RestoreVerificationPlanAssociation + ]: + for page in self.pages: + yield from page.restore_verification_plan_associations + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreVerificationPlanAssociationsAsyncPager: + """A pager for iterating through ``list_restore_verification_plan_associations`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``restore_verification_plan_associations`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRestoreVerificationPlanAssociations`` requests and continue to iterate + through the ``restore_verification_plan_associations`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsResponse` + 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[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ], + ], + request: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + response: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + *, + 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.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsResponse): + 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ]: + 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[ + restore_verification_plan_association.RestoreVerificationPlanAssociation + ]: + async def async_generator(): + async for page in self.pages: + for response in page.restore_verification_plan_associations: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreVerificationPlansPager: + """A pager for iterating through ``list_restore_verification_plans`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansResponse` object, and + provides an ``__iter__`` method to iterate through its + ``restore_verification_plans`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRestoreVerificationPlans`` requests and continue to iterate + through the ``restore_verification_plans`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansResponse` + 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[ + ..., restore_verification_plan.ListRestoreVerificationPlansResponse + ], + request: restore_verification_plan.ListRestoreVerificationPlansRequest, + response: restore_verification_plan.ListRestoreVerificationPlansResponse, + *, + 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.backupdr_v1beta.types.ListRestoreVerificationPlansRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansResponse): + 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 = restore_verification_plan.ListRestoreVerificationPlansRequest( + 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[restore_verification_plan.ListRestoreVerificationPlansResponse]: + 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[restore_verification_plan.RestoreVerificationPlan]: + for page in self.pages: + yield from page.restore_verification_plans + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRestoreVerificationPlansAsyncPager: + """A pager for iterating through ``list_restore_verification_plans`` requests. + + This class thinly wraps an initial + :class:`google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``restore_verification_plans`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRestoreVerificationPlans`` requests and continue to iterate + through the ``restore_verification_plans`` field on the + corresponding responses. + + All the usual :class:`google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansResponse` + 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[restore_verification_plan.ListRestoreVerificationPlansResponse], + ], + request: restore_verification_plan.ListRestoreVerificationPlansRequest, + response: restore_verification_plan.ListRestoreVerificationPlansResponse, + *, + 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.backupdr_v1beta.types.ListRestoreVerificationPlansRequest): + The initial request object. + response (google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansResponse): + 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 = restore_verification_plan.ListRestoreVerificationPlansRequest( + 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[restore_verification_plan.ListRestoreVerificationPlansResponse]: + 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[restore_verification_plan.RestoreVerificationPlan]: + async def async_generator(): + async for page in self.pages: + for response in page.restore_verification_plans: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListBackupVaultsPager: """A pager for iterating through ``list_backup_vaults`` requests. diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/base.py index 09ef74bf20a5..caac3d257008 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/base.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/base.py @@ -42,6 +42,17 @@ backupvault, bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1beta.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -197,6 +208,168 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.create_restore_template: gapic_v1.method.wrap_method( + self.create_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_template: gapic_v1.method.wrap_method( + self.get_restore_template, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_templates: gapic_v1.method.wrap_method( + self.list_restore_templates, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_restore_template: gapic_v1.method.wrap_method( + self.update_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_template: gapic_v1.method.wrap_method( + self.delete_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.run_restore_template: gapic_v1.method.wrap_method( + self.run_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_template_execution: gapic_v1.method.wrap_method( + self.get_restore_template_execution, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_template_executions: gapic_v1.method.wrap_method( + self.list_restore_template_executions, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.trigger_restore_cleanup: gapic_v1.method.wrap_method( + self.trigger_restore_cleanup, + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_verification_plan: gapic_v1.method.wrap_method( + self.create_restore_verification_plan, + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_verification_plan_association: gapic_v1.method.wrap_method( + self.create_restore_verification_plan_association, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_verification_plan_association: gapic_v1.method.wrap_method( + self.get_restore_verification_plan_association, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_verification_plan_associations: gapic_v1.method.wrap_method( + self.list_restore_verification_plan_associations, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_verification_plan_association: gapic_v1.method.wrap_method( + self.delete_restore_verification_plan_association, + default_timeout=60.0, + client_info=client_info, + ), + self.trigger_restore_verification: gapic_v1.method.wrap_method( + self.trigger_restore_verification, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_verification_plan: gapic_v1.method.wrap_method( + self.get_restore_verification_plan, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_verification_plans: gapic_v1.method.wrap_method( + self.list_restore_verification_plans, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_verification_plan: gapic_v1.method.wrap_method( + self.delete_restore_verification_plan, + default_timeout=60.0, + client_info=client_info, + ), self.create_backup_vault: gapic_v1.method.wrap_method( self.create_backup_vault, default_retry=retries.Retry( @@ -454,52 +627,97 @@ def _prep_wrapped_messages(self, client_info): ), self.create_auto_protection_policy: gapic_v1.method.wrap_method( self.create_auto_protection_policy, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.list_auto_protection_policies: gapic_v1.method.wrap_method( self.list_auto_protection_policies, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_auto_protection_policy: gapic_v1.method.wrap_method( self.get_auto_protection_policy, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.update_auto_protection_policy: gapic_v1.method.wrap_method( self.update_auto_protection_policy, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_auto_protection_policy: gapic_v1.method.wrap_method( self.delete_auto_protection_policy, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.create_auto_protection_policy_binding: gapic_v1.method.wrap_method( self.create_auto_protection_policy_binding, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_auto_protection_policy_binding: gapic_v1.method.wrap_method( self.get_auto_protection_policy_binding, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_auto_protection_policy_bindings: gapic_v1.method.wrap_method( self.list_auto_protection_policy_bindings, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_applied_auto_protection_policies: gapic_v1.method.wrap_method( self.list_applied_auto_protection_policies, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.initiate_delete_auto_protection_policy_binding: gapic_v1.method.wrap_method( self.initiate_delete_auto_protection_policy_binding, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_binding_matching_resource: gapic_v1.method.wrap_method( @@ -509,7 +727,16 @@ def _prep_wrapped_messages(self, client_info): ), self.list_binding_matching_resources: gapic_v1.method.wrap_method( self.list_binding_matching_resources, - default_timeout=None, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_location: gapic_v1.method.wrap_method( @@ -612,6 +839,204 @@ def delete_management_server( ]: raise NotImplementedError() + @property + def create_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.CreateRestoreTemplateRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_restore_template( + self, + ) -> Callable[ + [restore_template.GetRestoreTemplateRequest], + Union[ + restore_template.RestoreTemplate, + Awaitable[restore_template.RestoreTemplate], + ], + ]: + raise NotImplementedError() + + @property + def list_restore_templates( + self, + ) -> Callable[ + [restore_template.ListRestoreTemplatesRequest], + Union[ + restore_template.ListRestoreTemplatesResponse, + Awaitable[restore_template.ListRestoreTemplatesResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.UpdateRestoreTemplateRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_restore_template( + self, + ) -> Callable[ + [restore_template.DeleteRestoreTemplateRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def run_restore_template( + self, + ) -> Callable[ + [restore_template.RunRestoreTemplateRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_restore_template_execution( + self, + ) -> Callable[ + [restore_template_execution.GetRestoreTemplateExecutionRequest], + Union[ + restore_template_execution.RestoreTemplateExecution, + Awaitable[restore_template_execution.RestoreTemplateExecution], + ], + ]: + raise NotImplementedError() + + @property + def list_restore_template_executions( + self, + ) -> Callable[ + [restore_template_execution.ListRestoreTemplateExecutionsRequest], + Union[ + restore_template_execution.ListRestoreTemplateExecutionsResponse, + Awaitable[restore_template_execution.ListRestoreTemplateExecutionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def trigger_restore_cleanup( + self, + ) -> Callable[ + [restore_template_execution.TriggerRestoreCleanupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_restore_verification_plan( + self, + ) -> Callable[ + [gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def create_restore_verification_plan_association( + self, + ) -> Callable[ + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest + ], + Union[ + restore_verification_plan_association.RestoreVerificationPlanAssociation, + Awaitable[ + restore_verification_plan_association.RestoreVerificationPlanAssociation + ], + ], + ]: + raise NotImplementedError() + + @property + def list_restore_verification_plan_associations( + self, + ) -> Callable[ + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest + ], + Union[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + Awaitable[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ], + ], + ]: + raise NotImplementedError() + + @property + def delete_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest + ], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def trigger_restore_verification( + self, + ) -> Callable[ + [restore_verification_plan_association.TriggerRestoreVerificationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.GetRestoreVerificationPlanRequest], + Union[ + restore_verification_plan.RestoreVerificationPlan, + Awaitable[restore_verification_plan.RestoreVerificationPlan], + ], + ]: + raise NotImplementedError() + + @property + def list_restore_verification_plans( + self, + ) -> Callable[ + [restore_verification_plan.ListRestoreVerificationPlansRequest], + Union[ + restore_verification_plan.ListRestoreVerificationPlansResponse, + Awaitable[restore_verification_plan.ListRestoreVerificationPlansResponse], + ], + ]: + raise NotImplementedError() + + @property + def delete_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.DeleteRestoreVerificationPlanRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def create_backup_vault( self, diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc.py index 2a912a980bf1..2397dcdfdcaf 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc.py @@ -44,6 +44,17 @@ backupvault, bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1beta.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .base import DEFAULT_CLIENT_INFO, BackupDRTransport @@ -466,6 +477,576 @@ def delete_management_server( ) return self._stubs["delete_management_server"] + @property + def create_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.CreateRestoreTemplateRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create restore template method over gRPC. + + Creates a new RestoreTemplate in a given project and + location. + + Returns: + Callable[[~.CreateRestoreTemplateRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_template" not in self._stubs: + self._stubs["create_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateRestoreTemplate", + request_serializer=gcb_restore_template.CreateRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_restore_template"] + + @property + def get_restore_template( + self, + ) -> Callable[ + [restore_template.GetRestoreTemplateRequest], restore_template.RestoreTemplate + ]: + r"""Return a callable for the get restore template method over gRPC. + + Gets details of a RestoreTemplate. + + Returns: + Callable[[~.GetRestoreTemplateRequest], + ~.RestoreTemplate]: + 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_restore_template" not in self._stubs: + self._stubs["get_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetRestoreTemplate", + request_serializer=restore_template.GetRestoreTemplateRequest.serialize, + response_deserializer=restore_template.RestoreTemplate.deserialize, + ) + return self._stubs["get_restore_template"] + + @property + def list_restore_templates( + self, + ) -> Callable[ + [restore_template.ListRestoreTemplatesRequest], + restore_template.ListRestoreTemplatesResponse, + ]: + r"""Return a callable for the list restore templates method over gRPC. + + Lists RestoreTemplates in a given project and + location. + + Returns: + Callable[[~.ListRestoreTemplatesRequest], + ~.ListRestoreTemplatesResponse]: + 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_restore_templates" not in self._stubs: + self._stubs["list_restore_templates"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListRestoreTemplates", + request_serializer=restore_template.ListRestoreTemplatesRequest.serialize, + response_deserializer=restore_template.ListRestoreTemplatesResponse.deserialize, + ) + return self._stubs["list_restore_templates"] + + @property + def update_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.UpdateRestoreTemplateRequest], operations_pb2.Operation + ]: + r"""Return a callable for the update restore template method over gRPC. + + Updates the settings of a RestoreTemplate. + + Returns: + Callable[[~.UpdateRestoreTemplateRequest], + ~.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 "update_restore_template" not in self._stubs: + self._stubs["update_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateRestoreTemplate", + request_serializer=gcb_restore_template.UpdateRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_restore_template"] + + @property + def delete_restore_template( + self, + ) -> Callable[ + [restore_template.DeleteRestoreTemplateRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete restore template method over gRPC. + + Deletes a RestoreTemplate. + + Returns: + Callable[[~.DeleteRestoreTemplateRequest], + ~.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_restore_template" not in self._stubs: + self._stubs["delete_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteRestoreTemplate", + request_serializer=restore_template.DeleteRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_restore_template"] + + @property + def run_restore_template( + self, + ) -> Callable[ + [restore_template.RunRestoreTemplateRequest], operations_pb2.Operation + ]: + r"""Return a callable for the run restore template method over gRPC. + + Runs a RestoreTemplate. + + Returns: + Callable[[~.RunRestoreTemplateRequest], + ~.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 "run_restore_template" not in self._stubs: + self._stubs["run_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/RunRestoreTemplate", + request_serializer=restore_template.RunRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_restore_template"] + + @property + def get_restore_template_execution( + self, + ) -> Callable[ + [restore_template_execution.GetRestoreTemplateExecutionRequest], + restore_template_execution.RestoreTemplateExecution, + ]: + r"""Return a callable for the get restore template execution method over gRPC. + + Gets details of a RestoreTemplateExecution. + + Returns: + Callable[[~.GetRestoreTemplateExecutionRequest], + ~.RestoreTemplateExecution]: + 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_restore_template_execution" not in self._stubs: + self._stubs["get_restore_template_execution"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetRestoreTemplateExecution", + request_serializer=restore_template_execution.GetRestoreTemplateExecutionRequest.serialize, + response_deserializer=restore_template_execution.RestoreTemplateExecution.deserialize, + ) + ) + return self._stubs["get_restore_template_execution"] + + @property + def list_restore_template_executions( + self, + ) -> Callable[ + [restore_template_execution.ListRestoreTemplateExecutionsRequest], + restore_template_execution.ListRestoreTemplateExecutionsResponse, + ]: + r"""Return a callable for the list restore template + executions method over gRPC. + + Lists RestoreTemplateExecutions in a given project, + location and restore template. + + Returns: + Callable[[~.ListRestoreTemplateExecutionsRequest], + ~.ListRestoreTemplateExecutionsResponse]: + 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_restore_template_executions" not in self._stubs: + self._stubs["list_restore_template_executions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListRestoreTemplateExecutions", + request_serializer=restore_template_execution.ListRestoreTemplateExecutionsRequest.serialize, + response_deserializer=restore_template_execution.ListRestoreTemplateExecutionsResponse.deserialize, + ) + ) + return self._stubs["list_restore_template_executions"] + + @property + def trigger_restore_cleanup( + self, + ) -> Callable[ + [restore_template_execution.TriggerRestoreCleanupRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the trigger restore cleanup method over gRPC. + + Triggers cleanup of restored resources created during + execution. + + Returns: + Callable[[~.TriggerRestoreCleanupRequest], + ~.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 "trigger_restore_cleanup" not in self._stubs: + self._stubs["trigger_restore_cleanup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/TriggerRestoreCleanup", + request_serializer=restore_template_execution.TriggerRestoreCleanupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["trigger_restore_cleanup"] + + @property + def create_restore_verification_plan( + self, + ) -> Callable[ + [gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the create restore verification + plan method over gRPC. + + Creates a new RestoreVerificationPlan in a given + project and location. + + Returns: + Callable[[~.CreateRestoreVerificationPlanRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_verification_plan" not in self._stubs: + self._stubs["create_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateRestoreVerificationPlan", + request_serializer=gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_restore_verification_plan"] + + @property + def create_restore_verification_plan_association( + self, + ) -> Callable[ + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the create restore verification + plan association method over gRPC. + + Creates a new RestoreVerificationPlanAssociation in a + given RestoreVerificationPlan. + + Returns: + Callable[[~.CreateRestoreVerificationPlanAssociationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_verification_plan_association" not in self._stubs: + self._stubs["create_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateRestoreVerificationPlanAssociation", + request_serializer=gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_restore_verification_plan_association"] + + @property + def get_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest + ], + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ]: + r"""Return a callable for the get restore verification plan + association method over gRPC. + + Gets details of a single + RestoreVerificationPlanAssociation in a given + RestoreVerificationPlan. + + Returns: + Callable[[~.GetRestoreVerificationPlanAssociationRequest], + ~.RestoreVerificationPlanAssociation]: + 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_restore_verification_plan_association" not in self._stubs: + self._stubs["get_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetRestoreVerificationPlanAssociation", + request_serializer=restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=restore_verification_plan_association.RestoreVerificationPlanAssociation.deserialize, + ) + ) + return self._stubs["get_restore_verification_plan_association"] + + @property + def list_restore_verification_plan_associations( + self, + ) -> Callable[ + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest + ], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + ]: + r"""Return a callable for the list restore verification plan + associations method over gRPC. + + Lists RestoreVerificationPlanAssociations in a given + RestoreVerificationPlan. + + Returns: + Callable[[~.ListRestoreVerificationPlanAssociationsRequest], + ~.ListRestoreVerificationPlanAssociationsResponse]: + 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_restore_verification_plan_associations" not in self._stubs: + self._stubs["list_restore_verification_plan_associations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListRestoreVerificationPlanAssociations", + request_serializer=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest.serialize, + response_deserializer=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.deserialize, + ) + ) + return self._stubs["list_restore_verification_plan_associations"] + + @property + def delete_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest + ], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete restore verification + plan association method over gRPC. + + Deletes a single RestoreVerificationPlanAssociation + in a given RestoreVerificationPlan. + + Returns: + Callable[[~.DeleteRestoreVerificationPlanAssociationRequest], + ~.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_restore_verification_plan_association" not in self._stubs: + self._stubs["delete_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteRestoreVerificationPlanAssociation", + request_serializer=restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_restore_verification_plan_association"] + + @property + def trigger_restore_verification( + self, + ) -> Callable[ + [restore_verification_plan_association.TriggerRestoreVerificationRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the trigger restore verification method over gRPC. + + Triggers a new Restore Verification for the + association in a given RestoreVerificationPlan. + + Returns: + Callable[[~.TriggerRestoreVerificationRequest], + ~.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 "trigger_restore_verification" not in self._stubs: + self._stubs["trigger_restore_verification"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/TriggerRestoreVerification", + request_serializer=restore_verification_plan_association.TriggerRestoreVerificationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["trigger_restore_verification"] + + @property + def get_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.GetRestoreVerificationPlanRequest], + restore_verification_plan.RestoreVerificationPlan, + ]: + r"""Return a callable for the get restore verification plan method over gRPC. + + Gets details of a single RestoreVerificationPlan. + Returns the requested RestoreVerificationPlan. + + Returns: + Callable[[~.GetRestoreVerificationPlanRequest], + ~.RestoreVerificationPlan]: + 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_restore_verification_plan" not in self._stubs: + self._stubs["get_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetRestoreVerificationPlan", + request_serializer=restore_verification_plan.GetRestoreVerificationPlanRequest.serialize, + response_deserializer=restore_verification_plan.RestoreVerificationPlan.deserialize, + ) + ) + return self._stubs["get_restore_verification_plan"] + + @property + def list_restore_verification_plans( + self, + ) -> Callable[ + [restore_verification_plan.ListRestoreVerificationPlansRequest], + restore_verification_plan.ListRestoreVerificationPlansResponse, + ]: + r"""Return a callable for the list restore verification + plans method over gRPC. + + Lists RestoreVerificationPlans in a given project and + location. + + Returns: + Callable[[~.ListRestoreVerificationPlansRequest], + ~.ListRestoreVerificationPlansResponse]: + 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_restore_verification_plans" not in self._stubs: + self._stubs["list_restore_verification_plans"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListRestoreVerificationPlans", + request_serializer=restore_verification_plan.ListRestoreVerificationPlansRequest.serialize, + response_deserializer=restore_verification_plan.ListRestoreVerificationPlansResponse.deserialize, + ) + ) + return self._stubs["list_restore_verification_plans"] + + @property + def delete_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.DeleteRestoreVerificationPlanRequest], + operations_pb2.Operation, + ]: + r"""Return a callable for the delete restore verification + plan method over gRPC. + + Deletes a single RestoreVerificationPlan. If the ``force`` flag + is set to ``true``, any RestoreVerificationPlanAssociations + linked to this RestoreVerificationPlan will also be deleted. + + Returns: + Callable[[~.DeleteRestoreVerificationPlanRequest], + ~.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_restore_verification_plan" not in self._stubs: + self._stubs["delete_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteRestoreVerificationPlan", + request_serializer=restore_verification_plan.DeleteRestoreVerificationPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_restore_verification_plan"] + @property def create_backup_vault( self, diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc_asyncio.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc_asyncio.py index cede18e6c601..baef1bde6ae4 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc_asyncio.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/grpc_asyncio.py @@ -47,6 +47,17 @@ backupvault, bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1beta.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .base import DEFAULT_CLIENT_INFO, BackupDRTransport @@ -388,27 +399,594 @@ def list_management_servers( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "list_management_servers" not in self._stubs: - self._stubs["list_management_servers"] = self._logged_channel.unary_unary( - "/google.cloud.backupdr.v1beta.BackupDR/ListManagementServers", - request_serializer=backupdr.ListManagementServersRequest.serialize, - response_deserializer=backupdr.ListManagementServersResponse.deserialize, + if "list_management_servers" not in self._stubs: + self._stubs["list_management_servers"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListManagementServers", + request_serializer=backupdr.ListManagementServersRequest.serialize, + response_deserializer=backupdr.ListManagementServersResponse.deserialize, + ) + return self._stubs["list_management_servers"] + + @property + def get_management_server( + self, + ) -> Callable[ + [backupdr.GetManagementServerRequest], Awaitable[backupdr.ManagementServer] + ]: + r"""Return a callable for the get management server method over gRPC. + + Gets details of a single ManagementServer. + + Returns: + Callable[[~.GetManagementServerRequest], + Awaitable[~.ManagementServer]]: + 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_management_server" not in self._stubs: + self._stubs["get_management_server"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetManagementServer", + request_serializer=backupdr.GetManagementServerRequest.serialize, + response_deserializer=backupdr.ManagementServer.deserialize, + ) + return self._stubs["get_management_server"] + + @property + def create_management_server( + self, + ) -> Callable[ + [backupdr.CreateManagementServerRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create management server method over gRPC. + + Creates a new ManagementServer in a given project and + location. + + Returns: + Callable[[~.CreateManagementServerRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_management_server" not in self._stubs: + self._stubs["create_management_server"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateManagementServer", + request_serializer=backupdr.CreateManagementServerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_management_server"] + + @property + def delete_management_server( + self, + ) -> Callable[ + [backupdr.DeleteManagementServerRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete management server method over gRPC. + + Deletes a single ManagementServer. + + Returns: + Callable[[~.DeleteManagementServerRequest], + 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_management_server" not in self._stubs: + self._stubs["delete_management_server"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteManagementServer", + request_serializer=backupdr.DeleteManagementServerRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_management_server"] + + @property + def create_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.CreateRestoreTemplateRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create restore template method over gRPC. + + Creates a new RestoreTemplate in a given project and + location. + + Returns: + Callable[[~.CreateRestoreTemplateRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_template" not in self._stubs: + self._stubs["create_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateRestoreTemplate", + request_serializer=gcb_restore_template.CreateRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_restore_template"] + + @property + def get_restore_template( + self, + ) -> Callable[ + [restore_template.GetRestoreTemplateRequest], + Awaitable[restore_template.RestoreTemplate], + ]: + r"""Return a callable for the get restore template method over gRPC. + + Gets details of a RestoreTemplate. + + Returns: + Callable[[~.GetRestoreTemplateRequest], + Awaitable[~.RestoreTemplate]]: + 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_restore_template" not in self._stubs: + self._stubs["get_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetRestoreTemplate", + request_serializer=restore_template.GetRestoreTemplateRequest.serialize, + response_deserializer=restore_template.RestoreTemplate.deserialize, + ) + return self._stubs["get_restore_template"] + + @property + def list_restore_templates( + self, + ) -> Callable[ + [restore_template.ListRestoreTemplatesRequest], + Awaitable[restore_template.ListRestoreTemplatesResponse], + ]: + r"""Return a callable for the list restore templates method over gRPC. + + Lists RestoreTemplates in a given project and + location. + + Returns: + Callable[[~.ListRestoreTemplatesRequest], + Awaitable[~.ListRestoreTemplatesResponse]]: + 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_restore_templates" not in self._stubs: + self._stubs["list_restore_templates"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListRestoreTemplates", + request_serializer=restore_template.ListRestoreTemplatesRequest.serialize, + response_deserializer=restore_template.ListRestoreTemplatesResponse.deserialize, + ) + return self._stubs["list_restore_templates"] + + @property + def update_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.UpdateRestoreTemplateRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the update restore template method over gRPC. + + Updates the settings of a RestoreTemplate. + + Returns: + Callable[[~.UpdateRestoreTemplateRequest], + 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 "update_restore_template" not in self._stubs: + self._stubs["update_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/UpdateRestoreTemplate", + request_serializer=gcb_restore_template.UpdateRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["update_restore_template"] + + @property + def delete_restore_template( + self, + ) -> Callable[ + [restore_template.DeleteRestoreTemplateRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete restore template method over gRPC. + + Deletes a RestoreTemplate. + + Returns: + Callable[[~.DeleteRestoreTemplateRequest], + 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_restore_template" not in self._stubs: + self._stubs["delete_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteRestoreTemplate", + request_serializer=restore_template.DeleteRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_restore_template"] + + @property + def run_restore_template( + self, + ) -> Callable[ + [restore_template.RunRestoreTemplateRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the run restore template method over gRPC. + + Runs a RestoreTemplate. + + Returns: + Callable[[~.RunRestoreTemplateRequest], + 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 "run_restore_template" not in self._stubs: + self._stubs["run_restore_template"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/RunRestoreTemplate", + request_serializer=restore_template.RunRestoreTemplateRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["run_restore_template"] + + @property + def get_restore_template_execution( + self, + ) -> Callable[ + [restore_template_execution.GetRestoreTemplateExecutionRequest], + Awaitable[restore_template_execution.RestoreTemplateExecution], + ]: + r"""Return a callable for the get restore template execution method over gRPC. + + Gets details of a RestoreTemplateExecution. + + Returns: + Callable[[~.GetRestoreTemplateExecutionRequest], + Awaitable[~.RestoreTemplateExecution]]: + 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_restore_template_execution" not in self._stubs: + self._stubs["get_restore_template_execution"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetRestoreTemplateExecution", + request_serializer=restore_template_execution.GetRestoreTemplateExecutionRequest.serialize, + response_deserializer=restore_template_execution.RestoreTemplateExecution.deserialize, + ) + ) + return self._stubs["get_restore_template_execution"] + + @property + def list_restore_template_executions( + self, + ) -> Callable[ + [restore_template_execution.ListRestoreTemplateExecutionsRequest], + Awaitable[restore_template_execution.ListRestoreTemplateExecutionsResponse], + ]: + r"""Return a callable for the list restore template + executions method over gRPC. + + Lists RestoreTemplateExecutions in a given project, + location and restore template. + + Returns: + Callable[[~.ListRestoreTemplateExecutionsRequest], + Awaitable[~.ListRestoreTemplateExecutionsResponse]]: + 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_restore_template_executions" not in self._stubs: + self._stubs["list_restore_template_executions"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListRestoreTemplateExecutions", + request_serializer=restore_template_execution.ListRestoreTemplateExecutionsRequest.serialize, + response_deserializer=restore_template_execution.ListRestoreTemplateExecutionsResponse.deserialize, + ) + ) + return self._stubs["list_restore_template_executions"] + + @property + def trigger_restore_cleanup( + self, + ) -> Callable[ + [restore_template_execution.TriggerRestoreCleanupRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the trigger restore cleanup method over gRPC. + + Triggers cleanup of restored resources created during + execution. + + Returns: + Callable[[~.TriggerRestoreCleanupRequest], + 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 "trigger_restore_cleanup" not in self._stubs: + self._stubs["trigger_restore_cleanup"] = self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/TriggerRestoreCleanup", + request_serializer=restore_template_execution.TriggerRestoreCleanupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["trigger_restore_cleanup"] + + @property + def create_restore_verification_plan( + self, + ) -> Callable[ + [gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create restore verification + plan method over gRPC. + + Creates a new RestoreVerificationPlan in a given + project and location. + + Returns: + Callable[[~.CreateRestoreVerificationPlanRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_verification_plan" not in self._stubs: + self._stubs["create_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateRestoreVerificationPlan", + request_serializer=gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_restore_verification_plan"] + + @property + def create_restore_verification_plan_association( + self, + ) -> Callable[ + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create restore verification + plan association method over gRPC. + + Creates a new RestoreVerificationPlanAssociation in a + given RestoreVerificationPlan. + + Returns: + Callable[[~.CreateRestoreVerificationPlanAssociationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_restore_verification_plan_association" not in self._stubs: + self._stubs["create_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/CreateRestoreVerificationPlanAssociation", + request_serializer=gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_restore_verification_plan_association"] + + @property + def get_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest + ], + Awaitable[ + restore_verification_plan_association.RestoreVerificationPlanAssociation + ], + ]: + r"""Return a callable for the get restore verification plan + association method over gRPC. + + Gets details of a single + RestoreVerificationPlanAssociation in a given + RestoreVerificationPlan. + + Returns: + Callable[[~.GetRestoreVerificationPlanAssociationRequest], + Awaitable[~.RestoreVerificationPlanAssociation]]: + 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_restore_verification_plan_association" not in self._stubs: + self._stubs["get_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetRestoreVerificationPlanAssociation", + request_serializer=restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=restore_verification_plan_association.RestoreVerificationPlanAssociation.deserialize, + ) + ) + return self._stubs["get_restore_verification_plan_association"] + + @property + def list_restore_verification_plan_associations( + self, + ) -> Callable[ + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest + ], + Awaitable[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse + ], + ]: + r"""Return a callable for the list restore verification plan + associations method over gRPC. + + Lists RestoreVerificationPlanAssociations in a given + RestoreVerificationPlan. + + Returns: + Callable[[~.ListRestoreVerificationPlanAssociationsRequest], + Awaitable[~.ListRestoreVerificationPlanAssociationsResponse]]: + 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_restore_verification_plan_associations" not in self._stubs: + self._stubs["list_restore_verification_plan_associations"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListRestoreVerificationPlanAssociations", + request_serializer=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest.serialize, + response_deserializer=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.deserialize, + ) + ) + return self._stubs["list_restore_verification_plan_associations"] + + @property + def delete_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest + ], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete restore verification + plan association method over gRPC. + + Deletes a single RestoreVerificationPlanAssociation + in a given RestoreVerificationPlan. + + Returns: + Callable[[~.DeleteRestoreVerificationPlanAssociationRequest], + 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_restore_verification_plan_association" not in self._stubs: + self._stubs["delete_restore_verification_plan_association"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteRestoreVerificationPlanAssociation", + request_serializer=restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["delete_restore_verification_plan_association"] + + @property + def trigger_restore_verification( + self, + ) -> Callable[ + [restore_verification_plan_association.TriggerRestoreVerificationRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the trigger restore verification method over gRPC. + + Triggers a new Restore Verification for the + association in a given RestoreVerificationPlan. + + Returns: + Callable[[~.TriggerRestoreVerificationRequest], + 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 "trigger_restore_verification" not in self._stubs: + self._stubs["trigger_restore_verification"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/TriggerRestoreVerification", + request_serializer=restore_verification_plan_association.TriggerRestoreVerificationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) ) - return self._stubs["list_management_servers"] + return self._stubs["trigger_restore_verification"] @property - def get_management_server( + def get_restore_verification_plan( self, ) -> Callable[ - [backupdr.GetManagementServerRequest], Awaitable[backupdr.ManagementServer] + [restore_verification_plan.GetRestoreVerificationPlanRequest], + Awaitable[restore_verification_plan.RestoreVerificationPlan], ]: - r"""Return a callable for the get management server method over gRPC. + r"""Return a callable for the get restore verification plan method over gRPC. - Gets details of a single ManagementServer. + Gets details of a single RestoreVerificationPlan. + Returns the requested RestoreVerificationPlan. Returns: - Callable[[~.GetManagementServerRequest], - Awaitable[~.ManagementServer]]: + Callable[[~.GetRestoreVerificationPlanRequest], + Awaitable[~.RestoreVerificationPlan]]: A function that, when called, will call the underlying RPC on the server. """ @@ -416,28 +994,32 @@ def get_management_server( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "get_management_server" not in self._stubs: - self._stubs["get_management_server"] = self._logged_channel.unary_unary( - "/google.cloud.backupdr.v1beta.BackupDR/GetManagementServer", - request_serializer=backupdr.GetManagementServerRequest.serialize, - response_deserializer=backupdr.ManagementServer.deserialize, + if "get_restore_verification_plan" not in self._stubs: + self._stubs["get_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/GetRestoreVerificationPlan", + request_serializer=restore_verification_plan.GetRestoreVerificationPlanRequest.serialize, + response_deserializer=restore_verification_plan.RestoreVerificationPlan.deserialize, + ) ) - return self._stubs["get_management_server"] + return self._stubs["get_restore_verification_plan"] @property - def create_management_server( + def list_restore_verification_plans( self, ) -> Callable[ - [backupdr.CreateManagementServerRequest], Awaitable[operations_pb2.Operation] + [restore_verification_plan.ListRestoreVerificationPlansRequest], + Awaitable[restore_verification_plan.ListRestoreVerificationPlansResponse], ]: - r"""Return a callable for the create management server method over gRPC. + r"""Return a callable for the list restore verification + plans method over gRPC. - Creates a new ManagementServer in a given project and + Lists RestoreVerificationPlans in a given project and location. Returns: - Callable[[~.CreateManagementServerRequest], - Awaitable[~.Operation]]: + Callable[[~.ListRestoreVerificationPlansRequest], + Awaitable[~.ListRestoreVerificationPlansResponse]]: A function that, when called, will call the underlying RPC on the server. """ @@ -445,26 +1027,32 @@ def create_management_server( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "create_management_server" not in self._stubs: - self._stubs["create_management_server"] = self._logged_channel.unary_unary( - "/google.cloud.backupdr.v1beta.BackupDR/CreateManagementServer", - request_serializer=backupdr.CreateManagementServerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + if "list_restore_verification_plans" not in self._stubs: + self._stubs["list_restore_verification_plans"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/ListRestoreVerificationPlans", + request_serializer=restore_verification_plan.ListRestoreVerificationPlansRequest.serialize, + response_deserializer=restore_verification_plan.ListRestoreVerificationPlansResponse.deserialize, + ) ) - return self._stubs["create_management_server"] + return self._stubs["list_restore_verification_plans"] @property - def delete_management_server( + def delete_restore_verification_plan( self, ) -> Callable[ - [backupdr.DeleteManagementServerRequest], Awaitable[operations_pb2.Operation] + [restore_verification_plan.DeleteRestoreVerificationPlanRequest], + Awaitable[operations_pb2.Operation], ]: - r"""Return a callable for the delete management server method over gRPC. + r"""Return a callable for the delete restore verification + plan method over gRPC. - Deletes a single ManagementServer. + Deletes a single RestoreVerificationPlan. If the ``force`` flag + is set to ``true``, any RestoreVerificationPlanAssociations + linked to this RestoreVerificationPlan will also be deleted. Returns: - Callable[[~.DeleteManagementServerRequest], + Callable[[~.DeleteRestoreVerificationPlanRequest], Awaitable[~.Operation]]: A function that, when called, will call the underlying RPC on the server. @@ -473,13 +1061,15 @@ def delete_management_server( # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the functions for each. - if "delete_management_server" not in self._stubs: - self._stubs["delete_management_server"] = self._logged_channel.unary_unary( - "/google.cloud.backupdr.v1beta.BackupDR/DeleteManagementServer", - request_serializer=backupdr.DeleteManagementServerRequest.serialize, - response_deserializer=operations_pb2.Operation.FromString, + if "delete_restore_verification_plan" not in self._stubs: + self._stubs["delete_restore_verification_plan"] = ( + self._logged_channel.unary_unary( + "/google.cloud.backupdr.v1beta.BackupDR/DeleteRestoreVerificationPlan", + request_serializer=restore_verification_plan.DeleteRestoreVerificationPlanRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) ) - return self._stubs["delete_management_server"] + return self._stubs["delete_restore_verification_plan"] @property def create_backup_vault( @@ -1883,6 +2473,168 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.create_restore_template: self._wrap_method( + self.create_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_template: self._wrap_method( + self.get_restore_template, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_templates: self._wrap_method( + self.list_restore_templates, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_restore_template: self._wrap_method( + self.update_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_template: self._wrap_method( + self.delete_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.run_restore_template: self._wrap_method( + self.run_restore_template, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_template_execution: self._wrap_method( + self.get_restore_template_execution, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_template_executions: self._wrap_method( + self.list_restore_template_executions, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.trigger_restore_cleanup: self._wrap_method( + self.trigger_restore_cleanup, + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_verification_plan: self._wrap_method( + self.create_restore_verification_plan, + default_timeout=60.0, + client_info=client_info, + ), + self.create_restore_verification_plan_association: self._wrap_method( + self.create_restore_verification_plan_association, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_verification_plan_association: self._wrap_method( + self.get_restore_verification_plan_association, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_verification_plan_associations: self._wrap_method( + self.list_restore_verification_plan_associations, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_verification_plan_association: self._wrap_method( + self.delete_restore_verification_plan_association, + default_timeout=60.0, + client_info=client_info, + ), + self.trigger_restore_verification: self._wrap_method( + self.trigger_restore_verification, + default_timeout=60.0, + client_info=client_info, + ), + self.get_restore_verification_plan: self._wrap_method( + self.get_restore_verification_plan, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_restore_verification_plans: self._wrap_method( + self.list_restore_verification_plans, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.delete_restore_verification_plan: self._wrap_method( + self.delete_restore_verification_plan, + default_timeout=60.0, + client_info=client_info, + ), self.create_backup_vault: self._wrap_method( self.create_backup_vault, default_retry=retries.AsyncRetry( @@ -2140,52 +2892,97 @@ def _prep_wrapped_messages(self, client_info): ), self.create_auto_protection_policy: self._wrap_method( self.create_auto_protection_policy, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.list_auto_protection_policies: self._wrap_method( self.list_auto_protection_policies, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_auto_protection_policy: self._wrap_method( self.get_auto_protection_policy, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.update_auto_protection_policy: self._wrap_method( self.update_auto_protection_policy, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.delete_auto_protection_policy: self._wrap_method( self.delete_auto_protection_policy, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.create_auto_protection_policy_binding: self._wrap_method( self.create_auto_protection_policy_binding, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_auto_protection_policy_binding: self._wrap_method( self.get_auto_protection_policy_binding, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_auto_protection_policy_bindings: self._wrap_method( self.list_auto_protection_policy_bindings, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.list_applied_auto_protection_policies: self._wrap_method( self.list_applied_auto_protection_policies, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.initiate_delete_auto_protection_policy_binding: self._wrap_method( self.initiate_delete_auto_protection_policy_binding, - default_timeout=None, + default_timeout=60.0, client_info=client_info, ), self.get_binding_matching_resource: self._wrap_method( @@ -2195,7 +2992,16 @@ def _prep_wrapped_messages(self, client_info): ), self.list_binding_matching_resources: self._wrap_method( self.list_binding_matching_resources, - default_timeout=None, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, client_info=client_info, ), self.get_location: self._wrap_method( diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest.py index 2b3221f80cac..d4c60a98012c 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest.py @@ -45,6 +45,17 @@ backupvault, bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1beta.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO @@ -136,6 +147,30 @@ def post_create_management_server(self, response): logging.log(f"Received response: {response}") return response + def pre_create_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_restore_verification_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_restore_verification_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_restore_verification_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_restore_verification_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_auto_protection_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -184,6 +219,30 @@ def post_delete_management_server(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_restore_verification_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_restore_verification_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_restore_verification_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_restore_verification_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + def pre_fetch_backup_plan_associations_for_resource_type(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -304,6 +363,38 @@ def post_get_management_server(self, response): logging.log(f"Received response: {response}") return response + def pre_get_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_restore_template_execution(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_restore_template_execution(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_restore_verification_plan(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_restore_verification_plan(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_restore_verification_plan_association(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_restore_verification_plan_association(self, response): + logging.log(f"Received response: {response}") + return response + def pre_initialize_service(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -416,6 +507,38 @@ def post_list_management_servers(self, response): logging.log(f"Received response: {response}") return response + def pre_list_restore_template_executions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_restore_template_executions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_restore_templates(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_restore_templates(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_restore_verification_plan_associations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_restore_verification_plan_associations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_restore_verification_plans(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_restore_verification_plans(self, response): + logging.log(f"Received response: {response}") + return response + def pre_restore_backup(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -424,6 +547,14 @@ def post_restore_backup(self, response): logging.log(f"Received response: {response}") return response + def pre_run_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_run_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + def pre_trigger_backup(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -432,6 +563,22 @@ def post_trigger_backup(self, response): logging.log(f"Received response: {response}") return response + def pre_trigger_restore_cleanup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_trigger_restore_cleanup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_trigger_restore_verification(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_trigger_restore_verification(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_auto_protection_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -480,6 +627,14 @@ def post_update_data_source(self, response): logging.log(f"Received response: {response}") return response + def pre_update_restore_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_restore_template(self, response): + logging.log(f"Received response: {response}") + return response + transport = BackupDRRestTransport(interceptor=MyCustomBackupDRInterceptor()) client = BackupDRClient(transport=transport) @@ -777,6 +932,153 @@ def post_create_management_server_with_metadata( """ return response, metadata + def pre_create_restore_template( + self, + request: gcb_restore_template.CreateRestoreTemplateRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcb_restore_template.CreateRestoreTemplateRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_restore_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_restore_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_restore_template + + DEPRECATED. Please use the `post_create_restore_template_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_restore_template` interceptor runs + before the `post_create_restore_template_with_metadata` interceptor. + """ + return response + + def post_create_restore_template_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_restore_template + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_restore_template_with_metadata` + interceptor in new development instead of the `post_create_restore_template` interceptor. + When both interceptors are used, this `post_create_restore_template_with_metadata` interceptor runs after the + `post_create_restore_template` interceptor. The (possibly modified) response returned by + `post_create_restore_template` will be passed to + `post_create_restore_template_with_metadata`. + """ + return response, metadata + + def pre_create_restore_verification_plan( + self, + request: gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_restore_verification_plan + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_restore_verification_plan( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_restore_verification_plan + + DEPRECATED. Please use the `post_create_restore_verification_plan_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_restore_verification_plan` interceptor runs + before the `post_create_restore_verification_plan_with_metadata` interceptor. + """ + return response + + def post_create_restore_verification_plan_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_restore_verification_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_restore_verification_plan_with_metadata` + interceptor in new development instead of the `post_create_restore_verification_plan` interceptor. + When both interceptors are used, this `post_create_restore_verification_plan_with_metadata` interceptor runs after the + `post_create_restore_verification_plan` interceptor. The (possibly modified) response returned by + `post_create_restore_verification_plan` will be passed to + `post_create_restore_verification_plan_with_metadata`. + """ + return response, metadata + + def pre_create_restore_verification_plan_association( + self, + request: gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for create_restore_verification_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_create_restore_verification_plan_association( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_restore_verification_plan_association + + DEPRECATED. Please use the `post_create_restore_verification_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_create_restore_verification_plan_association` interceptor runs + before the `post_create_restore_verification_plan_association_with_metadata` interceptor. + """ + return response + + def post_create_restore_verification_plan_association_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_restore_verification_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_create_restore_verification_plan_association_with_metadata` + interceptor in new development instead of the `post_create_restore_verification_plan_association` interceptor. + When both interceptors are used, this `post_create_restore_verification_plan_association_with_metadata` interceptor runs after the + `post_create_restore_verification_plan_association` interceptor. The (possibly modified) response returned by + `post_create_restore_verification_plan_association` will be passed to + `post_create_restore_verification_plan_association_with_metadata`. + """ + return response, metadata + def pre_delete_auto_protection_policy( self, request: autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, @@ -1067,96 +1369,243 @@ def post_delete_management_server_with_metadata( """ return response, metadata - def pre_fetch_backup_plan_associations_for_resource_type( + def pre_delete_restore_template( self, - request: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + request: restore_template.DeleteRestoreTemplateRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + restore_template.DeleteRestoreTemplateRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for fetch_backup_plan_associations_for_resource_type + """Pre-rpc interceptor for delete_restore_template Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_fetch_backup_plan_associations_for_resource_type( - self, - response: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, - ) -> backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: - """Post-rpc interceptor for fetch_backup_plan_associations_for_resource_type + def post_delete_restore_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_restore_template - DEPRECATED. Please use the `post_fetch_backup_plan_associations_for_resource_type_with_metadata` + DEPRECATED. Please use the `post_delete_restore_template_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_fetch_backup_plan_associations_for_resource_type` interceptor runs - before the `post_fetch_backup_plan_associations_for_resource_type_with_metadata` interceptor. + it is returned to user code. This `post_delete_restore_template` interceptor runs + before the `post_delete_restore_template_with_metadata` interceptor. """ return response - def post_fetch_backup_plan_associations_for_resource_type_with_metadata( + def post_delete_restore_template_with_metadata( self, - response: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, - Sequence[Tuple[str, Union[str, bytes]]], - ]: - """Post-rpc interceptor for fetch_backup_plan_associations_for_resource_type + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_restore_template Override in a subclass to read or manipulate the response or metadata after it is returned by the BackupDR server but before it is returned to user code. - We recommend only using this `post_fetch_backup_plan_associations_for_resource_type_with_metadata` - interceptor in new development instead of the `post_fetch_backup_plan_associations_for_resource_type` interceptor. - When both interceptors are used, this `post_fetch_backup_plan_associations_for_resource_type_with_metadata` interceptor runs after the - `post_fetch_backup_plan_associations_for_resource_type` interceptor. The (possibly modified) response returned by - `post_fetch_backup_plan_associations_for_resource_type` will be passed to - `post_fetch_backup_plan_associations_for_resource_type_with_metadata`. + We recommend only using this `post_delete_restore_template_with_metadata` + interceptor in new development instead of the `post_delete_restore_template` interceptor. + When both interceptors are used, this `post_delete_restore_template_with_metadata` interceptor runs after the + `post_delete_restore_template` interceptor. The (possibly modified) response returned by + `post_delete_restore_template` will be passed to + `post_delete_restore_template_with_metadata`. """ return response, metadata - def pre_fetch_backups_for_resource_type( + def pre_delete_restore_verification_plan( self, - request: backupvault.FetchBackupsForResourceTypeRequest, + request: restore_verification_plan.DeleteRestoreVerificationPlanRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - backupvault.FetchBackupsForResourceTypeRequest, + restore_verification_plan.DeleteRestoreVerificationPlanRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for fetch_backups_for_resource_type + """Pre-rpc interceptor for delete_restore_verification_plan Override in a subclass to manipulate the request or metadata before they are sent to the BackupDR server. """ return request, metadata - def post_fetch_backups_for_resource_type( - self, response: backupvault.FetchBackupsForResourceTypeResponse - ) -> backupvault.FetchBackupsForResourceTypeResponse: - """Post-rpc interceptor for fetch_backups_for_resource_type + def post_delete_restore_verification_plan( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_restore_verification_plan - DEPRECATED. Please use the `post_fetch_backups_for_resource_type_with_metadata` + DEPRECATED. Please use the `post_delete_restore_verification_plan_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the BackupDR server but before - it is returned to user code. This `post_fetch_backups_for_resource_type` interceptor runs - before the `post_fetch_backups_for_resource_type_with_metadata` interceptor. + it is returned to user code. This `post_delete_restore_verification_plan` interceptor runs + before the `post_delete_restore_verification_plan_with_metadata` interceptor. """ return response - def post_fetch_backups_for_resource_type_with_metadata( + def post_delete_restore_verification_plan_with_metadata( self, - response: backupvault.FetchBackupsForResourceTypeResponse, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - backupvault.FetchBackupsForResourceTypeResponse, - Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_restore_verification_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_restore_verification_plan_with_metadata` + interceptor in new development instead of the `post_delete_restore_verification_plan` interceptor. + When both interceptors are used, this `post_delete_restore_verification_plan_with_metadata` interceptor runs after the + `post_delete_restore_verification_plan` interceptor. The (possibly modified) response returned by + `post_delete_restore_verification_plan` will be passed to + `post_delete_restore_verification_plan_with_metadata`. + """ + return response, metadata + + def pre_delete_restore_verification_plan_association( + self, + request: restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete_restore_verification_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_delete_restore_verification_plan_association( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_restore_verification_plan_association + + DEPRECATED. Please use the `post_delete_restore_verification_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_delete_restore_verification_plan_association` interceptor runs + before the `post_delete_restore_verification_plan_association_with_metadata` interceptor. + """ + return response + + def post_delete_restore_verification_plan_association_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_restore_verification_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_delete_restore_verification_plan_association_with_metadata` + interceptor in new development instead of the `post_delete_restore_verification_plan_association` interceptor. + When both interceptors are used, this `post_delete_restore_verification_plan_association_with_metadata` interceptor runs after the + `post_delete_restore_verification_plan_association` interceptor. The (possibly modified) response returned by + `post_delete_restore_verification_plan_association` will be passed to + `post_delete_restore_verification_plan_association_with_metadata`. + """ + return response, metadata + + def pre_fetch_backup_plan_associations_for_resource_type( + self, + request: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_backup_plan_associations_for_resource_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_fetch_backup_plan_associations_for_resource_type( + self, + response: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + ) -> backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: + """Post-rpc interceptor for fetch_backup_plan_associations_for_resource_type + + DEPRECATED. Please use the `post_fetch_backup_plan_associations_for_resource_type_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_fetch_backup_plan_associations_for_resource_type` interceptor runs + before the `post_fetch_backup_plan_associations_for_resource_type_with_metadata` interceptor. + """ + return response + + def post_fetch_backup_plan_associations_for_resource_type_with_metadata( + self, + response: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_backup_plan_associations_for_resource_type + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_fetch_backup_plan_associations_for_resource_type_with_metadata` + interceptor in new development instead of the `post_fetch_backup_plan_associations_for_resource_type` interceptor. + When both interceptors are used, this `post_fetch_backup_plan_associations_for_resource_type_with_metadata` interceptor runs after the + `post_fetch_backup_plan_associations_for_resource_type` interceptor. The (possibly modified) response returned by + `post_fetch_backup_plan_associations_for_resource_type` will be passed to + `post_fetch_backup_plan_associations_for_resource_type_with_metadata`. + """ + return response, metadata + + def pre_fetch_backups_for_resource_type( + self, + request: backupvault.FetchBackupsForResourceTypeRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.FetchBackupsForResourceTypeRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_backups_for_resource_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_fetch_backups_for_resource_type( + self, response: backupvault.FetchBackupsForResourceTypeResponse + ) -> backupvault.FetchBackupsForResourceTypeResponse: + """Post-rpc interceptor for fetch_backups_for_resource_type + + DEPRECATED. Please use the `post_fetch_backups_for_resource_type_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_fetch_backups_for_resource_type` interceptor runs + before the `post_fetch_backups_for_resource_type_with_metadata` interceptor. + """ + return response + + def post_fetch_backups_for_resource_type_with_metadata( + self, + response: backupvault.FetchBackupsForResourceTypeResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + backupvault.FetchBackupsForResourceTypeResponse, + Sequence[Tuple[str, Union[str, bytes]]], ]: """Post-rpc interceptor for fetch_backups_for_resource_type @@ -1820,6 +2269,214 @@ def post_get_management_server_with_metadata( """ return response, metadata + def pre_get_restore_template( + self, + request: restore_template.GetRestoreTemplateRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template.GetRestoreTemplateRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_restore_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_restore_template( + self, response: restore_template.RestoreTemplate + ) -> restore_template.RestoreTemplate: + """Post-rpc interceptor for get_restore_template + + DEPRECATED. Please use the `post_get_restore_template_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_restore_template` interceptor runs + before the `post_get_restore_template_with_metadata` interceptor. + """ + return response + + def post_get_restore_template_with_metadata( + self, + response: restore_template.RestoreTemplate, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template.RestoreTemplate, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_restore_template + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_restore_template_with_metadata` + interceptor in new development instead of the `post_get_restore_template` interceptor. + When both interceptors are used, this `post_get_restore_template_with_metadata` interceptor runs after the + `post_get_restore_template` interceptor. The (possibly modified) response returned by + `post_get_restore_template` will be passed to + `post_get_restore_template_with_metadata`. + """ + return response, metadata + + def pre_get_restore_template_execution( + self, + request: restore_template_execution.GetRestoreTemplateExecutionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template_execution.GetRestoreTemplateExecutionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_restore_template_execution + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_restore_template_execution( + self, response: restore_template_execution.RestoreTemplateExecution + ) -> restore_template_execution.RestoreTemplateExecution: + """Post-rpc interceptor for get_restore_template_execution + + DEPRECATED. Please use the `post_get_restore_template_execution_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_restore_template_execution` interceptor runs + before the `post_get_restore_template_execution_with_metadata` interceptor. + """ + return response + + def post_get_restore_template_execution_with_metadata( + self, + response: restore_template_execution.RestoreTemplateExecution, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template_execution.RestoreTemplateExecution, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_restore_template_execution + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_restore_template_execution_with_metadata` + interceptor in new development instead of the `post_get_restore_template_execution` interceptor. + When both interceptors are used, this `post_get_restore_template_execution_with_metadata` interceptor runs after the + `post_get_restore_template_execution` interceptor. The (possibly modified) response returned by + `post_get_restore_template_execution` will be passed to + `post_get_restore_template_execution_with_metadata`. + """ + return response, metadata + + def pre_get_restore_verification_plan( + self, + request: restore_verification_plan.GetRestoreVerificationPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan.GetRestoreVerificationPlanRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_restore_verification_plan + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_restore_verification_plan( + self, response: restore_verification_plan.RestoreVerificationPlan + ) -> restore_verification_plan.RestoreVerificationPlan: + """Post-rpc interceptor for get_restore_verification_plan + + DEPRECATED. Please use the `post_get_restore_verification_plan_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_restore_verification_plan` interceptor runs + before the `post_get_restore_verification_plan_with_metadata` interceptor. + """ + return response + + def post_get_restore_verification_plan_with_metadata( + self, + response: restore_verification_plan.RestoreVerificationPlan, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan.RestoreVerificationPlan, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_restore_verification_plan + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_restore_verification_plan_with_metadata` + interceptor in new development instead of the `post_get_restore_verification_plan` interceptor. + When both interceptors are used, this `post_get_restore_verification_plan_with_metadata` interceptor runs after the + `post_get_restore_verification_plan` interceptor. The (possibly modified) response returned by + `post_get_restore_verification_plan` will be passed to + `post_get_restore_verification_plan_with_metadata`. + """ + return response, metadata + + def pre_get_restore_verification_plan_association( + self, + request: restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_restore_verification_plan_association + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_get_restore_verification_plan_association( + self, + response: restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) -> restore_verification_plan_association.RestoreVerificationPlanAssociation: + """Post-rpc interceptor for get_restore_verification_plan_association + + DEPRECATED. Please use the `post_get_restore_verification_plan_association_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_get_restore_verification_plan_association` interceptor runs + before the `post_get_restore_verification_plan_association_with_metadata` interceptor. + """ + return response + + def post_get_restore_verification_plan_association_with_metadata( + self, + response: restore_verification_plan_association.RestoreVerificationPlanAssociation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan_association.RestoreVerificationPlanAssociation, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_restore_verification_plan_association + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_get_restore_verification_plan_association_with_metadata` + interceptor in new development instead of the `post_get_restore_verification_plan_association` interceptor. + When both interceptors are used, this `post_get_restore_verification_plan_association_with_metadata` interceptor runs after the + `post_get_restore_verification_plan_association` interceptor. The (possibly modified) response returned by + `post_get_restore_verification_plan_association` will be passed to + `post_get_restore_verification_plan_association_with_metadata`. + """ + return response, metadata + def pre_initialize_service( self, request: backupdr.InitializeServiceRequest, @@ -2531,9 +3188,218 @@ def post_list_management_servers_with_metadata( """ return response, metadata - def pre_restore_backup( + def pre_list_restore_template_executions( self, - request: backupvault.RestoreBackupRequest, + request: restore_template_execution.ListRestoreTemplateExecutionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template_execution.ListRestoreTemplateExecutionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_restore_template_executions + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_restore_template_executions( + self, response: restore_template_execution.ListRestoreTemplateExecutionsResponse + ) -> restore_template_execution.ListRestoreTemplateExecutionsResponse: + """Post-rpc interceptor for list_restore_template_executions + + DEPRECATED. Please use the `post_list_restore_template_executions_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_restore_template_executions` interceptor runs + before the `post_list_restore_template_executions_with_metadata` interceptor. + """ + return response + + def post_list_restore_template_executions_with_metadata( + self, + response: restore_template_execution.ListRestoreTemplateExecutionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template_execution.ListRestoreTemplateExecutionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_restore_template_executions + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_restore_template_executions_with_metadata` + interceptor in new development instead of the `post_list_restore_template_executions` interceptor. + When both interceptors are used, this `post_list_restore_template_executions_with_metadata` interceptor runs after the + `post_list_restore_template_executions` interceptor. The (possibly modified) response returned by + `post_list_restore_template_executions` will be passed to + `post_list_restore_template_executions_with_metadata`. + """ + return response, metadata + + def pre_list_restore_templates( + self, + request: restore_template.ListRestoreTemplatesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template.ListRestoreTemplatesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_restore_templates + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_restore_templates( + self, response: restore_template.ListRestoreTemplatesResponse + ) -> restore_template.ListRestoreTemplatesResponse: + """Post-rpc interceptor for list_restore_templates + + DEPRECATED. Please use the `post_list_restore_templates_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_restore_templates` interceptor runs + before the `post_list_restore_templates_with_metadata` interceptor. + """ + return response + + def post_list_restore_templates_with_metadata( + self, + response: restore_template.ListRestoreTemplatesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template.ListRestoreTemplatesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_restore_templates + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_restore_templates_with_metadata` + interceptor in new development instead of the `post_list_restore_templates` interceptor. + When both interceptors are used, this `post_list_restore_templates_with_metadata` interceptor runs after the + `post_list_restore_templates` interceptor. The (possibly modified) response returned by + `post_list_restore_templates` will be passed to + `post_list_restore_templates_with_metadata`. + """ + return response, metadata + + def pre_list_restore_verification_plan_associations( + self, + request: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_restore_verification_plan_associations + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_restore_verification_plan_associations( + self, + response: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + ) -> restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse: + """Post-rpc interceptor for list_restore_verification_plan_associations + + DEPRECATED. Please use the `post_list_restore_verification_plan_associations_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_restore_verification_plan_associations` interceptor runs + before the `post_list_restore_verification_plan_associations_with_metadata` interceptor. + """ + return response + + def post_list_restore_verification_plan_associations_with_metadata( + self, + response: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_restore_verification_plan_associations + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_restore_verification_plan_associations_with_metadata` + interceptor in new development instead of the `post_list_restore_verification_plan_associations` interceptor. + When both interceptors are used, this `post_list_restore_verification_plan_associations_with_metadata` interceptor runs after the + `post_list_restore_verification_plan_associations` interceptor. The (possibly modified) response returned by + `post_list_restore_verification_plan_associations` will be passed to + `post_list_restore_verification_plan_associations_with_metadata`. + """ + return response, metadata + + def pre_list_restore_verification_plans( + self, + request: restore_verification_plan.ListRestoreVerificationPlansRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan.ListRestoreVerificationPlansRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_restore_verification_plans + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_list_restore_verification_plans( + self, response: restore_verification_plan.ListRestoreVerificationPlansResponse + ) -> restore_verification_plan.ListRestoreVerificationPlansResponse: + """Post-rpc interceptor for list_restore_verification_plans + + DEPRECATED. Please use the `post_list_restore_verification_plans_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_list_restore_verification_plans` interceptor runs + before the `post_list_restore_verification_plans_with_metadata` interceptor. + """ + return response + + def post_list_restore_verification_plans_with_metadata( + self, + response: restore_verification_plan.ListRestoreVerificationPlansResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan.ListRestoreVerificationPlansResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_restore_verification_plans + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_list_restore_verification_plans_with_metadata` + interceptor in new development instead of the `post_list_restore_verification_plans` interceptor. + When both interceptors are used, this `post_list_restore_verification_plans_with_metadata` interceptor runs after the + `post_list_restore_verification_plans` interceptor. The (possibly modified) response returned by + `post_list_restore_verification_plans` will be passed to + `post_list_restore_verification_plans_with_metadata`. + """ + return response, metadata + + def pre_restore_backup( + self, + request: backupvault.RestoreBackupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ backupvault.RestoreBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] @@ -2579,6 +3445,55 @@ def post_restore_backup_with_metadata( """ return response, metadata + def pre_run_restore_template( + self, + request: restore_template.RunRestoreTemplateRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template.RunRestoreTemplateRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for run_restore_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_run_restore_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for run_restore_template + + DEPRECATED. Please use the `post_run_restore_template_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_run_restore_template` interceptor runs + before the `post_run_restore_template_with_metadata` interceptor. + """ + return response + + def post_run_restore_template_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 run_restore_template + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_run_restore_template_with_metadata` + interceptor in new development instead of the `post_run_restore_template` interceptor. + When both interceptors are used, this `post_run_restore_template_with_metadata` interceptor runs after the + `post_run_restore_template` interceptor. The (possibly modified) response returned by + `post_run_restore_template` will be passed to + `post_run_restore_template_with_metadata`. + """ + return response, metadata + def pre_trigger_backup( self, request: backupplanassociation.TriggerBackupRequest, @@ -2628,6 +3543,104 @@ def post_trigger_backup_with_metadata( """ return response, metadata + def pre_trigger_restore_cleanup( + self, + request: restore_template_execution.TriggerRestoreCleanupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_template_execution.TriggerRestoreCleanupRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for trigger_restore_cleanup + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_trigger_restore_cleanup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for trigger_restore_cleanup + + DEPRECATED. Please use the `post_trigger_restore_cleanup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_trigger_restore_cleanup` interceptor runs + before the `post_trigger_restore_cleanup_with_metadata` interceptor. + """ + return response + + def post_trigger_restore_cleanup_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 trigger_restore_cleanup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_trigger_restore_cleanup_with_metadata` + interceptor in new development instead of the `post_trigger_restore_cleanup` interceptor. + When both interceptors are used, this `post_trigger_restore_cleanup_with_metadata` interceptor runs after the + `post_trigger_restore_cleanup` interceptor. The (possibly modified) response returned by + `post_trigger_restore_cleanup` will be passed to + `post_trigger_restore_cleanup_with_metadata`. + """ + return response, metadata + + def pre_trigger_restore_verification( + self, + request: restore_verification_plan_association.TriggerRestoreVerificationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + restore_verification_plan_association.TriggerRestoreVerificationRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for trigger_restore_verification + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_trigger_restore_verification( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for trigger_restore_verification + + DEPRECATED. Please use the `post_trigger_restore_verification_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_trigger_restore_verification` interceptor runs + before the `post_trigger_restore_verification_with_metadata` interceptor. + """ + return response + + def post_trigger_restore_verification_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 trigger_restore_verification + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_trigger_restore_verification_with_metadata` + interceptor in new development instead of the `post_trigger_restore_verification` interceptor. + When both interceptors are used, this `post_trigger_restore_verification_with_metadata` interceptor runs after the + `post_trigger_restore_verification` interceptor. The (possibly modified) response returned by + `post_trigger_restore_verification` will be passed to + `post_trigger_restore_verification_with_metadata`. + """ + return response, metadata + def pre_update_auto_protection_policy( self, request: autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, @@ -2918,6 +3931,55 @@ def post_update_data_source_with_metadata( """ return response, metadata + def pre_update_restore_template( + self, + request: gcb_restore_template.UpdateRestoreTemplateRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + gcb_restore_template.UpdateRestoreTemplateRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_restore_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the BackupDR server. + """ + return request, metadata + + def post_update_restore_template( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_restore_template + + DEPRECATED. Please use the `post_update_restore_template_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the BackupDR server but before + it is returned to user code. This `post_update_restore_template` interceptor runs + before the `post_update_restore_template_with_metadata` interceptor. + """ + return response + + def post_update_restore_template_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_restore_template + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the BackupDR server but before it is returned to user code. + + We recommend only using this `post_update_restore_template_with_metadata` + interceptor in new development instead of the `post_update_restore_template` interceptor. + When both interceptors are used, this `post_update_restore_template_with_metadata` interceptor runs after the + `post_update_restore_template` interceptor. The (possibly modified) response returned by + `post_update_restore_template` will be passed to + `post_update_restore_template_with_metadata`. + """ + return response, metadata + def pre_get_location( self, request: locations_pb2.GetLocationRequest, @@ -4194,11 +5256,11 @@ def __call__( ) return resp - class _DeleteAutoProtectionPolicy( - _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy, BackupDRRestStub + class _CreateRestoreTemplate( + _BaseBackupDRRestTransport._BaseCreateRestoreTemplate, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteAutoProtectionPolicy") + return hash("BackupDRRestTransport.CreateRestoreTemplate") @staticmethod def _get_response( @@ -4219,50 +5281,50 @@ 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: autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, + request: gcb_restore_template.CreateRestoreTemplateRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the delete auto protection - policy method over HTTP. + r"""Call the create restore template method over HTTP. - Args: - request (~.autoprotectionpolicy.DeleteAutoProtectionPolicyRequest): - The request object. Request message for deleting an - AutoProtectionPolicy. - 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 (~.gcb_restore_template.CreateRestoreTemplateRequest): + The request object. Request message for creating a + RestoreTemplate instance. + 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. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy._get_http_options() - request, metadata = self._interceptor.pre_delete_auto_protection_policy( + http_options = _BaseBackupDRRestTransport._BaseCreateRestoreTemplate._get_http_options() + request, metadata = self._interceptor.pre_create_restore_template( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy, - "_BaseDeleteAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseCreateRestoreTemplate, + "_BaseCreateRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4286,23 +5348,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteAutoProtectionPolicy", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CreateRestoreTemplate", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteAutoProtectionPolicy", + "rpcName": "CreateRestoreTemplate", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteAutoProtectionPolicy._get_response( + response = BackupDRRestTransport._CreateRestoreTemplate._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4314,12 +5377,10 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_auto_protection_policy(resp) + resp = self._interceptor.post_create_restore_template(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_delete_auto_protection_policy_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_create_restore_template_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -4334,19 +5395,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_auto_protection_policy", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.create_restore_template", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteAutoProtectionPolicy", + "rpcName": "CreateRestoreTemplate", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteBackup(_BaseBackupDRRestTransport._BaseDeleteBackup, BackupDRRestStub): + class _CreateRestoreVerificationPlan( + _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlan, BackupDRRestStub + ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteBackup") + return hash("BackupDRRestTransport.CreateRestoreVerificationPlan") @staticmethod def _get_response( @@ -4367,48 +5430,51 @@ 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: backupvault.DeleteBackupRequest, + request: gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, *, 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. + r"""Call the create restore + verification plan method over HTTP. - Args: - request (~.backupvault.DeleteBackupRequest): - The request object. Message for deleting a Backup. - 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 (~.gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest): + The request object. The request message for creating a + ``RestoreVerificationPlan``. + 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. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseBackupDRRestTransport._BaseDeleteBackup._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlan._get_http_options() + request, metadata = self._interceptor.pre_create_restore_verification_plan( + request, metadata ) - request, metadata = self._interceptor.pre_delete_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteBackup, - "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlan, + "_BaseCreateRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4432,23 +5498,26 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackup", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CreateRestoreVerificationPlan", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteBackup", + "rpcName": "CreateRestoreVerificationPlan", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteBackup._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + BackupDRRestTransport._CreateRestoreVerificationPlan._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4460,10 +5529,12 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_backup(resp) + resp = self._interceptor.post_create_restore_verification_plan(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_backup_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_create_restore_verification_plan_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -4478,21 +5549,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.create_restore_verification_plan", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteBackup", + "rpcName": "CreateRestoreVerificationPlan", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteBackupPlan( - _BaseBackupDRRestTransport._BaseDeleteBackupPlan, BackupDRRestStub + class _CreateRestoreVerificationPlanAssociation( + _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlanAssociation, + BackupDRRestStub, ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteBackupPlan") + return hash( + "BackupDRRestTransport.CreateRestoreVerificationPlanAssociation" + ) @staticmethod def _get_response( @@ -4513,50 +5587,53 @@ 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: backupplan.DeleteBackupPlanRequest, + request: gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, *, 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 plan method over HTTP. + r"""Call the create restore + verification plan association method over HTTP. - Args: - request (~.backupplan.DeleteBackupPlanRequest): - The request object. The request message for deleting a ``BackupPlan``. - 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 (~.gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest): + The request object. Request message for + CreateRestoreVerificationPlanAssociation. + 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. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseBackupDRRestTransport._BaseDeleteBackupPlan._get_http_options() - ) - request, metadata = self._interceptor.pre_delete_backup_plan( - request, metadata + http_options = _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlanAssociation._get_http_options() + request, metadata = ( + self._interceptor.pre_create_restore_verification_plan_association( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteBackupPlan, - "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseCreateRestoreVerificationPlanAssociation, + "_BaseCreateRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4580,23 +5657,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackupPlan", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.CreateRestoreVerificationPlanAssociation", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteBackupPlan", + "rpcName": "CreateRestoreVerificationPlanAssociation", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteBackupPlan._get_response( + response = BackupDRRestTransport._CreateRestoreVerificationPlanAssociation._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4608,10 +5686,14 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_backup_plan(resp) + resp = self._interceptor.post_create_restore_verification_plan_association( + resp + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_backup_plan_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_create_restore_verification_plan_association_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -4626,21 +5708,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.create_restore_verification_plan_association", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteBackupPlan", + "rpcName": "CreateRestoreVerificationPlanAssociation", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteBackupPlanAssociation( - _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, BackupDRRestStub + class _DeleteAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteBackupPlanAssociation") + return hash("BackupDRRestTransport.DeleteAutoProtectionPolicy") @staticmethod def _get_response( @@ -4666,19 +5748,19 @@ def _get_response( def __call__( self, - request: backupplanassociation.DeleteBackupPlanAssociationRequest, + request: autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, *, 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 plan - association method over HTTP. + r"""Call the delete auto protection + policy method over HTTP. Args: - request (~.backupplanassociation.DeleteBackupPlanAssociationRequest): - The request object. Request message for deleting a backup - plan association. + request (~.autoprotectionpolicy.DeleteAutoProtectionPolicyRequest): + The request object. Request message for deleting an + AutoProtectionPolicy. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4695,16 +5777,16 @@ def __call__( """ - http_options = _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation._get_http_options() - request, metadata = self._interceptor.pre_delete_backup_plan_association( + http_options = _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_delete_auto_protection_policy( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, - "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseDeleteAutoProtectionPolicy, + "_BaseDeleteAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4728,17 +5810,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackupPlanAssociation", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteAutoProtectionPolicy", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteBackupPlanAssociation", + "rpcName": "DeleteAutoProtectionPolicy", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteBackupPlanAssociation._get_response( + response = BackupDRRestTransport._DeleteAutoProtectionPolicy._get_response( self._host, metadata, query_params, @@ -4756,10 +5838,10 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_backup_plan_association(resp) + resp = self._interceptor.post_delete_auto_protection_policy(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_delete_backup_plan_association_with_metadata( + self._interceptor.post_delete_auto_protection_policy_with_metadata( resp, response_metadata ) ) @@ -4776,21 +5858,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan_association", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_auto_protection_policy", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteBackupPlanAssociation", + "rpcName": "DeleteAutoProtectionPolicy", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteBackupVault( - _BaseBackupDRRestTransport._BaseDeleteBackupVault, BackupDRRestStub - ): + class _DeleteBackup(_BaseBackupDRRestTransport._BaseDeleteBackup, BackupDRRestStub): def __hash__(self): - return hash("BackupDRRestTransport.DeleteBackupVault") + return hash("BackupDRRestTransport.DeleteBackup") @staticmethod def _get_response( @@ -4816,17 +5896,17 @@ def _get_response( def __call__( self, - request: backupvault.DeleteBackupVaultRequest, + request: backupvault.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 vault method over HTTP. + r"""Call the delete backup method over HTTP. Args: - request (~.backupvault.DeleteBackupVaultRequest): - The request object. Message for deleting a BackupVault. + request (~.backupvault.DeleteBackupRequest): + The request object. Message for deleting a Backup. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4844,17 +5924,15 @@ def __call__( """ http_options = ( - _BaseBackupDRRestTransport._BaseDeleteBackupVault._get_http_options() - ) - request, metadata = self._interceptor.pre_delete_backup_vault( - request, metadata + _BaseBackupDRRestTransport._BaseDeleteBackup._get_http_options() ) + request, metadata = self._interceptor.pre_delete_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteBackupVault, - "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseDeleteBackup, + "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4878,17 +5956,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackupVault", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteBackupVault", + "rpcName": "DeleteBackup", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteBackupVault._get_response( + response = BackupDRRestTransport._DeleteBackup._get_response( self._host, metadata, query_params, @@ -4906,9 +5984,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_backup_vault(resp) + 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_vault_with_metadata( + resp, _ = self._interceptor.post_delete_backup_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -4924,21 +6002,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_vault", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteBackupVault", + "rpcName": "DeleteBackup", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteManagementServer( - _BaseBackupDRRestTransport._BaseDeleteManagementServer, BackupDRRestStub + class _DeleteBackupPlan( + _BaseBackupDRRestTransport._BaseDeleteBackupPlan, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.DeleteManagementServer") + return hash("BackupDRRestTransport.DeleteBackupPlan") @staticmethod def _get_response( @@ -4964,18 +6042,17 @@ def _get_response( def __call__( self, - request: backupdr.DeleteManagementServerRequest, + request: backupplan.DeleteBackupPlanRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the delete management server method over HTTP. + r"""Call the delete backup plan method over HTTP. Args: - request (~.backupdr.DeleteManagementServerRequest): - The request object. Request message for deleting a - management server instance. + request (~.backupplan.DeleteBackupPlanRequest): + The request object. The request message for deleting a ``BackupPlan``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4992,16 +6069,18 @@ def __call__( """ - http_options = _BaseBackupDRRestTransport._BaseDeleteManagementServer._get_http_options() - request, metadata = self._interceptor.pre_delete_management_server( + http_options = ( + _BaseBackupDRRestTransport._BaseDeleteBackupPlan._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_backup_plan( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseDeleteManagementServer, - "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseDeleteBackupPlan, + "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5025,17 +6104,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteManagementServer", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackupPlan", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteManagementServer", + "rpcName": "DeleteBackupPlan", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._DeleteManagementServer._get_response( + response = BackupDRRestTransport._DeleteBackupPlan._get_response( self._host, metadata, query_params, @@ -5053,9 +6132,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_management_server(resp) + resp = self._interceptor.post_delete_backup_plan(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_management_server_with_metadata( + resp, _ = self._interceptor.post_delete_backup_plan_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -5071,24 +6150,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_management_server", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "DeleteManagementServer", + "rpcName": "DeleteBackupPlan", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchBackupPlanAssociationsForResourceType( - _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, - BackupDRRestStub, + class _DeleteBackupPlanAssociation( + _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, BackupDRRestStub ): def __hash__(self): - return hash( - "BackupDRRestTransport.FetchBackupPlanAssociationsForResourceType" - ) + return hash("BackupDRRestTransport.DeleteBackupPlanAssociation") @staticmethod def _get_response( @@ -5114,20 +6190,19 @@ def _get_response( def __call__( self, - request: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + request: backupplanassociation.DeleteBackupPlanAssociationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: - r"""Call the fetch backup plan - associations for resource type method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the delete backup plan + association method over HTTP. Args: - request (~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest): - The request object. Request for the - FetchBackupPlanAssociationsForResourceType - method. + request (~.backupplanassociation.DeleteBackupPlanAssociationRequest): + The request object. Request message for deleting a backup + plan association. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5137,25 +6212,23 @@ def __call__( be of type `bytes`. Returns: - ~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: - Response for the - FetchBackupPlanAssociationsForResourceType - method. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType._get_http_options() - request, metadata = ( - self._interceptor.pre_fetch_backup_plan_associations_for_resource_type( - request, metadata - ) + http_options = _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_delete_backup_plan_association( + request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, - "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseDeleteBackupPlanAssociation, + "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5179,17 +6252,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchBackupPlanAssociationsForResourceType", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackupPlanAssociation", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "FetchBackupPlanAssociationsForResourceType", + "rpcName": "DeleteBackupPlanAssociation", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._FetchBackupPlanAssociationsForResourceType._get_response( + response = BackupDRRestTransport._DeleteBackupPlanAssociation._get_response( self._host, metadata, query_params, @@ -5204,21 +6277,13 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - pb_resp = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.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_fetch_backup_plan_associations_for_resource_type( - resp - ) - ) + resp = self._interceptor.post_delete_backup_plan_association(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_fetch_backup_plan_associations_for_resource_type_with_metadata( + self._interceptor.post_delete_backup_plan_association_with_metadata( resp, response_metadata ) ) @@ -5226,9 +6291,7 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -5237,21 +6300,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_backup_plan_associations_for_resource_type", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan_association", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "FetchBackupPlanAssociationsForResourceType", + "rpcName": "DeleteBackupPlanAssociation", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchBackupsForResourceType( - _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, BackupDRRestStub + class _DeleteBackupVault( + _BaseBackupDRRestTransport._BaseDeleteBackupVault, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.FetchBackupsForResourceType") + return hash("BackupDRRestTransport.DeleteBackupVault") @staticmethod def _get_response( @@ -5277,44 +6340,45 @@ def _get_response( def __call__( self, - request: backupvault.FetchBackupsForResourceTypeRequest, + request: backupvault.DeleteBackupVaultRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.FetchBackupsForResourceTypeResponse: - r"""Call the fetch backups for - resource type method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the delete backup vault method over HTTP. - Args: - request (~.backupvault.FetchBackupsForResourceTypeRequest): - The request object. Request for the - FetchBackupsForResourceType method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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 (~.backupvault.DeleteBackupVaultRequest): + The request object. Message for deleting a BackupVault. + 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: - ~.backupvault.FetchBackupsForResourceTypeResponse: - Response for the - FetchBackupsForResourceType method. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType._get_http_options() - request, metadata = self._interceptor.pre_fetch_backups_for_resource_type( + http_options = ( + _BaseBackupDRRestTransport._BaseDeleteBackupVault._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_backup_vault( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, - "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseDeleteBackupVault, + "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5338,17 +6402,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchBackupsForResourceType", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteBackupVault", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "FetchBackupsForResourceType", + "rpcName": "DeleteBackupVault", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._FetchBackupsForResourceType._get_response( + response = BackupDRRestTransport._DeleteBackupVault._get_response( self._host, metadata, query_params, @@ -5363,27 +6427,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.FetchBackupsForResourceTypeResponse() - pb_resp = backupvault.FetchBackupsForResourceTypeResponse.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_fetch_backups_for_resource_type(resp) + resp = self._interceptor.post_delete_backup_vault(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_fetch_backups_for_resource_type_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_delete_backup_vault_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - backupvault.FetchBackupsForResourceTypeResponse.to_json( - response - ) - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -5392,24 +6448,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_backups_for_resource_type", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_vault", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "FetchBackupsForResourceType", + "rpcName": "DeleteBackupVault", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchDataSourceReferencesForResourceType( - _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, - BackupDRRestStub, + class _DeleteManagementServer( + _BaseBackupDRRestTransport._BaseDeleteManagementServer, BackupDRRestStub ): def __hash__(self): - return hash( - "BackupDRRestTransport.FetchDataSourceReferencesForResourceType" - ) + return hash("BackupDRRestTransport.DeleteManagementServer") @staticmethod def _get_response( @@ -5435,48 +6488,44 @@ def _get_response( def __call__( self, - request: datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, + request: backupdr.DeleteManagementServerRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: - r"""Call the fetch data source - references for resource type method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the delete management server method over HTTP. - Args: - request (~.datasourcereference.FetchDataSourceReferencesForResourceTypeRequest): - The request object. Request for the - FetchDataSourceReferencesForResourceType - method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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 (~.backupdr.DeleteManagementServerRequest): + The request object. Request message for deleting a + management server instance. + 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: - ~.datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: - Response for the - FetchDataSourceReferencesForResourceType - method. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType._get_http_options() - request, metadata = ( - self._interceptor.pre_fetch_data_source_references_for_resource_type( - request, metadata - ) + http_options = _BaseBackupDRRestTransport._BaseDeleteManagementServer._get_http_options() + request, metadata = self._interceptor.pre_delete_management_server( + request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, - "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseDeleteManagementServer, + "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5500,17 +6549,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchDataSourceReferencesForResourceType", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteManagementServer", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "FetchDataSourceReferencesForResourceType", + "rpcName": "DeleteManagementServer", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._FetchDataSourceReferencesForResourceType._get_response( + response = BackupDRRestTransport._DeleteManagementServer._get_response( self._host, metadata, query_params, @@ -5525,35 +6574,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() - ) - pb_resp = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.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_fetch_data_source_references_for_resource_type( - resp - ) - ) + resp = self._interceptor.post_delete_management_server(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_fetch_data_source_references_for_resource_type_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_delete_management_server_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -5562,21 +6595,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_data_source_references_for_resource_type", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_management_server", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "FetchDataSourceReferencesForResourceType", + "rpcName": "DeleteManagementServer", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchUsableBackupVaults( - _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, BackupDRRestStub + class _DeleteRestoreTemplate( + _BaseBackupDRRestTransport._BaseDeleteRestoreTemplate, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.FetchUsableBackupVaults") + return hash("BackupDRRestTransport.DeleteRestoreTemplate") @staticmethod def _get_response( @@ -5602,44 +6635,44 @@ def _get_response( def __call__( self, - request: backupvault.FetchUsableBackupVaultsRequest, + request: restore_template.DeleteRestoreTemplateRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.FetchUsableBackupVaultsResponse: - r"""Call the fetch usable backup - vaults method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the delete restore template method over HTTP. - Args: - request (~.backupvault.FetchUsableBackupVaultsRequest): - The request object. Request message for fetching usable - BackupVaults. - 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 (~.restore_template.DeleteRestoreTemplateRequest): + The request object. Request message for deleting a + RestoreTemplate instance. + 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: - ~.backupvault.FetchUsableBackupVaultsResponse: - Response message for fetching usable - BackupVaults. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults._get_http_options() - request, metadata = self._interceptor.pre_fetch_usable_backup_vaults( + http_options = _BaseBackupDRRestTransport._BaseDeleteRestoreTemplate._get_http_options() + request, metadata = self._interceptor.pre_delete_restore_template( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, - "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseDeleteRestoreTemplate, + "_BaseDeleteRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5663,17 +6696,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchUsableBackupVaults", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteRestoreTemplate", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "FetchUsableBackupVaults", + "rpcName": "DeleteRestoreTemplate", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._FetchUsableBackupVaults._get_response( + response = BackupDRRestTransport._DeleteRestoreTemplate._get_response( self._host, metadata, query_params, @@ -5688,23 +6721,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.FetchUsableBackupVaultsResponse() - pb_resp = backupvault.FetchUsableBackupVaultsResponse.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_fetch_usable_backup_vaults(resp) + resp = self._interceptor.post_delete_restore_template(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_usable_backup_vaults_with_metadata( + resp, _ = self._interceptor.post_delete_restore_template_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - backupvault.FetchUsableBackupVaultsResponse.to_json(response) - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -5713,21 +6742,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_usable_backup_vaults", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_restore_template", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "FetchUsableBackupVaults", + "rpcName": "DeleteRestoreTemplate", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetAutoProtectionPolicy( - _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy, BackupDRRestStub + class _DeleteRestoreVerificationPlan( + _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlan, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetAutoProtectionPolicy") + return hash("BackupDRRestTransport.DeleteRestoreVerificationPlan") @staticmethod def _get_response( @@ -5753,19 +6782,19 @@ def _get_response( def __call__( self, - request: autoprotectionpolicy.GetAutoProtectionPolicyRequest, + request: restore_verification_plan.DeleteRestoreVerificationPlanRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autoprotectionpolicy.AutoProtectionPolicy: - r"""Call the get auto protection - policy method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the delete restore + verification plan method over HTTP. Args: - request (~.autoprotectionpolicy.GetAutoProtectionPolicyRequest): - The request object. Request message for getting an - AutoProtectionPolicy. + request (~.restore_verification_plan.DeleteRestoreVerificationPlanRequest): + The request object. The request message for deleting a + ``RestoreVerificationPlan``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5775,28 +6804,23 @@ def __call__( be of type `bytes`. Returns: - ~.autoprotectionpolicy.AutoProtectionPolicy: - An AutoprotectionPolicy is a policy - resource designed to automate backup - management, moving from manual - per-resource protection to a bulk - approach. The policy dynamically - discovers and applies a specified backup - plan to all eligible resources that - match its defined scope and criteria. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy._get_http_options() - request, metadata = self._interceptor.pre_get_auto_protection_policy( + http_options = _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlan._get_http_options() + request, metadata = self._interceptor.pre_delete_restore_verification_plan( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy, - "_BaseGetAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlan, + "_BaseDeleteRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5820,23 +6844,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetAutoProtectionPolicy", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteRestoreVerificationPlan", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetAutoProtectionPolicy", + "rpcName": "DeleteRestoreVerificationPlan", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetAutoProtectionPolicy._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + BackupDRRestTransport._DeleteRestoreVerificationPlan._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -5845,23 +6871,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = autoprotectionpolicy.AutoProtectionPolicy() - pb_resp = autoprotectionpolicy.AutoProtectionPolicy.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_auto_protection_policy(resp) + resp = self._interceptor.post_delete_restore_verification_plan(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_auto_protection_policy_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_delete_restore_verification_plan_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - autoprotectionpolicy.AutoProtectionPolicy.to_json(response) - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -5870,21 +6894,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_restore_verification_plan", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetAutoProtectionPolicy", + "rpcName": "DeleteRestoreVerificationPlan", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetAutoProtectionPolicyBinding( - _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding, BackupDRRestStub + class _DeleteRestoreVerificationPlanAssociation( + _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlanAssociation, + BackupDRRestStub, ): def __hash__(self): - return hash("BackupDRRestTransport.GetAutoProtectionPolicyBinding") + return hash( + "BackupDRRestTransport.DeleteRestoreVerificationPlanAssociation" + ) @staticmethod def _get_response( @@ -5910,19 +6937,19 @@ def _get_response( def __call__( self, - request: autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, + request: restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: - r"""Call the get auto protection - policy binding method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the delete restore + verification plan association method over HTTP. Args: - request (~.autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest): - The request object. Request message for getting an - AutoProtectionPolicyBinding. + request (~.restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest): + The request object. Request message for + DeleteRestoreVerificationPlanAssociation. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -5932,18 +6959,16 @@ def __call__( be of type `bytes`. Returns: - ~.autoprotectionpolicybinding.AutoProtectionPolicyBinding: - An AutoprotectionPolicyBinding (APPA) - acts as the bridge between an - AutoprotectionPolicy and the scope - (Project, Folder, or Organization) where - the policy should be applied. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlanAssociation._get_http_options() request, metadata = ( - self._interceptor.pre_get_auto_protection_policy_binding( + self._interceptor.pre_delete_restore_verification_plan_association( request, metadata ) ) @@ -5951,8 +6976,8 @@ def __call__( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding, - "_BaseGetAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseDeleteRestoreVerificationPlanAssociation, + "_BaseDeleteRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5976,25 +7001,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetAutoProtectionPolicyBinding", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.DeleteRestoreVerificationPlanAssociation", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetAutoProtectionPolicyBinding", + "rpcName": "DeleteRestoreVerificationPlanAssociation", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - BackupDRRestTransport._GetAutoProtectionPolicyBinding._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = BackupDRRestTransport._DeleteRestoreVerificationPlanAssociation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -6003,15 +7026,15 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = autoprotectionpolicybinding.AutoProtectionPolicyBinding() - pb_resp = autoprotectionpolicybinding.AutoProtectionPolicyBinding.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_auto_protection_policy_binding(resp) + resp = self._interceptor.post_delete_restore_verification_plan_association( + resp + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_get_auto_protection_policy_binding_with_metadata( + self._interceptor.post_delete_restore_verification_plan_association_with_metadata( resp, response_metadata ) ) @@ -6019,11 +7042,7 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - autoprotectionpolicybinding.AutoProtectionPolicyBinding.to_json( - response - ) - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -6032,19 +7051,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy_binding", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.delete_restore_verification_plan_association", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetAutoProtectionPolicyBinding", + "rpcName": "DeleteRestoreVerificationPlanAssociation", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBackup(_BaseBackupDRRestTransport._BaseGetBackup, BackupDRRestStub): + class _FetchBackupPlanAssociationsForResourceType( + _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, + BackupDRRestStub, + ): def __hash__(self): - return hash("BackupDRRestTransport.GetBackup") + return hash( + "BackupDRRestTransport.FetchBackupPlanAssociationsForResourceType" + ) @staticmethod def _get_response( @@ -6070,38 +7094,48 @@ def _get_response( def __call__( self, - request: backupvault.GetBackupRequest, + request: backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.Backup: - r"""Call the get backup method over HTTP. - - Args: - request (~.backupvault.GetBackupRequest): - The request object. Request message for getting a Backup. - 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`. + ) -> backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: + r"""Call the fetch backup plan + associations for resource type method over HTTP. + + Args: + request (~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest): + The request object. Request for the + FetchBackupPlanAssociationsForResourceType + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse: + Response for the + FetchBackupPlanAssociationsForResourceType + method. - Returns: - ~.backupvault.Backup: - Message describing a Backup object. """ - http_options = _BaseBackupDRRestTransport._BaseGetBackup._get_http_options() - request, metadata = self._interceptor.pre_get_backup(request, metadata) + http_options = _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_backup_plan_associations_for_resource_type( + request, metadata + ) + ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackup, - "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseFetchBackupPlanAssociationsForResourceType, + "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6125,17 +7159,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackup", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchBackupPlanAssociationsForResourceType", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackup", + "rpcName": "FetchBackupPlanAssociationsForResourceType", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackup._get_response( + response = BackupDRRestTransport._FetchBackupPlanAssociationsForResourceType._get_response( self._host, metadata, query_params, @@ -6150,21 +7184,31 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.Backup() - pb_resp = backupvault.Backup.pb(resp) + resp = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + pb_resp = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + resp + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup(resp) + resp = ( + self._interceptor.post_fetch_backup_plan_associations_for_resource_type( + resp + ) + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_fetch_backup_plan_associations_for_resource_type_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.Backup.to_json(response) + response_payload = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -6173,21 +7217,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_backup_plan_associations_for_resource_type", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackup", + "rpcName": "FetchBackupPlanAssociationsForResourceType", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBackupPlan( - _BaseBackupDRRestTransport._BaseGetBackupPlan, BackupDRRestStub + class _FetchBackupsForResourceType( + _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetBackupPlan") + return hash("BackupDRRestTransport.FetchBackupsForResourceType") @staticmethod def _get_response( @@ -6213,45 +7257,44 @@ def _get_response( def __call__( self, - request: backupplan.GetBackupPlanRequest, + request: backupvault.FetchBackupsForResourceTypeRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplan.BackupPlan: - r"""Call the get backup plan method over HTTP. + ) -> backupvault.FetchBackupsForResourceTypeResponse: + r"""Call the fetch backups for + resource type method over HTTP. - Args: - request (~.backupplan.GetBackupPlanRequest): - The request object. The request message for getting a ``BackupPlan``. - 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 (~.backupvault.FetchBackupsForResourceTypeRequest): + The request object. Request for the + FetchBackupsForResourceType method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: - ~.backupplan.BackupPlan: - A ``BackupPlan`` specifies some common fields, such as - ``description`` as well as one or more ``BackupRule`` - messages. Each ``BackupRule`` has a retention policy and - defines a schedule by which the system is to perform - backup workloads. + Returns: + ~.backupvault.FetchBackupsForResourceTypeResponse: + Response for the + FetchBackupsForResourceType method. """ - http_options = ( - _BaseBackupDRRestTransport._BaseGetBackupPlan._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType._get_http_options() + request, metadata = self._interceptor.pre_fetch_backups_for_resource_type( + request, metadata ) - request, metadata = self._interceptor.pre_get_backup_plan(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackupPlan, - "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseFetchBackupsForResourceType, + "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6275,17 +7318,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupPlan", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchBackupsForResourceType", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackupPlan", + "rpcName": "FetchBackupsForResourceType", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackupPlan._get_response( + response = BackupDRRestTransport._FetchBackupsForResourceType._get_response( self._host, metadata, query_params, @@ -6300,21 +7343,27 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplan.BackupPlan() - pb_resp = backupplan.BackupPlan.pb(resp) + resp = backupvault.FetchBackupsForResourceTypeResponse() + pb_resp = backupvault.FetchBackupsForResourceTypeResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup_plan(resp) + resp = self._interceptor.post_fetch_backups_for_resource_type(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_plan_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_fetch_backups_for_resource_type_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupplan.BackupPlan.to_json(response) + response_payload = ( + backupvault.FetchBackupsForResourceTypeResponse.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -6323,21 +7372,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_backups_for_resource_type", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackupPlan", + "rpcName": "FetchBackupsForResourceType", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBackupPlanAssociation( - _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, BackupDRRestStub + class _FetchDataSourceReferencesForResourceType( + _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, + BackupDRRestStub, ): def __hash__(self): - return hash("BackupDRRestTransport.GetBackupPlanAssociation") + return hash( + "BackupDRRestTransport.FetchDataSourceReferencesForResourceType" + ) @staticmethod def _get_response( @@ -6363,19 +7415,20 @@ def _get_response( def __call__( self, - request: backupplanassociation.GetBackupPlanAssociationRequest, + request: datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplanassociation.BackupPlanAssociation: - r"""Call the get backup plan - association method over HTTP. + ) -> datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: + r"""Call the fetch data source + references for resource type method over HTTP. Args: - request (~.backupplanassociation.GetBackupPlanAssociationRequest): - The request object. Request message for getting a - BackupPlanAssociation resource. + request (~.datasourcereference.FetchDataSourceReferencesForResourceTypeRequest): + The request object. Request for the + FetchDataSourceReferencesForResourceType + method. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6385,24 +7438,25 @@ def __call__( be of type `bytes`. Returns: - ~.backupplanassociation.BackupPlanAssociation: - A BackupPlanAssociation represents a - single BackupPlanAssociation which - contains details like workload, backup - plan etc + ~.datasourcereference.FetchDataSourceReferencesForResourceTypeResponse: + Response for the + FetchDataSourceReferencesForResourceType + method. """ - http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation._get_http_options() - request, metadata = self._interceptor.pre_get_backup_plan_association( - request, metadata + http_options = _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_data_source_references_for_resource_type( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, - "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseFetchDataSourceReferencesForResourceType, + "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6426,17 +7480,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupPlanAssociation", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchDataSourceReferencesForResourceType", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackupPlanAssociation", + "rpcName": "FetchDataSourceReferencesForResourceType", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackupPlanAssociation._get_response( + response = BackupDRRestTransport._FetchDataSourceReferencesForResourceType._get_response( self._host, metadata, query_params, @@ -6451,22 +7505,34 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplanassociation.BackupPlanAssociation() - pb_resp = backupplanassociation.BackupPlanAssociation.pb(resp) + resp = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + pb_resp = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + resp + ) + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup_plan_association(resp) + resp = ( + self._interceptor.post_fetch_data_source_references_for_resource_type( + resp + ) + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_plan_association_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_fetch_data_source_references_for_resource_type_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - backupplanassociation.BackupPlanAssociation.to_json(response) + response_payload = datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.to_json( + response ) except: response_payload = None @@ -6476,21 +7542,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_association", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_data_source_references_for_resource_type", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackupPlanAssociation", + "rpcName": "FetchDataSourceReferencesForResourceType", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBackupPlanRevision( - _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, BackupDRRestStub + class _FetchUsableBackupVaults( + _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetBackupPlanRevision") + return hash("BackupDRRestTransport.FetchUsableBackupVaults") @staticmethod def _get_response( @@ -6516,43 +7582,44 @@ def _get_response( def __call__( self, - request: backupplan.GetBackupPlanRevisionRequest, + request: backupvault.FetchUsableBackupVaultsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplan.BackupPlanRevision: - r"""Call the get backup plan revision method over HTTP. - - Args: - request (~.backupplan.GetBackupPlanRevisionRequest): - The request object. The request message for getting a - ``BackupPlanRevision``. - 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`. + ) -> backupvault.FetchUsableBackupVaultsResponse: + r"""Call the fetch usable backup + vaults method over HTTP. - Returns: - ~.backupplan.BackupPlanRevision: - ``BackupPlanRevision`` represents a snapshot of a - ``BackupPlan`` at a point in time. + Args: + request (~.backupvault.FetchUsableBackupVaultsRequest): + The request object. Request message for fetching usable + BackupVaults. + 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: + ~.backupvault.FetchUsableBackupVaultsResponse: + Response message for fetching usable + BackupVaults. """ - http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanRevision._get_http_options() - request, metadata = self._interceptor.pre_get_backup_plan_revision( + http_options = _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults._get_http_options() + request, metadata = self._interceptor.pre_fetch_usable_backup_vaults( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, - "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseFetchUsableBackupVaults, + "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6576,17 +7643,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupPlanRevision", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.FetchUsableBackupVaults", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackupPlanRevision", + "rpcName": "FetchUsableBackupVaults", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackupPlanRevision._get_response( + response = BackupDRRestTransport._FetchUsableBackupVaults._get_response( self._host, metadata, query_params, @@ -6601,21 +7668,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplan.BackupPlanRevision() - pb_resp = backupplan.BackupPlanRevision.pb(resp) + resp = backupvault.FetchUsableBackupVaultsResponse() + pb_resp = backupvault.FetchUsableBackupVaultsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup_plan_revision(resp) + resp = self._interceptor.post_fetch_usable_backup_vaults(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_plan_revision_with_metadata( + resp, _ = self._interceptor.post_fetch_usable_backup_vaults_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupplan.BackupPlanRevision.to_json(response) + response_payload = ( + backupvault.FetchUsableBackupVaultsResponse.to_json(response) + ) except: response_payload = None http_response = { @@ -6624,21 +7693,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_revision", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.fetch_usable_backup_vaults", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackupPlanRevision", + "rpcName": "FetchUsableBackupVaults", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBackupVault( - _BaseBackupDRRestTransport._BaseGetBackupVault, BackupDRRestStub + class _GetAutoProtectionPolicy( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetBackupVault") + return hash("BackupDRRestTransport.GetAutoProtectionPolicy") @staticmethod def _get_response( @@ -6664,45 +7733,50 @@ def _get_response( def __call__( self, - request: backupvault.GetBackupVaultRequest, + request: autoprotectionpolicy.GetAutoProtectionPolicyRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.BackupVault: - r"""Call the get backup vault method over HTTP. + ) -> autoprotectionpolicy.AutoProtectionPolicy: + r"""Call the get auto protection + policy method over HTTP. - Args: - request (~.backupvault.GetBackupVaultRequest): - The request object. Request message for getting a - BackupVault. - 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 (~.autoprotectionpolicy.GetAutoProtectionPolicyRequest): + The request object. Request message for getting an + AutoProtectionPolicy. + 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: - ~.backupvault.BackupVault: - Message describing a BackupVault - object. + Returns: + ~.autoprotectionpolicy.AutoProtectionPolicy: + An AutoprotectionPolicy is a policy + resource designed to automate backup + management, moving from manual + per-resource protection to a bulk + approach. The policy dynamically + discovers and applies a specified backup + plan to all eligible resources that + match its defined scope and criteria. """ - http_options = ( - _BaseBackupDRRestTransport._BaseGetBackupVault._get_http_options() - ) - request, metadata = self._interceptor.pre_get_backup_vault( + http_options = _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy._get_http_options() + request, metadata = self._interceptor.pre_get_auto_protection_policy( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBackupVault, - "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicy, + "_BaseGetAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6726,17 +7800,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupVault", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetAutoProtectionPolicy", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackupVault", + "rpcName": "GetAutoProtectionPolicy", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBackupVault._get_response( + response = BackupDRRestTransport._GetAutoProtectionPolicy._get_response( self._host, metadata, query_params, @@ -6751,21 +7825,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.BackupVault() - pb_resp = backupvault.BackupVault.pb(resp) + resp = autoprotectionpolicy.AutoProtectionPolicy() + pb_resp = autoprotectionpolicy.AutoProtectionPolicy.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_backup_vault(resp) + resp = self._interceptor.post_get_auto_protection_policy(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_backup_vault_with_metadata( + resp, _ = self._interceptor.post_get_auto_protection_policy_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.BackupVault.to_json(response) + response_payload = ( + autoprotectionpolicy.AutoProtectionPolicy.to_json(response) + ) except: response_payload = None http_response = { @@ -6774,21 +7850,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_vault", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBackupVault", + "rpcName": "GetAutoProtectionPolicy", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetBindingMatchingResource( - _BaseBackupDRRestTransport._BaseGetBindingMatchingResource, BackupDRRestStub + class _GetAutoProtectionPolicyBinding( + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetBindingMatchingResource") + return hash("BackupDRRestTransport.GetAutoProtectionPolicyBinding") @staticmethod def _get_response( @@ -6814,19 +7890,19 @@ def _get_response( def __call__( self, - request: bindingmatchingresource.GetBindingMatchingResourceRequest, + request: autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> bindingmatchingresource.BindingMatchingResource: - r"""Call the get binding matching - resource method over HTTP. + ) -> autoprotectionpolicybinding.AutoProtectionPolicyBinding: + r"""Call the get auto protection + policy binding method over HTTP. Args: - request (~.bindingmatchingresource.GetBindingMatchingResourceRequest): - The request object. Request message for getting a - BindingMatchingResource. + request (~.autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest): + The request object. Request message for getting an + AutoProtectionPolicyBinding. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6836,23 +7912,27 @@ def __call__( be of type `bytes`. Returns: - ~.bindingmatchingresource.BindingMatchingResource: - BindingMatchingResource contains the - details of a resource that matches the - criteria of a binding. + ~.autoprotectionpolicybinding.AutoProtectionPolicyBinding: + An AutoprotectionPolicyBinding (APPA) + acts as the bridge between an + AutoprotectionPolicy and the scope + (Project, Folder, or Organization) where + the policy should be applied. """ - http_options = _BaseBackupDRRestTransport._BaseGetBindingMatchingResource._get_http_options() - request, metadata = self._interceptor.pre_get_binding_matching_resource( - request, metadata + http_options = _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding._get_http_options() + request, metadata = ( + self._interceptor.pre_get_auto_protection_policy_binding( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetBindingMatchingResource, - "_BaseGetBindingMatchingResource__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetAutoProtectionPolicyBinding, + "_BaseGetAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -6876,23 +7956,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBindingMatchingResource", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetAutoProtectionPolicyBinding", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBindingMatchingResource", + "rpcName": "GetAutoProtectionPolicyBinding", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetBindingMatchingResource._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + BackupDRRestTransport._GetAutoProtectionPolicyBinding._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -6901,15 +7983,15 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = bindingmatchingresource.BindingMatchingResource() - pb_resp = bindingmatchingresource.BindingMatchingResource.pb(resp) + resp = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + pb_resp = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_binding_matching_resource(resp) + resp = self._interceptor.post_get_auto_protection_policy_binding(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_get_binding_matching_resource_with_metadata( + self._interceptor.post_get_auto_protection_policy_binding_with_metadata( resp, response_metadata ) ) @@ -6918,7 +8000,7 @@ def __call__( ): # pragma: NO COVER try: response_payload = ( - bindingmatchingresource.BindingMatchingResource.to_json( + autoprotectionpolicybinding.AutoProtectionPolicyBinding.to_json( response ) ) @@ -6930,21 +8012,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_binding_matching_resource", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy_binding", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetBindingMatchingResource", + "rpcName": "GetAutoProtectionPolicyBinding", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetDataSource( - _BaseBackupDRRestTransport._BaseGetDataSource, BackupDRRestStub - ): + class _GetBackup(_BaseBackupDRRestTransport._BaseGetBackup, BackupDRRestStub): def __hash__(self): - return hash("BackupDRRestTransport.GetDataSource") + return hash("BackupDRRestTransport.GetBackup") @staticmethod def _get_response( @@ -6970,18 +8050,17 @@ def _get_response( def __call__( self, - request: backupvault.GetDataSourceRequest, + request: backupvault.GetBackupRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.DataSource: - r"""Call the get data source method over HTTP. + ) -> backupvault.Backup: + r"""Call the get backup method over HTTP. Args: - request (~.backupvault.GetDataSourceRequest): - The request object. Request message for getting a - DataSource instance. + request (~.backupvault.GetBackupRequest): + The request object. Request message for getting a Backup. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -6991,24 +8070,18 @@ def __call__( be of type `bytes`. Returns: - ~.backupvault.DataSource: - Message describing a DataSource - object. Datasource object used to - represent Datasource details for both - admin and basic view. - + ~.backupvault.Backup: + Message describing a Backup object. """ - http_options = ( - _BaseBackupDRRestTransport._BaseGetDataSource._get_http_options() - ) - request, metadata = self._interceptor.pre_get_data_source(request, metadata) + http_options = _BaseBackupDRRestTransport._BaseGetBackup._get_http_options() + request, metadata = self._interceptor.pre_get_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetDataSource, - "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetBackup, + "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7032,17 +8105,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetDataSource", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetDataSource", + "rpcName": "GetBackup", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetDataSource._get_response( + response = BackupDRRestTransport._GetBackup._get_response( self._host, metadata, query_params, @@ -7057,21 +8130,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.DataSource() - pb_resp = backupvault.DataSource.pb(resp) + resp = backupvault.Backup() + pb_resp = backupvault.Backup.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_data_source(resp) + resp = self._interceptor.post_get_backup(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_data_source_with_metadata( + 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 = backupvault.DataSource.to_json(response) + response_payload = backupvault.Backup.to_json(response) except: response_payload = None http_response = { @@ -7080,21 +8153,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_data_source", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetDataSource", + "rpcName": "GetBackup", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetDataSourceReference( - _BaseBackupDRRestTransport._BaseGetDataSourceReference, BackupDRRestStub + class _GetBackupPlan( + _BaseBackupDRRestTransport._BaseGetBackupPlan, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetDataSourceReference") + return hash("BackupDRRestTransport.GetBackupPlan") @staticmethod def _get_response( @@ -7120,18 +8193,17 @@ def _get_response( def __call__( self, - request: datasourcereference.GetDataSourceReferenceRequest, + request: backupplan.GetBackupPlanRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasourcereference.DataSourceReference: - r"""Call the get data source reference method over HTTP. + ) -> backupplan.BackupPlan: + r"""Call the get backup plan method over HTTP. Args: - request (~.datasourcereference.GetDataSourceReferenceRequest): - The request object. Request for the - GetDataSourceReference method. + request (~.backupplan.GetBackupPlanRequest): + The request object. The request message for getting a ``BackupPlan``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7141,22 +8213,25 @@ def __call__( be of type `bytes`. Returns: - ~.datasourcereference.DataSourceReference: - DataSourceReference is a reference to - a DataSource resource. + ~.backupplan.BackupPlan: + A ``BackupPlan`` specifies some common fields, such as + ``description`` as well as one or more ``BackupRule`` + messages. Each ``BackupRule`` has a retention policy and + defines a schedule by which the system is to perform + backup workloads. """ - http_options = _BaseBackupDRRestTransport._BaseGetDataSourceReference._get_http_options() - request, metadata = self._interceptor.pre_get_data_source_reference( - request, metadata + http_options = ( + _BaseBackupDRRestTransport._BaseGetBackupPlan._get_http_options() ) + request, metadata = self._interceptor.pre_get_backup_plan(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetDataSourceReference, - "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetBackupPlan, + "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7180,17 +8255,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetDataSourceReference", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupPlan", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetDataSourceReference", + "rpcName": "GetBackupPlan", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetDataSourceReference._get_response( + response = BackupDRRestTransport._GetBackupPlan._get_response( self._host, metadata, query_params, @@ -7205,23 +8280,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = datasourcereference.DataSourceReference() - pb_resp = datasourcereference.DataSourceReference.pb(resp) + resp = backupplan.BackupPlan() + pb_resp = backupplan.BackupPlan.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_data_source_reference(resp) + resp = self._interceptor.post_get_backup_plan(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_data_source_reference_with_metadata( + resp, _ = self._interceptor.post_get_backup_plan_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = datasourcereference.DataSourceReference.to_json( - response - ) + response_payload = backupplan.BackupPlan.to_json(response) except: response_payload = None http_response = { @@ -7230,21 +8303,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_data_source_reference", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetDataSourceReference", + "rpcName": "GetBackupPlan", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetManagementServer( - _BaseBackupDRRestTransport._BaseGetManagementServer, BackupDRRestStub + class _GetBackupPlanAssociation( + _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.GetManagementServer") + return hash("BackupDRRestTransport.GetBackupPlanAssociation") @staticmethod def _get_response( @@ -7270,45 +8343,46 @@ def _get_response( def __call__( self, - request: backupdr.GetManagementServerRequest, + request: backupplanassociation.GetBackupPlanAssociationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupdr.ManagementServer: - r"""Call the get management server method over HTTP. + ) -> backupplanassociation.BackupPlanAssociation: + r"""Call the get backup plan + association method over HTTP. - Args: - request (~.backupdr.GetManagementServerRequest): - The request object. Request message for getting a - management server instance. - 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 (~.backupplanassociation.GetBackupPlanAssociationRequest): + The request object. Request message for getting a + BackupPlanAssociation resource. + 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: - ~.backupdr.ManagementServer: - ManagementServer describes a single - BackupDR ManagementServer instance. + Returns: + ~.backupplanassociation.BackupPlanAssociation: + A BackupPlanAssociation represents a + single BackupPlanAssociation which + contains details like workload, backup + plan etc """ - http_options = ( - _BaseBackupDRRestTransport._BaseGetManagementServer._get_http_options() - ) - request, metadata = self._interceptor.pre_get_management_server( + http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_get_backup_plan_association( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseGetManagementServer, - "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetBackupPlanAssociation, + "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7332,17 +8406,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetManagementServer", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupPlanAssociation", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetManagementServer", + "rpcName": "GetBackupPlanAssociation", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._GetManagementServer._get_response( + response = BackupDRRestTransport._GetBackupPlanAssociation._get_response( self._host, metadata, query_params, @@ -7357,21 +8431,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupdr.ManagementServer() - pb_resp = backupdr.ManagementServer.pb(resp) + resp = backupplanassociation.BackupPlanAssociation() + pb_resp = backupplanassociation.BackupPlanAssociation.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_management_server(resp) + resp = self._interceptor.post_get_backup_plan_association(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_management_server_with_metadata( + resp, _ = self._interceptor.post_get_backup_plan_association_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupdr.ManagementServer.to_json(response) + response_payload = ( + backupplanassociation.BackupPlanAssociation.to_json(response) + ) except: response_payload = None http_response = { @@ -7380,21 +8456,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_management_server", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_association", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "GetManagementServer", + "rpcName": "GetBackupPlanAssociation", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _InitializeService( - _BaseBackupDRRestTransport._BaseInitializeService, BackupDRRestStub + class _GetBackupPlanRevision( + _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.InitializeService") + return hash("BackupDRRestTransport.GetBackupPlanRevision") @staticmethod def _get_response( @@ -7415,24 +8491,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: backupdr.InitializeServiceRequest, + request: backupplan.GetBackupPlanRevisionRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the initialize service method over HTTP. + ) -> backupplan.BackupPlanRevision: + r"""Call the get backup plan revision method over HTTP. Args: - request (~.backupdr.InitializeServiceRequest): - The request object. Request message for initializing the - service. + request (~.backupplan.GetBackupPlanRevisionRequest): + The request object. The request message for getting a + ``BackupPlanRevision``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7442,25 +8517,22 @@ 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. + ~.backupplan.BackupPlanRevision: + ``BackupPlanRevision`` represents a snapshot of a + ``BackupPlan`` at a point in time. """ - http_options = ( - _BaseBackupDRRestTransport._BaseInitializeService._get_http_options() - ) - request, metadata = self._interceptor.pre_initialize_service( + http_options = _BaseBackupDRRestTransport._BaseGetBackupPlanRevision._get_http_options() + request, metadata = self._interceptor.pre_get_backup_plan_revision( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseInitializeService, - "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetBackupPlanRevision, + "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7484,24 +8556,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.InitializeService", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupPlanRevision", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "InitializeService", + "rpcName": "GetBackupPlanRevision", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._InitializeService._get_response( + response = BackupDRRestTransport._GetBackupPlanRevision._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -7510,19 +8581,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 = backupplan.BackupPlanRevision() + pb_resp = backupplan.BackupPlanRevision.pb(resp) - resp = self._interceptor.post_initialize_service(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_plan_revision(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_initialize_service_with_metadata( + resp, _ = self._interceptor.post_get_backup_plan_revision_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 = backupplan.BackupPlanRevision.to_json(response) except: response_payload = None http_response = { @@ -7531,24 +8604,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.initialize_service", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_revision", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "InitializeService", + "rpcName": "GetBackupPlanRevision", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _InitiateDeleteAutoProtectionPolicyBinding( - _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding, - BackupDRRestStub, + class _GetBackupVault( + _BaseBackupDRRestTransport._BaseGetBackupVault, BackupDRRestStub ): def __hash__(self): - return hash( - "BackupDRRestTransport.InitiateDeleteAutoProtectionPolicyBinding" - ) + return hash("BackupDRRestTransport.GetBackupVault") @staticmethod def _get_response( @@ -7569,53 +8639,50 @@ 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: autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + request: backupvault.GetBackupVaultRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the initiate delete auto - protection policy binding method over HTTP. + ) -> backupvault.BackupVault: + r"""Call the get backup vault method over HTTP. - Args: - request (~.autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest): - The request object. Request message for initiating delete - of an AutoProtectionPolicyBinding. - 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 (~.backupvault.GetBackupVaultRequest): + The request object. Request message for getting a + BackupVault. + 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. + Returns: + ~.backupvault.BackupVault: + Message describing a BackupVault + object. """ - http_options = _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding._get_http_options() - request, metadata = ( - self._interceptor.pre_initiate_delete_auto_protection_policy_binding( - request, metadata - ) + http_options = ( + _BaseBackupDRRestTransport._BaseGetBackupVault._get_http_options() + ) + request, metadata = self._interceptor.pre_get_backup_vault( + request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding, - "_BaseInitiateDeleteAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetBackupVault, + "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7639,24 +8706,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.InitiateDeleteAutoProtectionPolicyBinding", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBackupVault", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "InitiateDeleteAutoProtectionPolicyBinding", + "rpcName": "GetBackupVault", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._InitiateDeleteAutoProtectionPolicyBinding._get_response( + response = BackupDRRestTransport._GetBackupVault._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -7665,25 +8731,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 = backupvault.BackupVault() + pb_resp = backupvault.BackupVault.pb(resp) - resp = ( - self._interceptor.post_initiate_delete_auto_protection_policy_binding( - resp - ) - ) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_vault(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_initiate_delete_auto_protection_policy_binding_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_get_backup_vault_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 = backupvault.BackupVault.to_json(response) except: response_payload = None http_response = { @@ -7692,22 +8754,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.initiate_delete_auto_protection_policy_binding", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_backup_vault", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "InitiateDeleteAutoProtectionPolicyBinding", + "rpcName": "GetBackupVault", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListAppliedAutoProtectionPolicies( - _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies, - BackupDRRestStub, + class _GetBindingMatchingResource( + _BaseBackupDRRestTransport._BaseGetBindingMatchingResource, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListAppliedAutoProtectionPolicies") + return hash("BackupDRRestTransport.GetBindingMatchingResource") @staticmethod def _get_response( @@ -7733,19 +8794,19 @@ def _get_response( def __call__( self, - request: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + request: bindingmatchingresource.GetBindingMatchingResourceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: - r"""Call the list applied auto - protection policies method over HTTP. + ) -> bindingmatchingresource.BindingMatchingResource: + r"""Call the get binding matching + resource method over HTTP. Args: - request (~.appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest): - The request object. Request message for listing - AppliedAutoProtectionPolicies. + request (~.bindingmatchingresource.GetBindingMatchingResourceRequest): + The request object. Request message for getting a + BindingMatchingResource. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -7755,24 +8816,23 @@ def __call__( be of type `bytes`. Returns: - ~.appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: - Response message for - ListAppliedAutoProtectionPolicies. + ~.bindingmatchingresource.BindingMatchingResource: + BindingMatchingResource contains the + details of a resource that matches the + criteria of a binding. """ - http_options = _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies._get_http_options() - request, metadata = ( - self._interceptor.pre_list_applied_auto_protection_policies( - request, metadata - ) + http_options = _BaseBackupDRRestTransport._BaseGetBindingMatchingResource._get_http_options() + request, metadata = self._interceptor.pre_get_binding_matching_resource( + request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies, - "_BaseListAppliedAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetBindingMatchingResource, + "_BaseGetBindingMatchingResource__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7796,25 +8856,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListAppliedAutoProtectionPolicies", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetBindingMatchingResource", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListAppliedAutoProtectionPolicies", + "rpcName": "GetBindingMatchingResource", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - BackupDRRestTransport._ListAppliedAutoProtectionPolicies._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = BackupDRRestTransport._GetBindingMatchingResource._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -7823,19 +8881,15 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() - ) - pb_resp = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( - resp - ) + resp = bindingmatchingresource.BindingMatchingResource() + pb_resp = bindingmatchingresource.BindingMatchingResource.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_applied_auto_protection_policies(resp) + resp = self._interceptor.post_get_binding_matching_resource(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_list_applied_auto_protection_policies_with_metadata( + self._interceptor.post_get_binding_matching_resource_with_metadata( resp, response_metadata ) ) @@ -7843,8 +8897,10 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.to_json( - response + response_payload = ( + bindingmatchingresource.BindingMatchingResource.to_json( + response + ) ) except: response_payload = None @@ -7854,21 +8910,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_applied_auto_protection_policies", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_binding_matching_resource", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListAppliedAutoProtectionPolicies", + "rpcName": "GetBindingMatchingResource", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListAutoProtectionPolicies( - _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies, BackupDRRestStub + class _GetDataSource( + _BaseBackupDRRestTransport._BaseGetDataSource, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListAutoProtectionPolicies") + return hash("BackupDRRestTransport.GetDataSource") @staticmethod def _get_response( @@ -7894,44 +8950,45 @@ def _get_response( def __call__( self, - request: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + request: backupvault.GetDataSourceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autoprotectionpolicy.ListAutoProtectionPoliciesResponse: - r"""Call the list auto protection - policies method over HTTP. + ) -> backupvault.DataSource: + r"""Call the get data source method over HTTP. - Args: - request (~.autoprotectionpolicy.ListAutoProtectionPoliciesRequest): - The request object. Request message for - ListAutoProtectionPolicies. - 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 (~.backupvault.GetDataSourceRequest): + The request object. Request message for getting a + DataSource instance. + 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: - ~.autoprotectionpolicy.ListAutoProtectionPoliciesResponse: - Response message for - ListAutoProtectionPolicies. + Returns: + ~.backupvault.DataSource: + Message describing a DataSource + object. Datasource object used to + represent Datasource details for both + admin and basic view. """ - http_options = _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies._get_http_options() - request, metadata = self._interceptor.pre_list_auto_protection_policies( - request, metadata + http_options = ( + _BaseBackupDRRestTransport._BaseGetDataSource._get_http_options() ) + request, metadata = self._interceptor.pre_get_data_source(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies, - "_BaseListAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetDataSource, + "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -7955,17 +9012,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListAutoProtectionPolicies", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetDataSource", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListAutoProtectionPolicies", + "rpcName": "GetDataSource", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListAutoProtectionPolicies._get_response( + response = BackupDRRestTransport._GetDataSource._get_response( self._host, metadata, query_params, @@ -7980,27 +9037,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() - pb_resp = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb(resp) + resp = backupvault.DataSource() + pb_resp = backupvault.DataSource.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_auto_protection_policies(resp) + resp = self._interceptor.post_get_data_source(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_list_auto_protection_policies_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_get_data_source_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse.to_json( - response - ) - ) + response_payload = backupvault.DataSource.to_json(response) except: response_payload = None http_response = { @@ -8009,22 +9060,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policies", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.get_data_source", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListAutoProtectionPolicies", + "rpcName": "GetDataSource", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListAutoProtectionPolicyBindings( - _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings, - BackupDRRestStub, + class _GetDataSourceReference( + _BaseBackupDRRestTransport._BaseGetDataSourceReference, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListAutoProtectionPolicyBindings") + return hash("BackupDRRestTransport.GetDataSourceReference") @staticmethod def _get_response( @@ -8050,46 +9100,43 @@ def _get_response( def __call__( self, - request: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + request: datasourcereference.GetDataSourceReferenceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: - r"""Call the list auto protection - policy bindings method over HTTP. + ) -> datasourcereference.DataSourceReference: + r"""Call the get data source reference method over HTTP. - Args: - request (~.autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest): - The request object. Request message for - ListAutoProtectionPolicyBindings. - 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 (~.datasourcereference.GetDataSourceReferenceRequest): + The request object. Request for the + GetDataSourceReference method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: - ~.autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: - Response message for - ListAutoProtectionPolicyBindings. + Returns: + ~.datasourcereference.DataSourceReference: + DataSourceReference is a reference to + a DataSource resource. """ - http_options = _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings._get_http_options() - request, metadata = ( - self._interceptor.pre_list_auto_protection_policy_bindings( - request, metadata - ) + http_options = _BaseBackupDRRestTransport._BaseGetDataSourceReference._get_http_options() + request, metadata = self._interceptor.pre_get_data_source_reference( + request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings, - "_BaseListAutoProtectionPolicyBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseGetDataSourceReference, + "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -8113,10 +9160,2480 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListAutoProtectionPolicyBindings", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.GetDataSourceReference", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetDataSourceReference", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetDataSourceReference._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 = datasourcereference.DataSourceReference() + pb_resp = datasourcereference.DataSourceReference.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_data_source_reference(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_data_source_reference_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = datasourcereference.DataSourceReference.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.backupdr_v1beta.BackupDRClient.get_data_source_reference", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetDataSourceReference", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetManagementServer( + _BaseBackupDRRestTransport._BaseGetManagementServer, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetManagementServer") + + @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: backupdr.GetManagementServerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupdr.ManagementServer: + r"""Call the get management server method over HTTP. + + Args: + request (~.backupdr.GetManagementServerRequest): + The request object. Request message for getting a + management server instance. + 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: + ~.backupdr.ManagementServer: + ManagementServer describes a single + BackupDR ManagementServer instance. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetManagementServer._get_http_options() + ) + request, metadata = self._interceptor.pre_get_management_server( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetManagementServer, + "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.GetManagementServer", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetManagementServer", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetManagementServer._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 = backupdr.ManagementServer() + pb_resp = backupdr.ManagementServer.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_management_server(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_management_server_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupdr.ManagementServer.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.backupdr_v1beta.BackupDRClient.get_management_server", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetManagementServer", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRestoreTemplate( + _BaseBackupDRRestTransport._BaseGetRestoreTemplate, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetRestoreTemplate") + + @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: restore_template.GetRestoreTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> restore_template.RestoreTemplate: + r"""Call the get restore template method over HTTP. + + Args: + request (~.restore_template.GetRestoreTemplateRequest): + The request object. Request message for getting a + RestoreTemplate instance. + 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: + ~.restore_template.RestoreTemplate: + A ``RestoreTemplate`` encapsulates DR readiness + configurations for validating backups. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseGetRestoreTemplate._get_http_options() + ) + request, metadata = self._interceptor.pre_get_restore_template( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetRestoreTemplate, + "_BaseGetRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.GetRestoreTemplate", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetRestoreTemplate", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetRestoreTemplate._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 = restore_template.RestoreTemplate() + pb_resp = restore_template.RestoreTemplate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_restore_template(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_restore_template_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = restore_template.RestoreTemplate.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.backupdr_v1beta.BackupDRClient.get_restore_template", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetRestoreTemplate", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRestoreTemplateExecution( + _BaseBackupDRRestTransport._BaseGetRestoreTemplateExecution, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetRestoreTemplateExecution") + + @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: restore_template_execution.GetRestoreTemplateExecutionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> restore_template_execution.RestoreTemplateExecution: + r"""Call the get restore template + execution method over HTTP. + + Args: + request (~.restore_template_execution.GetRestoreTemplateExecutionRequest): + The request object. Request message for getting a + RestoreTemplateExecution instance. + 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: + ~.restore_template_execution.RestoreTemplateExecution: + A ``RestoreTemplateExecution`` represents a single + historical or active execution run. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetRestoreTemplateExecution._get_http_options() + request, metadata = self._interceptor.pre_get_restore_template_execution( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetRestoreTemplateExecution, + "_BaseGetRestoreTemplateExecution__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.GetRestoreTemplateExecution", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetRestoreTemplateExecution", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetRestoreTemplateExecution._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 = restore_template_execution.RestoreTemplateExecution() + pb_resp = restore_template_execution.RestoreTemplateExecution.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_restore_template_execution(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_restore_template_execution_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + restore_template_execution.RestoreTemplateExecution.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.backupdr_v1beta.BackupDRClient.get_restore_template_execution", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetRestoreTemplateExecution", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRestoreVerificationPlan( + _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlan, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetRestoreVerificationPlan") + + @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: restore_verification_plan.GetRestoreVerificationPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> restore_verification_plan.RestoreVerificationPlan: + r"""Call the get restore verification + plan method over HTTP. + + Args: + request (~.restore_verification_plan.GetRestoreVerificationPlanRequest): + The request object. The request message for getting a + ``RestoreVerificationPlan``. + 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: + ~.restore_verification_plan.RestoreVerificationPlan: + A ``RestoreVerificationPlan`` specifies the scheduling + and clean-up template for automated restore + verification. It contains a ``schedule`` to dictate when + the verifications should run, and a + ``RestoreVerificationCleanupRule`` for post-verification + resource deletion. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlan._get_http_options() + request, metadata = self._interceptor.pre_get_restore_verification_plan( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlan, + "_BaseGetRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.GetRestoreVerificationPlan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetRestoreVerificationPlan", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetRestoreVerificationPlan._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 = restore_verification_plan.RestoreVerificationPlan() + pb_resp = restore_verification_plan.RestoreVerificationPlan.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_restore_verification_plan(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_restore_verification_plan_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + restore_verification_plan.RestoreVerificationPlan.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.backupdr_v1beta.BackupDRClient.get_restore_verification_plan", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetRestoreVerificationPlan", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRestoreVerificationPlanAssociation( + _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlanAssociation, + BackupDRRestStub, + ): + def __hash__(self): + return hash("BackupDRRestTransport.GetRestoreVerificationPlanAssociation") + + @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: restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> restore_verification_plan_association.RestoreVerificationPlanAssociation: + r"""Call the get restore verification + plan association method over HTTP. + + Args: + request (~.restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest): + The request object. Request message for + GetRestoreVerificationPlanAssociation. + 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: + ~.restore_verification_plan_association.RestoreVerificationPlanAssociation: + A ``RestoreVerificationPlanAssociation`` binds a + specific workload to a ``RestoreVerificationPlan``. + + """ + + http_options = _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlanAssociation._get_http_options() + request, metadata = ( + self._interceptor.pre_get_restore_verification_plan_association( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseGetRestoreVerificationPlanAssociation, + "_BaseGetRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.GetRestoreVerificationPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetRestoreVerificationPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._GetRestoreVerificationPlanAssociation._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 = restore_verification_plan_association.RestoreVerificationPlanAssociation() + pb_resp = restore_verification_plan_association.RestoreVerificationPlanAssociation.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_restore_verification_plan_association( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_restore_verification_plan_association_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = restore_verification_plan_association.RestoreVerificationPlanAssociation.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.backupdr_v1beta.BackupDRClient.get_restore_verification_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "GetRestoreVerificationPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _InitializeService( + _BaseBackupDRRestTransport._BaseInitializeService, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.InitializeService") + + @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: backupdr.InitializeServiceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the initialize service method over HTTP. + + Args: + request (~.backupdr.InitializeServiceRequest): + The request object. Request message for initializing the + service. + 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 = ( + _BaseBackupDRRestTransport._BaseInitializeService._get_http_options() + ) + request, metadata = self._interceptor.pre_initialize_service( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseInitializeService, + "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.InitializeService", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "InitializeService", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._InitializeService._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_initialize_service(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_initialize_service_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.backupdr_v1beta.BackupDRClient.initialize_service", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "InitializeService", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _InitiateDeleteAutoProtectionPolicyBinding( + _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding, + BackupDRRestStub, + ): + def __hash__(self): + return hash( + "BackupDRRestTransport.InitiateDeleteAutoProtectionPolicyBinding" + ) + + @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: autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the initiate delete auto + protection policy binding method over HTTP. + + Args: + request (~.autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest): + The request object. Request message for initiating delete + of an AutoProtectionPolicyBinding. + 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 = _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding._get_http_options() + request, metadata = ( + self._interceptor.pre_initiate_delete_auto_protection_policy_binding( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseInitiateDeleteAutoProtectionPolicyBinding, + "_BaseInitiateDeleteAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.InitiateDeleteAutoProtectionPolicyBinding", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "InitiateDeleteAutoProtectionPolicyBinding", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._InitiateDeleteAutoProtectionPolicyBinding._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_initiate_delete_auto_protection_policy_binding( + resp + ) + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_initiate_delete_auto_protection_policy_binding_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.backupdr_v1beta.BackupDRClient.initiate_delete_auto_protection_policy_binding", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "InitiateDeleteAutoProtectionPolicyBinding", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAppliedAutoProtectionPolicies( + _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies, + BackupDRRestStub, + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListAppliedAutoProtectionPolicies") + + @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: appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: + r"""Call the list applied auto + protection policies method over HTTP. + + Args: + request (~.appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest): + The request object. Request message for listing + AppliedAutoProtectionPolicies. + 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: + ~.appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse: + Response message for + ListAppliedAutoProtectionPolicies. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies._get_http_options() + request, metadata = ( + self._interceptor.pre_list_applied_auto_protection_policies( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListAppliedAutoProtectionPolicies, + "_BaseListAppliedAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListAppliedAutoProtectionPolicies", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAppliedAutoProtectionPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._ListAppliedAutoProtectionPolicies._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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + pb_resp = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_applied_auto_protection_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_applied_auto_protection_policies_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.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.backupdr_v1beta.BackupDRClient.list_applied_auto_protection_policies", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAppliedAutoProtectionPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAutoProtectionPolicies( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListAutoProtectionPolicies") + + @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: autoprotectionpolicy.ListAutoProtectionPoliciesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicy.ListAutoProtectionPoliciesResponse: + r"""Call the list auto protection + policies method over HTTP. + + Args: + request (~.autoprotectionpolicy.ListAutoProtectionPoliciesRequest): + The request object. Request message for + ListAutoProtectionPolicies. + 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: + ~.autoprotectionpolicy.ListAutoProtectionPoliciesResponse: + Response message for + ListAutoProtectionPolicies. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies._get_http_options() + request, metadata = self._interceptor.pre_list_auto_protection_policies( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicies, + "_BaseListAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListAutoProtectionPolicies", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAutoProtectionPolicies", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListAutoProtectionPolicies._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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + pb_resp = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_auto_protection_policies(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_auto_protection_policies_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse.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.backupdr_v1beta.BackupDRClient.list_auto_protection_policies", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAutoProtectionPolicies", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAutoProtectionPolicyBindings( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings, + BackupDRRestStub, + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListAutoProtectionPolicyBindings") + + @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: autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: + r"""Call the list auto protection + policy bindings method over HTTP. + + Args: + request (~.autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest): + The request object. Request message for + ListAutoProtectionPolicyBindings. + 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: + ~.autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse: + Response message for + ListAutoProtectionPolicyBindings. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings._get_http_options() + request, metadata = ( + self._interceptor.pre_list_auto_protection_policy_bindings( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListAutoProtectionPolicyBindings, + "_BaseListAutoProtectionPolicyBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListAutoProtectionPolicyBindings", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListAutoProtectionPolicyBindings", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + BackupDRRestTransport._ListAutoProtectionPolicyBindings._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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + pb_resp = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + resp + ) + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_auto_protection_policy_bindings(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_auto_protection_policy_bindings_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.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.backupdr_v1beta.BackupDRClient.list_auto_protection_policy_bindings", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", "rpcName": "ListAutoProtectionPolicyBindings", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackupPlanAssociations( + _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackupPlanAssociations") + + @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: backupplanassociation.ListBackupPlanAssociationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplanassociation.ListBackupPlanAssociationsResponse: + r"""Call the list backup plan + associations method over HTTP. + + Args: + request (~.backupplanassociation.ListBackupPlanAssociationsRequest): + The request object. Request message for List + BackupPlanAssociation + 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: + ~.backupplanassociation.ListBackupPlanAssociationsResponse: + Response message for List + BackupPlanAssociation + + """ + + http_options = _BaseBackupDRRestTransport._BaseListBackupPlanAssociations._get_http_options() + request, metadata = self._interceptor.pre_list_backup_plan_associations( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, + "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListBackupPlanAssociations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlanAssociations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackupPlanAssociations._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 = backupplanassociation.ListBackupPlanAssociationsResponse() + pb_resp = backupplanassociation.ListBackupPlanAssociationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backup_plan_associations(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_backup_plan_associations_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplanassociation.ListBackupPlanAssociationsResponse.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.backupdr_v1beta.BackupDRClient.list_backup_plan_associations", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlanAssociations", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackupPlanRevisions( + _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackupPlanRevisions") + + @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: backupplan.ListBackupPlanRevisionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.ListBackupPlanRevisionsResponse: + r"""Call the list backup plan + revisions method over HTTP. + + Args: + request (~.backupplan.ListBackupPlanRevisionsRequest): + The request object. The request message for getting a list of + ``BackupPlanRevision``. + 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: + ~.backupplan.ListBackupPlanRevisionsResponse: + The response message for getting a list of + ``BackupPlanRevision``. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListBackupPlanRevisions._get_http_options() + request, metadata = self._interceptor.pre_list_backup_plan_revisions( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, + "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListBackupPlanRevisions", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlanRevisions", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackupPlanRevisions._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 = backupplan.ListBackupPlanRevisionsResponse() + pb_resp = backupplan.ListBackupPlanRevisionsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backup_plan_revisions(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_backup_plan_revisions_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + backupplan.ListBackupPlanRevisionsResponse.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.backupdr_v1beta.BackupDRClient.list_backup_plan_revisions", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlanRevisions", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackupPlans( + _BaseBackupDRRestTransport._BaseListBackupPlans, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackupPlans") + + @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: backupplan.ListBackupPlansRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupplan.ListBackupPlansResponse: + r"""Call the list backup plans method over HTTP. + + Args: + request (~.backupplan.ListBackupPlansRequest): + The request object. The request message for getting a list ``BackupPlan``. + 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: + ~.backupplan.ListBackupPlansResponse: + The response message for getting a list of + ``BackupPlan``. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseListBackupPlans._get_http_options() + ) + request, metadata = self._interceptor.pre_list_backup_plans( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackupPlans, + "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListBackupPlans", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlans", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackupPlans._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 = backupplan.ListBackupPlansResponse() + pb_resp = backupplan.ListBackupPlansResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backup_plans(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_backup_plans_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupplan.ListBackupPlansResponse.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.backupdr_v1beta.BackupDRClient.list_backup_plans", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupPlans", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackups(_BaseBackupDRRestTransport._BaseListBackups, BackupDRRestStub): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackups") + + @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: backupvault.ListBackupsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.ListBackupsResponse: + r"""Call the list backups method over HTTP. + + Args: + request (~.backupvault.ListBackupsRequest): + The request object. Request message for listing Backups. + 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: + ~.backupvault.ListBackupsResponse: + Response message for listing Backups. + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseListBackups._get_http_options() + ) + request, metadata = self._interceptor.pre_list_backups(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackups, + "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListBackups", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackups", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackups._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 = backupvault.ListBackupsResponse() + pb_resp = backupvault.ListBackupsResponse.pb(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_list_backups_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupvault.ListBackupsResponse.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.backupdr_v1beta.BackupDRClient.list_backups", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackups", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackupVaults( + _BaseBackupDRRestTransport._BaseListBackupVaults, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBackupVaults") + + @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: backupvault.ListBackupVaultsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> backupvault.ListBackupVaultsResponse: + r"""Call the list backup vaults method over HTTP. + + Args: + request (~.backupvault.ListBackupVaultsRequest): + The request object. Request message for listing + backupvault stores. + 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: + ~.backupvault.ListBackupVaultsResponse: + Response message for listing + BackupVaults. + + """ + + http_options = ( + _BaseBackupDRRestTransport._BaseListBackupVaults._get_http_options() + ) + request, metadata = self._interceptor.pre_list_backup_vaults( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBackupVaults, + "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListBackupVaults", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupVaults", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListBackupVaults._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 = backupvault.ListBackupVaultsResponse() + pb_resp = backupvault.ListBackupVaultsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backup_vaults(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_backup_vaults_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = backupvault.ListBackupVaultsResponse.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.backupdr_v1beta.BackupDRClient.list_backup_vaults", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBackupVaults", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBindingMatchingResources( + _BaseBackupDRRestTransport._BaseListBindingMatchingResources, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListBindingMatchingResources") + + @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: bindingmatchingresource.ListBindingMatchingResourcesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> bindingmatchingresource.ListBindingMatchingResourcesResponse: + r"""Call the list binding matching + resources method over HTTP. + + Args: + request (~.bindingmatchingresource.ListBindingMatchingResourcesRequest): + The request object. Request message for List + BindingMatchingResources. + 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: + ~.bindingmatchingresource.ListBindingMatchingResourcesResponse: + The response message for getting a list of + ``BindingMatchingResources``. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListBindingMatchingResources._get_http_options() + request, metadata = self._interceptor.pre_list_binding_matching_resources( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListBindingMatchingResources, + "_BaseListBindingMatchingResources__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListBindingMatchingResources", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBindingMatchingResources", "httpRequest": http_request, "metadata": http_request["headers"], }, @@ -8124,7 +11641,7 @@ def __call__( # Send the request response = ( - BackupDRRestTransport._ListAutoProtectionPolicyBindings._get_response( + BackupDRRestTransport._ListBindingMatchingResources._get_response( self._host, metadata, query_params, @@ -8140,30 +11657,179 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() - ) - pb_resp = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( - resp - ) - ) + resp = bindingmatchingresource.ListBindingMatchingResourcesResponse() + pb_resp = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + resp + ) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_binding_matching_resources(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_list_binding_matching_resources_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = bindingmatchingresource.ListBindingMatchingResourcesResponse.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.backupdr_v1beta.BackupDRClient.list_binding_matching_resources", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListBindingMatchingResources", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListDataSourceReferences( + _BaseBackupDRRestTransport._BaseListDataSourceReferences, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.ListDataSourceReferences") + + @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: datasourcereference.ListDataSourceReferencesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> datasourcereference.ListDataSourceReferencesResponse: + r"""Call the list data source + references method over HTTP. + + Args: + request (~.datasourcereference.ListDataSourceReferencesRequest): + The request object. Request for the + ListDataSourceReferences method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.datasourcereference.ListDataSourceReferencesResponse: + Response for the + ListDataSourceReferences method. + + """ + + http_options = _BaseBackupDRRestTransport._BaseListDataSourceReferences._get_http_options() + request, metadata = self._interceptor.pre_list_data_source_references( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseListDataSourceReferences, + "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.ListDataSourceReferences", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "ListDataSourceReferences", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._ListDataSourceReferences._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 = datasourcereference.ListDataSourceReferencesResponse() + pb_resp = datasourcereference.ListDataSourceReferencesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_auto_protection_policy_bindings(resp) + resp = self._interceptor.post_list_data_source_references(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_list_auto_protection_policy_bindings_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_list_data_source_references_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.to_json( - response + response_payload = ( + datasourcereference.ListDataSourceReferencesResponse.to_json( + response + ) ) except: response_payload = None @@ -8173,21 +11839,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policy_bindings", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_data_source_references", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListAutoProtectionPolicyBindings", + "rpcName": "ListDataSourceReferences", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackupPlanAssociations( - _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, BackupDRRestStub + class _ListDataSources( + _BaseBackupDRRestTransport._BaseListDataSources, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackupPlanAssociations") + return hash("BackupDRRestTransport.ListDataSources") @staticmethod def _get_response( @@ -8213,44 +11879,45 @@ def _get_response( def __call__( self, - request: backupplanassociation.ListBackupPlanAssociationsRequest, + request: backupvault.ListDataSourcesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplanassociation.ListBackupPlanAssociationsResponse: - r"""Call the list backup plan - associations method over HTTP. + ) -> backupvault.ListDataSourcesResponse: + r"""Call the list data sources method over HTTP. - Args: - request (~.backupplanassociation.ListBackupPlanAssociationsRequest): - The request object. Request message for List - BackupPlanAssociation - 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 (~.backupvault.ListDataSourcesRequest): + The request object. Request message for listing + DataSources. + 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: - ~.backupplanassociation.ListBackupPlanAssociationsResponse: - Response message for List - BackupPlanAssociation + Returns: + ~.backupvault.ListDataSourcesResponse: + Response message for listing + DataSources. """ - http_options = _BaseBackupDRRestTransport._BaseListBackupPlanAssociations._get_http_options() - request, metadata = self._interceptor.pre_list_backup_plan_associations( + http_options = ( + _BaseBackupDRRestTransport._BaseListDataSources._get_http_options() + ) + request, metadata = self._interceptor.pre_list_data_sources( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackupPlanAssociations, - "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListDataSources, + "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -8274,17 +11941,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackupPlanAssociations", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListDataSources", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackupPlanAssociations", + "rpcName": "ListDataSources", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackupPlanAssociations._get_response( + response = BackupDRRestTransport._ListDataSources._get_response( self._host, metadata, query_params, @@ -8299,23 +11966,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplanassociation.ListBackupPlanAssociationsResponse() - pb_resp = backupplanassociation.ListBackupPlanAssociationsResponse.pb(resp) + resp = backupvault.ListDataSourcesResponse() + pb_resp = backupvault.ListDataSourcesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_backup_plan_associations(resp) + resp = self._interceptor.post_list_data_sources(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_list_backup_plan_associations_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_list_data_sources_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupplanassociation.ListBackupPlanAssociationsResponse.to_json( + response_payload = backupvault.ListDataSourcesResponse.to_json( response ) except: @@ -8326,21 +11991,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_associations", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_data_sources", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackupPlanAssociations", + "rpcName": "ListDataSources", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackupPlanRevisions( - _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, BackupDRRestStub + class _ListManagementServers( + _BaseBackupDRRestTransport._BaseListManagementServers, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackupPlanRevisions") + return hash("BackupDRRestTransport.ListManagementServers") @staticmethod def _get_response( @@ -8366,44 +12031,43 @@ def _get_response( def __call__( self, - request: backupplan.ListBackupPlanRevisionsRequest, + request: backupdr.ListManagementServersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplan.ListBackupPlanRevisionsResponse: - r"""Call the list backup plan - revisions method over HTTP. + ) -> backupdr.ListManagementServersResponse: + r"""Call the list management servers method over HTTP. - Args: - request (~.backupplan.ListBackupPlanRevisionsRequest): - The request object. The request message for getting a list of - ``BackupPlanRevision``. - 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 (~.backupdr.ListManagementServersRequest): + The request object. Request message for listing + management servers. + 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: - ~.backupplan.ListBackupPlanRevisionsResponse: - The response message for getting a list of - ``BackupPlanRevision``. + Returns: + ~.backupdr.ListManagementServersResponse: + Response message for listing + management servers. """ - http_options = _BaseBackupDRRestTransport._BaseListBackupPlanRevisions._get_http_options() - request, metadata = self._interceptor.pre_list_backup_plan_revisions( + http_options = _BaseBackupDRRestTransport._BaseListManagementServers._get_http_options() + request, metadata = self._interceptor.pre_list_management_servers( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackupPlanRevisions, - "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListManagementServers, + "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -8427,17 +12091,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackupPlanRevisions", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListManagementServers", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackupPlanRevisions", + "rpcName": "ListManagementServers", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackupPlanRevisions._get_response( + response = BackupDRRestTransport._ListManagementServers._get_response( self._host, metadata, query_params, @@ -8452,22 +12116,22 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplan.ListBackupPlanRevisionsResponse() - pb_resp = backupplan.ListBackupPlanRevisionsResponse.pb(resp) + resp = backupdr.ListManagementServersResponse() + pb_resp = backupdr.ListManagementServersResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_backup_plan_revisions(resp) + resp = self._interceptor.post_list_management_servers(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_backup_plan_revisions_with_metadata( + resp, _ = self._interceptor.post_list_management_servers_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - backupplan.ListBackupPlanRevisionsResponse.to_json(response) + response_payload = backupdr.ListManagementServersResponse.to_json( + response ) except: response_payload = None @@ -8477,21 +12141,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_revisions", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_management_servers", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackupPlanRevisions", + "rpcName": "ListManagementServers", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackupPlans( - _BaseBackupDRRestTransport._BaseListBackupPlans, BackupDRRestStub + class _ListRestoreTemplateExecutions( + _BaseBackupDRRestTransport._BaseListRestoreTemplateExecutions, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackupPlans") + return hash("BackupDRRestTransport.ListRestoreTemplateExecutions") @staticmethod def _get_response( @@ -8517,44 +12181,44 @@ def _get_response( def __call__( self, - request: backupplan.ListBackupPlansRequest, + request: restore_template_execution.ListRestoreTemplateExecutionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupplan.ListBackupPlansResponse: - r"""Call the list backup plans method over HTTP. + ) -> restore_template_execution.ListRestoreTemplateExecutionsResponse: + r"""Call the list restore template + executions method over HTTP. - Args: - request (~.backupplan.ListBackupPlansRequest): - The request object. The request message for getting a list ``BackupPlan``. - 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 (~.restore_template_execution.ListRestoreTemplateExecutionsRequest): + The request object. Request message for listing + RestoreTemplateExecutions. + 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: - ~.backupplan.ListBackupPlansResponse: - The response message for getting a list of - ``BackupPlan``. + Returns: + ~.restore_template_execution.ListRestoreTemplateExecutionsResponse: + Response message for listing + RestoreTemplateExecutions. """ - http_options = ( - _BaseBackupDRRestTransport._BaseListBackupPlans._get_http_options() - ) - request, metadata = self._interceptor.pre_list_backup_plans( + http_options = _BaseBackupDRRestTransport._BaseListRestoreTemplateExecutions._get_http_options() + request, metadata = self._interceptor.pre_list_restore_template_executions( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackupPlans, - "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListRestoreTemplateExecutions, + "_BaseListRestoreTemplateExecutions__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -8578,23 +12242,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackupPlans", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListRestoreTemplateExecutions", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackupPlans", + "rpcName": "ListRestoreTemplateExecutions", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackupPlans._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + BackupDRRestTransport._ListRestoreTemplateExecutions._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -8603,21 +12269,27 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupplan.ListBackupPlansResponse() - pb_resp = backupplan.ListBackupPlansResponse.pb(resp) + resp = restore_template_execution.ListRestoreTemplateExecutionsResponse() + pb_resp = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse.pb( + resp + ) + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_backup_plans(resp) + resp = self._interceptor.post_list_restore_template_executions(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_backup_plans_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_list_restore_template_executions_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupplan.ListBackupPlansResponse.to_json( + response_payload = restore_template_execution.ListRestoreTemplateExecutionsResponse.to_json( response ) except: @@ -8628,19 +12300,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plans", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_restore_template_executions", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackupPlans", + "rpcName": "ListRestoreTemplateExecutions", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackups(_BaseBackupDRRestTransport._BaseListBackups, BackupDRRestStub): + class _ListRestoreTemplates( + _BaseBackupDRRestTransport._BaseListRestoreTemplates, BackupDRRestStub + ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackups") + return hash("BackupDRRestTransport.ListRestoreTemplates") @staticmethod def _get_response( @@ -8666,17 +12340,18 @@ def _get_response( def __call__( self, - request: backupvault.ListBackupsRequest, + request: restore_template.ListRestoreTemplatesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.ListBackupsResponse: - r"""Call the list backups method over HTTP. + ) -> restore_template.ListRestoreTemplatesResponse: + r"""Call the list restore templates method over HTTP. - Args: - request (~.backupvault.ListBackupsRequest): - The request object. Request message for listing Backups. + Args: + request (~.restore_template.ListRestoreTemplatesRequest): + The request object. Request message for listing + RestoreTemplates. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8686,20 +12361,24 @@ def __call__( be of type `bytes`. Returns: - ~.backupvault.ListBackupsResponse: - Response message for listing Backups. + ~.restore_template.ListRestoreTemplatesResponse: + Response message for listing + RestoreTemplates. + """ http_options = ( - _BaseBackupDRRestTransport._BaseListBackups._get_http_options() + _BaseBackupDRRestTransport._BaseListRestoreTemplates._get_http_options() + ) + request, metadata = self._interceptor.pre_list_restore_templates( + request, metadata ) - request, metadata = self._interceptor.pre_list_backups(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackups, - "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListRestoreTemplates, + "_BaseListRestoreTemplates__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -8723,17 +12402,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackups", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListRestoreTemplates", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackups", + "rpcName": "ListRestoreTemplates", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackups._get_response( + response = BackupDRRestTransport._ListRestoreTemplates._get_response( self._host, metadata, query_params, @@ -8748,21 +12427,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.ListBackupsResponse() - pb_resp = backupvault.ListBackupsResponse.pb(resp) + resp = restore_template.ListRestoreTemplatesResponse() + pb_resp = restore_template.ListRestoreTemplatesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_backups(resp) + resp = self._interceptor.post_list_restore_templates(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_backups_with_metadata( + resp, _ = self._interceptor.post_list_restore_templates_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.ListBackupsResponse.to_json(response) + response_payload = ( + restore_template.ListRestoreTemplatesResponse.to_json(response) + ) except: response_payload = None http_response = { @@ -8771,21 +12452,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backups", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_restore_templates", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackups", + "rpcName": "ListRestoreTemplates", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBackupVaults( - _BaseBackupDRRestTransport._BaseListBackupVaults, BackupDRRestStub + class _ListRestoreVerificationPlanAssociations( + _BaseBackupDRRestTransport._BaseListRestoreVerificationPlanAssociations, + BackupDRRestStub, ): def __hash__(self): - return hash("BackupDRRestTransport.ListBackupVaults") + return hash("BackupDRRestTransport.ListRestoreVerificationPlanAssociations") @staticmethod def _get_response( @@ -8811,45 +12493,46 @@ def _get_response( def __call__( self, - request: backupvault.ListBackupVaultsRequest, + request: restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.ListBackupVaultsResponse: - r"""Call the list backup vaults method over HTTP. + ) -> restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse: + r"""Call the list restore verification + plan associations method over HTTP. - Args: - request (~.backupvault.ListBackupVaultsRequest): - The request object. Request message for listing - backupvault stores. - 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 (~.restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest): + The request object. Request message for + ListRestoreVerificationPlanAssociations. + 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: - ~.backupvault.ListBackupVaultsResponse: - Response message for listing - BackupVaults. + Returns: + ~.restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse: + Response message for + ListRestoreVerificationPlanAssociations. """ - http_options = ( - _BaseBackupDRRestTransport._BaseListBackupVaults._get_http_options() - ) - request, metadata = self._interceptor.pre_list_backup_vaults( - request, metadata + http_options = _BaseBackupDRRestTransport._BaseListRestoreVerificationPlanAssociations._get_http_options() + request, metadata = ( + self._interceptor.pre_list_restore_verification_plan_associations( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBackupVaults, - "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListRestoreVerificationPlanAssociations, + "_BaseListRestoreVerificationPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -8873,17 +12556,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBackupVaults", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListRestoreVerificationPlanAssociations", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackupVaults", + "rpcName": "ListRestoreVerificationPlanAssociations", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListBackupVaults._get_response( + response = BackupDRRestTransport._ListRestoreVerificationPlanAssociations._get_response( self._host, metadata, query_params, @@ -8898,21 +12581,27 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.ListBackupVaultsResponse() - pb_resp = backupvault.ListBackupVaultsResponse.pb(resp) + resp = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + pb_resp = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.pb( + resp + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_backup_vaults(resp) + resp = self._interceptor.post_list_restore_verification_plan_associations( + resp + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_backup_vaults_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_list_restore_verification_plan_associations_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.ListBackupVaultsResponse.to_json( + response_payload = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.to_json( response ) except: @@ -8923,21 +12612,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_backup_vaults", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_restore_verification_plan_associations", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBackupVaults", + "rpcName": "ListRestoreVerificationPlanAssociations", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBindingMatchingResources( - _BaseBackupDRRestTransport._BaseListBindingMatchingResources, BackupDRRestStub + class _ListRestoreVerificationPlans( + _BaseBackupDRRestTransport._BaseListRestoreVerificationPlans, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListBindingMatchingResources") + return hash("BackupDRRestTransport.ListRestoreVerificationPlans") @staticmethod def _get_response( @@ -8963,19 +12652,19 @@ def _get_response( def __call__( self, - request: bindingmatchingresource.ListBindingMatchingResourcesRequest, + request: restore_verification_plan.ListRestoreVerificationPlansRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> bindingmatchingresource.ListBindingMatchingResourcesResponse: - r"""Call the list binding matching - resources method over HTTP. + ) -> restore_verification_plan.ListRestoreVerificationPlansResponse: + r"""Call the list restore verification + plans method over HTTP. Args: - request (~.bindingmatchingresource.ListBindingMatchingResourcesRequest): - The request object. Request message for List - BindingMatchingResources. + request (~.restore_verification_plan.ListRestoreVerificationPlansRequest): + The request object. The request message for getting a list of + ``RestoreVerificationPlans``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -8985,22 +12674,22 @@ def __call__( be of type `bytes`. Returns: - ~.bindingmatchingresource.ListBindingMatchingResourcesResponse: + ~.restore_verification_plan.ListRestoreVerificationPlansResponse: The response message for getting a list of - ``BindingMatchingResources``. + ``RestoreVerificationPlans``. """ - http_options = _BaseBackupDRRestTransport._BaseListBindingMatchingResources._get_http_options() - request, metadata = self._interceptor.pre_list_binding_matching_resources( + http_options = _BaseBackupDRRestTransport._BaseListRestoreVerificationPlans._get_http_options() + request, metadata = self._interceptor.pre_list_restore_verification_plans( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListBindingMatchingResources, - "_BaseListBindingMatchingResources__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseListRestoreVerificationPlans, + "_BaseListRestoreVerificationPlans__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -9024,10 +12713,10 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListBindingMatchingResources", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListRestoreVerificationPlans", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBindingMatchingResources", + "rpcName": "ListRestoreVerificationPlans", "httpRequest": http_request, "metadata": http_request["headers"], }, @@ -9035,7 +12724,7 @@ def __call__( # Send the request response = ( - BackupDRRestTransport._ListBindingMatchingResources._get_response( + BackupDRRestTransport._ListRestoreVerificationPlans._get_response( self._host, metadata, query_params, @@ -9051,17 +12740,17 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = bindingmatchingresource.ListBindingMatchingResourcesResponse() - pb_resp = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + resp = restore_verification_plan.ListRestoreVerificationPlansResponse() + pb_resp = restore_verification_plan.ListRestoreVerificationPlansResponse.pb( resp ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_binding_matching_resources(resp) + resp = self._interceptor.post_list_restore_verification_plans(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] resp, _ = ( - self._interceptor.post_list_binding_matching_resources_with_metadata( + self._interceptor.post_list_restore_verification_plans_with_metadata( resp, response_metadata ) ) @@ -9069,7 +12758,7 @@ def __call__( logging.DEBUG ): # pragma: NO COVER try: - response_payload = bindingmatchingresource.ListBindingMatchingResourcesResponse.to_json( + response_payload = restore_verification_plan.ListRestoreVerificationPlansResponse.to_json( response ) except: @@ -9080,21 +12769,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_binding_matching_resources", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_restore_verification_plans", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListBindingMatchingResources", + "rpcName": "ListRestoreVerificationPlans", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListDataSourceReferences( - _BaseBackupDRRestTransport._BaseListDataSourceReferences, BackupDRRestStub + class _RestoreBackup( + _BaseBackupDRRestTransport._BaseRestoreBackup, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListDataSourceReferences") + return hash("BackupDRRestTransport.RestoreBackup") @staticmethod def _get_response( @@ -9115,49 +12804,50 @@ 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: datasourcereference.ListDataSourceReferencesRequest, + request: backupvault.RestoreBackupRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> datasourcereference.ListDataSourceReferencesResponse: - r"""Call the list data source - references method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the restore backup method over HTTP. - Args: - request (~.datasourcereference.ListDataSourceReferencesRequest): - The request object. Request for the - ListDataSourceReferences method. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, 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 (~.backupvault.RestoreBackupRequest): + The request object. Request message for restoring from a + Backup. + 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: - ~.datasourcereference.ListDataSourceReferencesResponse: - Response for the - ListDataSourceReferences method. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseListDataSourceReferences._get_http_options() - request, metadata = self._interceptor.pre_list_data_source_references( - request, metadata + http_options = ( + _BaseBackupDRRestTransport._BaseRestoreBackup._get_http_options() ) + request, metadata = self._interceptor.pre_restore_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListDataSourceReferences, - "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseRestoreBackup, + "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -9181,23 +12871,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListDataSourceReferences", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.RestoreBackup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListDataSourceReferences", + "rpcName": "RestoreBackup", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListDataSourceReferences._get_response( + response = BackupDRRestTransport._RestoreBackup._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -9206,25 +12897,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = datasourcereference.ListDataSourceReferencesResponse() - pb_resp = datasourcereference.ListDataSourceReferencesResponse.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_data_source_references(resp) + resp = self._interceptor.post_restore_backup(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_data_source_references_with_metadata( + resp, _ = self._interceptor.post_restore_backup_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - datasourcereference.ListDataSourceReferencesResponse.to_json( - response - ) - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -9233,21 +12918,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_data_source_references", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.restore_backup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListDataSourceReferences", + "rpcName": "RestoreBackup", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListDataSources( - _BaseBackupDRRestTransport._BaseListDataSources, BackupDRRestStub + class _RunRestoreTemplate( + _BaseBackupDRRestTransport._BaseRunRestoreTemplate, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListDataSources") + return hash("BackupDRRestTransport.RunRestoreTemplate") @staticmethod def _get_response( @@ -9268,23 +12953,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: backupvault.ListDataSourcesRequest, + request: restore_template.RunRestoreTemplateRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupvault.ListDataSourcesResponse: - r"""Call the list data sources method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the run restore template method over HTTP. Args: - request (~.backupvault.ListDataSourcesRequest): - The request object. Request message for listing - DataSources. + request (~.restore_template.RunRestoreTemplateRequest): + The request object. Request message for running a + RestoreTemplate. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9294,24 +12980,25 @@ def __call__( be of type `bytes`. Returns: - ~.backupvault.ListDataSourcesResponse: - Response message for listing - DataSources. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ http_options = ( - _BaseBackupDRRestTransport._BaseListDataSources._get_http_options() + _BaseBackupDRRestTransport._BaseRunRestoreTemplate._get_http_options() ) - request, metadata = self._interceptor.pre_list_data_sources( + request, metadata = self._interceptor.pre_run_restore_template( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListDataSources, - "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseRunRestoreTemplate, + "_BaseRunRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -9335,23 +13022,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListDataSources", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.RunRestoreTemplate", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListDataSources", + "rpcName": "RunRestoreTemplate", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListDataSources._get_response( + response = BackupDRRestTransport._RunRestoreTemplate._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -9360,23 +13048,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupvault.ListDataSourcesResponse() - pb_resp = backupvault.ListDataSourcesResponse.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_data_sources(resp) + resp = self._interceptor.post_run_restore_template(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_data_sources_with_metadata( + resp, _ = self._interceptor.post_run_restore_template_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupvault.ListDataSourcesResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -9385,21 +13069,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_data_sources", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.run_restore_template", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListDataSources", + "rpcName": "RunRestoreTemplate", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListManagementServers( - _BaseBackupDRRestTransport._BaseListManagementServers, BackupDRRestStub + class _TriggerBackup( + _BaseBackupDRRestTransport._BaseTriggerBackup, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.ListManagementServers") + return hash("BackupDRRestTransport.TriggerBackup") @staticmethod def _get_response( @@ -9420,23 +13104,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: backupdr.ListManagementServersRequest, + request: backupplanassociation.TriggerBackupRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> backupdr.ListManagementServersResponse: - r"""Call the list management servers method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the trigger backup method over HTTP. Args: - request (~.backupdr.ListManagementServersRequest): - The request object. Request message for listing - management servers. + request (~.backupplanassociation.TriggerBackupRequest): + The request object. Request message for triggering a + backup. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9446,22 +13131,23 @@ def __call__( be of type `bytes`. Returns: - ~.backupdr.ListManagementServersResponse: - Response message for listing - management servers. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseBackupDRRestTransport._BaseListManagementServers._get_http_options() - request, metadata = self._interceptor.pre_list_management_servers( - request, metadata + http_options = ( + _BaseBackupDRRestTransport._BaseTriggerBackup._get_http_options() ) + request, metadata = self._interceptor.pre_trigger_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseListManagementServers, - "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseTriggerBackup, + "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -9485,23 +13171,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.ListManagementServers", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.TriggerBackup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListManagementServers", + "rpcName": "TriggerBackup", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._ListManagementServers._get_response( + response = BackupDRRestTransport._TriggerBackup._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -9510,23 +13197,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = backupdr.ListManagementServersResponse() - pb_resp = backupdr.ListManagementServersResponse.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_management_servers(resp) + resp = self._interceptor.post_trigger_backup(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_management_servers_with_metadata( + resp, _ = self._interceptor.post_trigger_backup_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = backupdr.ListManagementServersResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -9535,21 +13218,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.list_management_servers", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.trigger_backup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "ListManagementServers", + "rpcName": "TriggerBackup", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _RestoreBackup( - _BaseBackupDRRestTransport._BaseRestoreBackup, BackupDRRestStub + class _TriggerRestoreCleanup( + _BaseBackupDRRestTransport._BaseTriggerRestoreCleanup, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.RestoreBackup") + return hash("BackupDRRestTransport.TriggerRestoreCleanup") @staticmethod def _get_response( @@ -9576,18 +13259,18 @@ def _get_response( def __call__( self, - request: backupvault.RestoreBackupRequest, + request: restore_template_execution.TriggerRestoreCleanupRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the restore backup method over HTTP. + r"""Call the trigger restore cleanup method over HTTP. Args: - request (~.backupvault.RestoreBackupRequest): - The request object. Request message for restoring from a - Backup. + request (~.restore_template_execution.TriggerRestoreCleanupRequest): + The request object. Request message for triggering a + restore cleanup. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -9604,16 +13287,16 @@ def __call__( """ - http_options = ( - _BaseBackupDRRestTransport._BaseRestoreBackup._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseTriggerRestoreCleanup._get_http_options() + request, metadata = self._interceptor.pre_trigger_restore_cleanup( + request, metadata ) - request, metadata = self._interceptor.pre_restore_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseRestoreBackup, - "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseTriggerRestoreCleanup, + "_BaseTriggerRestoreCleanup__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -9637,17 +13320,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.RestoreBackup", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.TriggerRestoreCleanup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "RestoreBackup", + "rpcName": "TriggerRestoreCleanup", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._RestoreBackup._get_response( + response = BackupDRRestTransport._TriggerRestoreCleanup._get_response( self._host, metadata, query_params, @@ -9666,9 +13349,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_restore_backup(resp) + resp = self._interceptor.post_trigger_restore_cleanup(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_restore_backup_with_metadata( + resp, _ = self._interceptor.post_trigger_restore_cleanup_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -9684,21 +13367,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.restore_backup", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.trigger_restore_cleanup", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "RestoreBackup", + "rpcName": "TriggerRestoreCleanup", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _TriggerBackup( - _BaseBackupDRRestTransport._BaseTriggerBackup, BackupDRRestStub + class _TriggerRestoreVerification( + _BaseBackupDRRestTransport._BaseTriggerRestoreVerification, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.TriggerBackup") + return hash("BackupDRRestTransport.TriggerRestoreVerification") @staticmethod def _get_response( @@ -9725,44 +13408,45 @@ def _get_response( def __call__( self, - request: backupplanassociation.TriggerBackupRequest, + request: restore_verification_plan_association.TriggerRestoreVerificationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the trigger backup method over HTTP. + r"""Call the trigger restore + verification method over HTTP. - Args: - request (~.backupplanassociation.TriggerBackupRequest): - The request object. Request message for triggering a - backup. - 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 (~.restore_verification_plan_association.TriggerRestoreVerificationRequest): + The request object. Request message for + TriggerRestoreVerification. + 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. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = ( - _BaseBackupDRRestTransport._BaseTriggerBackup._get_http_options() + http_options = _BaseBackupDRRestTransport._BaseTriggerRestoreVerification._get_http_options() + request, metadata = self._interceptor.pre_trigger_restore_verification( + request, metadata ) - request, metadata = self._interceptor.pre_trigger_backup(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseTriggerBackup, - "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseTriggerRestoreVerification, + "_BaseTriggerRestoreVerification__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -9786,17 +13470,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.TriggerBackup", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.TriggerRestoreVerification", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "TriggerBackup", + "rpcName": "TriggerRestoreVerification", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._TriggerBackup._get_response( + response = BackupDRRestTransport._TriggerRestoreVerification._get_response( self._host, metadata, query_params, @@ -9815,9 +13499,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_trigger_backup(resp) + resp = self._interceptor.post_trigger_restore_verification(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_trigger_backup_with_metadata( + resp, _ = self._interceptor.post_trigger_restore_verification_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -9833,10 +13517,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.trigger_backup", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.trigger_restore_verification", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "TriggerBackup", + "rpcName": "TriggerRestoreVerification", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -10345,24 +14029,177 @@ def __call__( 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. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseBackupDRRestTransport._BaseUpdateBackupPlanAssociation._get_http_options() + request, metadata = self._interceptor.pre_update_backup_plan_association( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseBackupDRRestTransport._BaseUpdateBackupPlanAssociation, + "_BaseUpdateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.backupdr_v1beta.BackupDRClient.UpdateBackupPlanAssociation", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackupPlanAssociation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = BackupDRRestTransport._UpdateBackupPlanAssociation._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_update_backup_plan_association(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_update_backup_plan_association_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.backupdr_v1beta.BackupDRClient.update_backup_plan_association", + extra={ + "serviceName": "google.cloud.backupdr.v1beta.BackupDR", + "rpcName": "UpdateBackupPlanAssociation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateBackupVault( + _BaseBackupDRRestTransport._BaseUpdateBackupVault, BackupDRRestStub + ): + def __hash__(self): + return hash("BackupDRRestTransport.UpdateBackupVault") + + @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: backupvault.UpdateBackupVaultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the update backup vault method over HTTP. + + Args: + request (~.backupvault.UpdateBackupVaultRequest): + The request object. Request message for updating a + BackupVault. + 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 = _BaseBackupDRRestTransport._BaseUpdateBackupPlanAssociation._get_http_options() - request, metadata = self._interceptor.pre_update_backup_plan_association( + http_options = ( + _BaseBackupDRRestTransport._BaseUpdateBackupVault._get_http_options() + ) + request, metadata = self._interceptor.pre_update_backup_vault( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseUpdateBackupPlanAssociation, - "_BaseUpdateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseUpdateBackupVault, + "_BaseUpdateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -10386,17 +14223,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateBackupPlanAssociation", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateBackupVault", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "UpdateBackupPlanAssociation", + "rpcName": "UpdateBackupVault", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._UpdateBackupPlanAssociation._get_response( + response = BackupDRRestTransport._UpdateBackupVault._get_response( self._host, metadata, query_params, @@ -10415,12 +14252,10 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_backup_plan_association(resp) + resp = self._interceptor.post_update_backup_vault(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_update_backup_plan_association_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_update_backup_vault_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG @@ -10435,21 +14270,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_backup_plan_association", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_backup_vault", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "UpdateBackupPlanAssociation", + "rpcName": "UpdateBackupVault", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _UpdateBackupVault( - _BaseBackupDRRestTransport._BaseUpdateBackupVault, BackupDRRestStub + class _UpdateDataSource( + _BaseBackupDRRestTransport._BaseUpdateDataSource, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.UpdateBackupVault") + return hash("BackupDRRestTransport.UpdateDataSource") @staticmethod def _get_response( @@ -10476,18 +14311,18 @@ def _get_response( def __call__( self, - request: backupvault.UpdateBackupVaultRequest, + request: backupvault.UpdateDataSourceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the update backup vault method over HTTP. + r"""Call the update data source method over HTTP. Args: - request (~.backupvault.UpdateBackupVaultRequest): - The request object. Request message for updating a - BackupVault. + request (~.backupvault.UpdateDataSourceRequest): + The request object. Request message for updating a data + source instance. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -10505,17 +14340,17 @@ def __call__( """ http_options = ( - _BaseBackupDRRestTransport._BaseUpdateBackupVault._get_http_options() + _BaseBackupDRRestTransport._BaseUpdateDataSource._get_http_options() ) - request, metadata = self._interceptor.pre_update_backup_vault( + request, metadata = self._interceptor.pre_update_data_source( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseUpdateBackupVault, - "_BaseUpdateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseUpdateDataSource, + "_BaseUpdateDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -10539,17 +14374,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateBackupVault", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateDataSource", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "UpdateBackupVault", + "rpcName": "UpdateDataSource", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._UpdateBackupVault._get_response( + response = BackupDRRestTransport._UpdateDataSource._get_response( self._host, metadata, query_params, @@ -10568,9 +14403,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_backup_vault(resp) + resp = self._interceptor.post_update_data_source(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_backup_vault_with_metadata( + resp, _ = self._interceptor.post_update_data_source_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -10586,21 +14421,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_backup_vault", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_data_source", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "UpdateBackupVault", + "rpcName": "UpdateDataSource", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _UpdateDataSource( - _BaseBackupDRRestTransport._BaseUpdateDataSource, BackupDRRestStub + class _UpdateRestoreTemplate( + _BaseBackupDRRestTransport._BaseUpdateRestoreTemplate, BackupDRRestStub ): def __hash__(self): - return hash("BackupDRRestTransport.UpdateDataSource") + return hash("BackupDRRestTransport.UpdateRestoreTemplate") @staticmethod def _get_response( @@ -10627,18 +14462,18 @@ def _get_response( def __call__( self, - request: backupvault.UpdateDataSourceRequest, + request: gcb_restore_template.UpdateRestoreTemplateRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> operations_pb2.Operation: - r"""Call the update data source method over HTTP. + r"""Call the update restore template method over HTTP. Args: - request (~.backupvault.UpdateDataSourceRequest): - The request object. Request message for updating a data - source instance. + request (~.gcb_restore_template.UpdateRestoreTemplateRequest): + The request object. Request message for updating a + RestoreTemplate instance. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -10655,18 +14490,16 @@ def __call__( """ - http_options = ( - _BaseBackupDRRestTransport._BaseUpdateDataSource._get_http_options() - ) - request, metadata = self._interceptor.pre_update_data_source( + http_options = _BaseBackupDRRestTransport._BaseUpdateRestoreTemplate._get_http_options() + request, metadata = self._interceptor.pre_update_restore_template( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseBackupDRRestTransport._BaseUpdateDataSource, - "_BaseUpdateDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseBackupDRRestTransport._BaseUpdateRestoreTemplate, + "_BaseUpdateRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -10690,17 +14523,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateDataSource", + f"Sending request for google.cloud.backupdr_v1beta.BackupDRClient.UpdateRestoreTemplate", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "UpdateDataSource", + "rpcName": "UpdateRestoreTemplate", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = BackupDRRestTransport._UpdateDataSource._get_response( + response = BackupDRRestTransport._UpdateRestoreTemplate._get_response( self._host, metadata, query_params, @@ -10719,9 +14552,9 @@ def __call__( resp = operations_pb2.Operation() json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_update_data_source(resp) + resp = self._interceptor.post_update_restore_template(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_update_data_source_with_metadata( + resp, _ = self._interceptor.post_update_restore_template_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -10737,10 +14570,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_data_source", + "Received response for google.cloud.backupdr_v1beta.BackupDRClient.update_restore_template", extra={ "serviceName": "google.cloud.backupdr.v1beta.BackupDR", - "rpcName": "UpdateDataSource", + "rpcName": "UpdateRestoreTemplate", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -10812,6 +14645,44 @@ def create_management_server( self._session, self._host, self._interceptor ) # type: ignore + @property + def create_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.CreateRestoreTemplateRequest], 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._CreateRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_restore_verification_plan( + self, + ) -> Callable[ + [gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest], + 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._CreateRestoreVerificationPlan( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def create_restore_verification_plan_association( + self, + ) -> Callable[ + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest + ], + 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._CreateRestoreVerificationPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + @property def delete_auto_protection_policy( self, @@ -10872,6 +14743,44 @@ def delete_management_server( self._session, self._host, self._interceptor ) # type: ignore + @property + def delete_restore_template( + self, + ) -> Callable[ + [restore_template.DeleteRestoreTemplateRequest], 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._DeleteRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.DeleteRestoreVerificationPlanRequest], + 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._DeleteRestoreVerificationPlan( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def delete_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest + ], + 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._DeleteRestoreVerificationPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + @property def fetch_backup_plan_associations_for_resource_type( self, @@ -11039,6 +14948,57 @@ def get_management_server( # In C++ this would require a dynamic_cast return self._GetManagementServer(self._session, self._host, self._interceptor) # type: ignore + @property + def get_restore_template( + self, + ) -> Callable[ + [restore_template.GetRestoreTemplateRequest], restore_template.RestoreTemplate + ]: + # 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._GetRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_restore_template_execution( + self, + ) -> Callable[ + [restore_template_execution.GetRestoreTemplateExecutionRequest], + restore_template_execution.RestoreTemplateExecution, + ]: + # 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._GetRestoreTemplateExecution( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_restore_verification_plan( + self, + ) -> Callable[ + [restore_verification_plan.GetRestoreVerificationPlanRequest], + restore_verification_plan.RestoreVerificationPlan, + ]: + # 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._GetRestoreVerificationPlan( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def get_restore_verification_plan_association( + self, + ) -> Callable[ + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest + ], + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ]: + # 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._GetRestoreVerificationPlanAssociation( + self._session, self._host, self._interceptor + ) # type: ignore + @property def initialize_service( self, @@ -11199,6 +15159,58 @@ def list_management_servers( # In C++ this would require a dynamic_cast return self._ListManagementServers(self._session, self._host, self._interceptor) # type: ignore + @property + def list_restore_template_executions( + self, + ) -> Callable[ + [restore_template_execution.ListRestoreTemplateExecutionsRequest], + restore_template_execution.ListRestoreTemplateExecutionsResponse, + ]: + # 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._ListRestoreTemplateExecutions( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_restore_templates( + self, + ) -> Callable[ + [restore_template.ListRestoreTemplatesRequest], + restore_template.ListRestoreTemplatesResponse, + ]: + # 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._ListRestoreTemplates(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_restore_verification_plan_associations( + self, + ) -> Callable[ + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest + ], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse, + ]: + # 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._ListRestoreVerificationPlanAssociations( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def list_restore_verification_plans( + self, + ) -> Callable[ + [restore_verification_plan.ListRestoreVerificationPlansRequest], + restore_verification_plan.ListRestoreVerificationPlansResponse, + ]: + # 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._ListRestoreVerificationPlans( + self._session, self._host, self._interceptor + ) # type: ignore + @property def restore_backup( self, @@ -11207,6 +15219,16 @@ def restore_backup( # In C++ this would require a dynamic_cast return self._RestoreBackup(self._session, self._host, self._interceptor) # type: ignore + @property + def run_restore_template( + self, + ) -> Callable[ + [restore_template.RunRestoreTemplateRequest], 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._RunRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + @property def trigger_backup( self, @@ -11217,6 +15239,30 @@ def trigger_backup( # In C++ this would require a dynamic_cast return self._TriggerBackup(self._session, self._host, self._interceptor) # type: ignore + @property + def trigger_restore_cleanup( + self, + ) -> Callable[ + [restore_template_execution.TriggerRestoreCleanupRequest], + 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._TriggerRestoreCleanup(self._session, self._host, self._interceptor) # type: ignore + + @property + def trigger_restore_verification( + self, + ) -> Callable[ + [restore_verification_plan_association.TriggerRestoreVerificationRequest], + 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._TriggerRestoreVerification( + self._session, self._host, self._interceptor + ) # type: ignore + @property def update_auto_protection_policy( self, @@ -11275,6 +15321,16 @@ def update_data_source( # In C++ this would require a dynamic_cast return self._UpdateDataSource(self._session, self._host, self._interceptor) # type: ignore + @property + def update_restore_template( + self, + ) -> Callable[ + [gcb_restore_template.UpdateRestoreTemplateRequest], 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._UpdateRestoreTemplate(self._session, self._host, self._interceptor) # type: ignore + @property def get_location(self): return self._GetLocation(self._session, self._host, self._interceptor) # type: ignore diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest_base.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest_base.py index 62ae1ad6bd98..c63cdcdffa66 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest_base.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/services/backup_dr/transports/rest_base.py @@ -36,6 +36,17 @@ backupvault, bindingmatchingresource, datasourcereference, + restore_template, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1beta.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) from .base import DEFAULT_CLIENT_INFO, BackupDRTransport @@ -217,6 +228,63 @@ def _get_http_options(): ] return http_options + class _BaseCreateRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "restoreTemplateId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/restoreTemplates", + "body": "restore_template", + }, + ] + return http_options + + class _BaseCreateRestoreVerificationPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "restoreVerificationPlanId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*}/restoreVerificationPlans", + "body": "restore_verification_plan", + }, + ] + return http_options + + class _BaseCreateRestoreVerificationPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "restoreVerificationPlanAssociationId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*/locations/*/restoreVerificationPlans/*}/associations", + "body": "restore_verification_plan_association", + }, + ] + return http_options + class _BaseDeleteAutoProtectionPolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -313,6 +381,54 @@ def _get_http_options(): ] return http_options + class _BaseDeleteRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/restoreTemplates/*}", + }, + ] + return http_options + + class _BaseDeleteRestoreVerificationPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/restoreVerificationPlans/*}", + }, + ] + return http_options + + class _BaseDeleteRestoreVerificationPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/restoreVerificationPlans/*/associations/*}", + }, + ] + return http_options + class _BaseFetchBackupPlanAssociationsForResourceType: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -559,6 +675,70 @@ def _get_http_options(): ] return http_options + class _BaseGetRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/restoreTemplates/*}", + }, + ] + return http_options + + class _BaseGetRestoreTemplateExecution: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/restoreTemplates/*/executions/*}", + }, + ] + return http_options + + class _BaseGetRestoreVerificationPlan: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/restoreVerificationPlans/*}", + }, + ] + return http_options + + class _BaseGetRestoreVerificationPlanAssociation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/restoreVerificationPlans/*/associations/*}", + }, + ] + return http_options + class _BaseInitializeService: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -785,6 +965,70 @@ def _get_http_options(): ] return http_options + class _BaseListRestoreTemplateExecutions: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/restoreTemplates/*}/executions", + }, + ] + return http_options + + class _BaseListRestoreTemplates: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/restoreTemplates", + }, + ] + return http_options + + class _BaseListRestoreVerificationPlanAssociations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*/restoreVerificationPlans/*}/associations", + }, + ] + return http_options + + class _BaseListRestoreVerificationPlans: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/locations/*}/restoreVerificationPlans", + }, + ] + return http_options + class _BaseRestoreBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -802,6 +1046,23 @@ def _get_http_options(): ] return http_options + class _BaseRunRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/restoreTemplates/*}:run", + "body": "*", + }, + ] + return http_options + class _BaseTriggerBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -819,13 +1080,45 @@ def _get_http_options(): ] return http_options + class _BaseTriggerRestoreCleanup: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/restoreTemplates/*/executions/*}:triggerRestoreCleanup", + "body": "*", + }, + ] + return http_options + + class _BaseTriggerRestoreVerification: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/restoreVerificationPlans/*/associations/*}:triggerRestoreVerification", + "body": "*", + }, + ] + return http_options + class _BaseUpdateAutoProtectionPolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "updateMask": {}, - } + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} @staticmethod def _get_http_options(): @@ -933,6 +1226,23 @@ def _get_http_options(): ] return http_options + class _BaseUpdateRestoreTemplate: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{restore_template.name=projects/*/locations/*/restoreTemplates/*}", + "body": "restore_template", + }, + ] + return http_options + class _BaseGetLocation: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/__init__.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/__init__.py index f5c59a6ebe29..4971836a526c 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/__init__.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/__init__.py @@ -128,6 +128,7 @@ UpdateBackupRequest, UpdateBackupVaultRequest, UpdateDataSourceRequest, + VerificationSummary, ) from .backupvault_alloydb import ( AlloyDBClusterBackupPlanAssociationProperties, @@ -208,6 +209,58 @@ PitrSettings, ResourceBackupConfig, ) +from .restore_template import ( + CreateRestoreTemplateRequest, + DeleteRestoreTemplateRequest, + ExecutionSummary, + GetRestoreTemplateRequest, + ListRestoreTemplatesRequest, + ListRestoreTemplatesResponse, + RestoreTemplate, + RunRestoreTemplateRequest, + RunRestoreTemplateResponse, + UpdateRestoreTemplateRequest, +) +from .restore_template_common import ( + BackupSelectionConfig, + PostRestoreConfig, + PreRestoreConfig, + VerificationConfig, +) +from .restore_template_execution import ( + CleanupPhaseInfo, + GetRestoreTemplateExecutionRequest, + ListRestoreTemplateExecutionsRequest, + ListRestoreTemplateExecutionsResponse, + PhaseState, + PostRestorePhaseInfo, + PreparePhaseInfo, + PreRestorePhaseInfo, + RestorePhaseInfo, + RestoreTemplateExecution, + TriggerRestoreCleanupRequest, + VerificationPhaseInfo, +) +from .restore_verification_plan import ( + CreateRestoreVerificationPlanRequest, + DeleteRestoreVerificationPlanRequest, + GetRestoreVerificationPlanRequest, + ListRestoreVerificationPlansRequest, + ListRestoreVerificationPlansResponse, + RestoreVerificationCleanupRule, + RestoreVerificationPlan, +) +from .restore_verification_plan_association import ( + CreateRestoreVerificationPlanAssociationRequest, + DeleteRestoreVerificationPlanAssociationRequest, + GetRestoreVerificationPlanAssociationRequest, + ListRestoreVerificationPlanAssociationsRequest, + ListRestoreVerificationPlanAssociationsResponse, + RestoreVerificationPlanAssociation, + TriggerRestoreVerificationRequest, + TriggerRestoreVerificationResponse, + TriggerSummary, +) __all__ = ( "AppliedAutoProtectionPolicy", @@ -309,6 +362,7 @@ "UpdateBackupRequest", "UpdateBackupVaultRequest", "UpdateDataSourceRequest", + "VerificationSummary", "BackupConfigState", "BackupVaultView", "BackupView", @@ -375,4 +429,46 @@ "ListResourceBackupConfigsResponse", "PitrSettings", "ResourceBackupConfig", + "CreateRestoreTemplateRequest", + "DeleteRestoreTemplateRequest", + "ExecutionSummary", + "GetRestoreTemplateRequest", + "ListRestoreTemplatesRequest", + "ListRestoreTemplatesResponse", + "RestoreTemplate", + "RunRestoreTemplateRequest", + "RunRestoreTemplateResponse", + "UpdateRestoreTemplateRequest", + "BackupSelectionConfig", + "PostRestoreConfig", + "PreRestoreConfig", + "VerificationConfig", + "CleanupPhaseInfo", + "GetRestoreTemplateExecutionRequest", + "ListRestoreTemplateExecutionsRequest", + "ListRestoreTemplateExecutionsResponse", + "PostRestorePhaseInfo", + "PreparePhaseInfo", + "PreRestorePhaseInfo", + "RestorePhaseInfo", + "RestoreTemplateExecution", + "TriggerRestoreCleanupRequest", + "VerificationPhaseInfo", + "PhaseState", + "CreateRestoreVerificationPlanRequest", + "DeleteRestoreVerificationPlanRequest", + "GetRestoreVerificationPlanRequest", + "ListRestoreVerificationPlansRequest", + "ListRestoreVerificationPlansResponse", + "RestoreVerificationCleanupRule", + "RestoreVerificationPlan", + "CreateRestoreVerificationPlanAssociationRequest", + "DeleteRestoreVerificationPlanAssociationRequest", + "GetRestoreVerificationPlanAssociationRequest", + "ListRestoreVerificationPlanAssociationsRequest", + "ListRestoreVerificationPlanAssociationsResponse", + "RestoreVerificationPlanAssociation", + "TriggerRestoreVerificationRequest", + "TriggerRestoreVerificationResponse", + "TriggerSummary", ) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicy.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicy.py index 562884def56c..8c194e3b2900 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicy.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicy.py @@ -50,11 +50,12 @@ class AutoProtectionPolicy(proto.Message): Attributes: name (str): - Identifier. The resource name of the AutoprotectionPolicy. - Format: + Output only. Identifier. The resource name of the + AutoprotectionPolicy. Format: ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}`` description (str): - Optional. A description of the policy. + Optional. A description of the policy. The + description must be at most 2048 characters. backup_plan_details (MutableSequence[google.cloud.backupdr_v1beta.types.BackupPlanDetail]): Required. The backup plan details for matching resources. @@ -282,7 +283,7 @@ class KeyValuePair(proto.Message): Format:``[\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62}``. values (MutableSequence[str]): Required. The values of the label to match. There will be - explicit “OR” between values of array. Each value must be in + explicit "OR" between values of array. Each value must be in the format ``{label_value}``. The value must match the regex Format: ``[\\p{Ll}\\p{Lo}\\p{N}_-]{1,63}``. """ @@ -309,9 +310,24 @@ class CreateAutoProtectionPolicyRequest(proto.Message): Required. The ID to use for the policy. This will become the final component of the policy's resource name. + + This value must start with a lowercase letter + followed by up to 62 lowercase letters, numbers, + or hyphens, and cannot end with a hyphen. auto_protection_policy (google.cloud.backupdr_v1beta.types.AutoProtectionPolicy): Required. The AutoProtectionPolicy resource 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. + + 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( @@ -327,6 +343,10 @@ class CreateAutoProtectionPolicyRequest(proto.Message): number=3, message="AutoProtectionPolicy", ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) class GetAutoProtectionPolicyRequest(proto.Message): @@ -351,12 +371,23 @@ class UpdateAutoProtectionPolicyRequest(proto.Message): auto_protection_policy (google.cloud.backupdr_v1beta.types.AutoProtectionPolicy): Required. The policy to update. update_mask (google.protobuf.field_mask_pb2.FieldMask): - Required. Field mask is used to specify the fields to be + Optional. Field mask is used to specify the fields to be overwritten in the AutoProtectionPolicy resource by the update. The fields specified in the update_mask are relative to the resource, not the full request. A field will be overwritten if it is in the mask. If the user does not provide a mask then all fields will be overwritten. + 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. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). """ auto_protection_policy: "AutoProtectionPolicy" = proto.Field( @@ -369,6 +400,10 @@ class UpdateAutoProtectionPolicyRequest(proto.Message): number=2, message=field_mask_pb2.FieldMask, ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) class DeleteAutoProtectionPolicyRequest(proto.Message): @@ -379,10 +414,22 @@ class DeleteAutoProtectionPolicyRequest(proto.Message): Required. The name of the policy to delete. Format: projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy} etag (str): - The current etag of the AutoProtectionPolicy. - If an etag is provided and does not match the - current etag of the connection, the request will - be rejected with an ABORTED error. + Optional. The current etag of the + AutoProtectionPolicy. If an etag is provided and + does not match the current etag of the + connection, the request will be rejected with an + ABORTED error. + 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. + + 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( @@ -393,6 +440,10 @@ class DeleteAutoProtectionPolicyRequest(proto.Message): proto.STRING, number=2, ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) class ListAutoProtectionPoliciesRequest(proto.Message): @@ -455,7 +506,8 @@ class ListAutoProtectionPoliciesResponse(proto.Message): next page. If this field is omitted, there are no subsequent pages. unreachable (MutableSequence[str]): - Locations that could not be reached. + Unordered list. Locations that could not be + reached. """ @property diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicybinding.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicybinding.py index f0c5c3900a71..ffe4d0cd677d 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicybinding.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/autoprotectionpolicybinding.py @@ -41,11 +41,12 @@ class AutoProtectionPolicyBinding(proto.Message): Attributes: name (str): - Identifier. The resource name of the + Output only. Identifier. The resource name of the AutoProtectionPolicyBinding. Format: ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}`` description (str): - Optional. A description of the binding. + Optional. A description of the binding. The + description must be at most 2048 characters. state (google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding.State): Output only. The current state of the AutoProtectionPolicyBinding. @@ -64,9 +65,9 @@ class AutoProtectionPolicyBinding(proto.Message): Output only. The timestamp when the binding was last updated. etag (str): - Optional. Output only. The etag for the - binding. If this is provided on update, it must - match the server's etag. + Output only. The etag for the binding. + If this is provided on update, it must match the + server's etag. """ class State(proto.Enum): @@ -169,9 +170,24 @@ class CreateAutoProtectionPolicyBindingRequest(proto.Message): Required. The ID to use for the binding. This will become the final component of the binding's resource name. + + This value must start with a lowercase letter + followed by up to 62 lowercase letters, numbers, + or hyphens, and cannot end with a hyphen. auto_protection_policy_binding (google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding): Required. The AutoProtectionPolicyBinding resource 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. + + 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( @@ -187,6 +203,10 @@ class CreateAutoProtectionPolicyBindingRequest(proto.Message): number=3, message="AutoProtectionPolicyBinding", ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) class GetAutoProtectionPolicyBindingRequest(proto.Message): @@ -297,12 +317,37 @@ class InitiateDeleteAutoProtectionPolicyBindingRequest(proto.Message): name (str): Required. The name of the binding to delete. Format: projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding} + etag (str): + Optional. The current etag of the + AutoProtectionPolicyBinding. If an etag is + provided and does not match the current etag of + the binding, deletion will be blocked and an + ABORTED error will be returned. + 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. + + 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, ) + etag: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault.py index 06f7db5ab771..53fbcdc6f0f1 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/backupvault.py @@ -48,6 +48,7 @@ "BackupApplianceLockInfo", "BackupLock", "Backup", + "VerificationSummary", "CreateBackupVaultRequest", "ListBackupVaultsRequest", "ListBackupVaultsResponse", @@ -1212,6 +1213,9 @@ class Backup(proto.Message): kms_key_versions (MutableSequence[str]): Optional. Output only. The list of KMS key versions used to encrypt the backup. + verification_summary (google.cloud.backupdr_v1beta.types.VerificationSummary): + Output only. The restore verification status + of the backup. """ class State(proto.Enum): @@ -1443,6 +1447,59 @@ class GCPBackupPlanInfo(proto.Message): proto.STRING, number=33, ) + verification_summary: "VerificationSummary" = proto.Field( + proto.MESSAGE, + number=37, + message="VerificationSummary", + ) + + +class VerificationSummary(proto.Message): + r"""VerificationSummary contains the status and timestamp of the + latest Automated Verification test. + + Attributes: + last_verification_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup was + last verified. + last_verification_state (google.cloud.backupdr_v1beta.types.VerificationSummary.LastVerificationState): + Output only. The state of the last + verification. + last_verification_execution (str): + Output only. The last verification execution. + """ + + class LastVerificationState(proto.Enum): + r"""LastVerificationState represents the state of the + verification. + + Values: + STATE_UNSPECIFIED (0): + Verification state is unspecified. + SUCCEEDED (1): + Verification succeeded. + FAILED (2): + Verification failed. + """ + + STATE_UNSPECIFIED = 0 + SUCCEEDED = 1 + FAILED = 2 + + last_verification_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + last_verification_state: LastVerificationState = proto.Field( + proto.ENUM, + number=2, + enum=LastVerificationState, + ) + last_verification_execution: str = proto.Field( + proto.STRING, + number=3, + ) class CreateBackupVaultRequest(proto.Message): diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/bindingmatchingresource.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/bindingmatchingresource.py index 6b5e6b15f218..def0410b981c 100644 --- a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/bindingmatchingresource.py +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/bindingmatchingresource.py @@ -144,12 +144,12 @@ class BindingMatchingResource(proto.Message): Attributes: name (str): - Identifier. The resource name of the + Output only. Identifier. The resource name of the ``BindingMatchingResource``. Format: ``projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource}`` resource (str): - Required. Immutable. Resource name of the workload that - matches the criteria of the binding. + Output only. Resource name of the workload that matches the + criteria of the binding. The format can be either a relative resource name (e.g., ``projects/my-project/zones/us-central1-a/instances/my-instance``) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_template.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_template.py new file mode 100644 index 000000000000..22f845713028 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_template.py @@ -0,0 +1,493 @@ +# -*- 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 google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +from google.cloud.backupdr_v1beta.types import restore_template_common +from google.cloud.backupdr_v1beta.types import ( + restore_template_execution as gcb_restore_template_execution, +) + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "RestoreTemplate", + "ExecutionSummary", + "CreateRestoreTemplateRequest", + "GetRestoreTemplateRequest", + "UpdateRestoreTemplateRequest", + "DeleteRestoreTemplateRequest", + "RunRestoreTemplateRequest", + "RunRestoreTemplateResponse", + "ListRestoreTemplatesRequest", + "ListRestoreTemplatesResponse", + }, +) + + +class RestoreTemplate(proto.Message): + r"""A ``RestoreTemplate`` encapsulates DR readiness configurations for + validating backups. + + Attributes: + name (str): + Identifier. The resource name of the + RestoreTemplate. + description (str): + Optional. User-provided description of the + restore template. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore + template was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the restore + template was last updated. + resource_type (str): + Required. Immutable. The specific type of the workload being + restored. The format is "{service_name}/{resource_kind}", + for example, "compute.googleapis.com/Instance". + labels (MutableMapping[str, str]): + Optional. User-defined labels. + backup_selection_config (google.cloud.backupdr_v1beta.types.BackupSelectionConfig): + Required. Backup selection configuration. + pre_restore_config (google.cloud.backupdr_v1beta.types.PreRestoreConfig): + Optional. Pre-restore configuration. + post_restore_config (google.cloud.backupdr_v1beta.types.PostRestoreConfig): + Optional. Post-restore configuration. + verification_config (google.cloud.backupdr_v1beta.types.VerificationConfig): + Optional. Verification configuration. + restore_properties (google.protobuf.struct_pb2.Struct): + Required. Defines target environments where the resource + will be restored. + + The target resource name in ``restore_properties`` supports + the ``{EXECUTION_ID}`` token to dynamically generate unique + resource names for each execution. During restore execution, + every occurrence of ``{EXECUTION_ID}`` in the target + resource name is replaced with the 8-character + ``RestoreTemplateExecution`` ID (for example, + ``"restored-resource-{EXECUTION_ID}"`` or + ``"restored-{EXECUTION_ID}-resource"`` resolves to + ``"restored-resource-5d437b06"`` or + ``"restored-5d437b06-resource"``). + state (google.cloud.backupdr_v1beta.types.RestoreTemplate.State): + Output only. The state of the restore + template. + execution_summary (google.cloud.backupdr_v1beta.types.ExecutionSummary): + Output only. Summary of the last execution. + etag (str): + Optional. Etag for concurrency control. + """ + + class State(proto.Enum): + r"""The state of the RestoreTemplate. + + Values: + STATE_UNSPECIFIED (0): + State not specified. + CREATING (1): + The template is being created. + ACTIVE (2): + The template is active and ready to use. + UPDATING (3): + The template is being updated. + DELETING (4): + The template is being deleted. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + UPDATING = 3 + DELETING = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + resource_type: str = proto.Field( + proto.STRING, + number=5, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + backup_selection_config: restore_template_common.BackupSelectionConfig = ( + proto.Field( + proto.MESSAGE, + number=7, + message=restore_template_common.BackupSelectionConfig, + ) + ) + pre_restore_config: restore_template_common.PreRestoreConfig = proto.Field( + proto.MESSAGE, + number=8, + message=restore_template_common.PreRestoreConfig, + ) + post_restore_config: restore_template_common.PostRestoreConfig = proto.Field( + proto.MESSAGE, + number=9, + message=restore_template_common.PostRestoreConfig, + ) + verification_config: restore_template_common.VerificationConfig = proto.Field( + proto.MESSAGE, + number=10, + message=restore_template_common.VerificationConfig, + ) + restore_properties: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=11, + message=struct_pb2.Struct, + ) + state: State = proto.Field( + proto.ENUM, + number=12, + enum=State, + ) + execution_summary: "ExecutionSummary" = proto.Field( + proto.MESSAGE, + number=13, + message="ExecutionSummary", + ) + etag: str = proto.Field( + proto.STRING, + number=14, + ) + + +class ExecutionSummary(proto.Message): + r"""Summary of the last execution. + + Attributes: + last_execution (str): + Output only. The resource name of the last execution. + Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}`` + last_execution_state (google.cloud.backupdr_v1beta.types.RestoreTemplateExecution.ExecutionState): + Output only. The state of the last execution. + """ + + last_execution: str = proto.Field( + proto.STRING, + number=1, + ) + last_execution_state: gcb_restore_template_execution.RestoreTemplateExecution.ExecutionState = proto.Field( + proto.ENUM, + number=2, + enum=gcb_restore_template_execution.RestoreTemplateExecution.ExecutionState, + ) + + +class CreateRestoreTemplateRequest(proto.Message): + r"""Request message for creating a RestoreTemplate instance. + + Attributes: + parent (str): + Required. The restore template project and location in the + format 'projects/{project_id}/locations/{location}'. + restore_template_id (str): + Required. The ID of the restore template to + create. The ID must be unique for the specified + project and location. + restore_template (google.cloud.backupdr_v1beta.types.RestoreTemplate): + Required. A RestoreTemplate resource. + 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 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, + ) + restore_template_id: str = proto.Field( + proto.STRING, + number=2, + ) + restore_template: "RestoreTemplate" = proto.Field( + proto.MESSAGE, + number=3, + message="RestoreTemplate", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetRestoreTemplateRequest(proto.Message): + r"""Request message for getting a RestoreTemplate instance. + + Attributes: + name (str): + Required. The name of the restore template to retrieve. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}' + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class UpdateRestoreTemplateRequest(proto.Message): + r"""Request message for updating a RestoreTemplate instance. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to update. Field mask is used + to specify the fields to be overwritten in the + RestoreTemplate resource by the update. The fields specified + in the update_mask are relative to the resource, not the + full request. A field will be overwritten if it is in the + mask. + restore_template (google.cloud.backupdr_v1beta.types.RestoreTemplate): + Required. The restore template 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 request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + validate_only (bool): + Optional. Only validate the request, but do + not perform mutations. The default is 'false'. + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + restore_template: "RestoreTemplate" = proto.Field( + proto.MESSAGE, + number=2, + message="RestoreTemplate", + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=4, + ) + + +class DeleteRestoreTemplateRequest(proto.Message): + r"""Request message for deleting a RestoreTemplate instance. + + Attributes: + name (str): + Required. The name of the restore template to delete. + Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}' + 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 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 child + RestoreTemplateExecutions will also be deleted. + If false and the RestoreTemplate has any child + executions, the request will fail. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class RunRestoreTemplateRequest(proto.Message): + r"""Request message for running a RestoreTemplate. + + Attributes: + name (str): + Required. The name of the restore template to run. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}' + backup (str): + Optional. The resource name of the Backup to restore from. + If not specified, the latest backup matching the backup + selection configuration in the RestoreTemplate will be used. + Format: + 'projects/{project}/locations/{location}/backupVaults/{backup_vault}/dataSources/{data_source}/backups/{backup}' + 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 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, + ) + backup: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class RunRestoreTemplateResponse(proto.Message): + r"""Response message for RunRestoreTemplate. + + Attributes: + restore_template_execution (str): + Output only. The resource name of the initiated + RestoreTemplateExecution. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}`` + """ + + restore_template_execution: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRestoreTemplatesRequest(proto.Message): + r"""Request message for listing RestoreTemplates. + + Attributes: + parent (str): + Required. The project and location from which to list the + restore templates. Format: + ``projects/{project}/locations/{location}``. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. A page token, received from a previous + ``ListRestoreTemplates`` call. + filter (str): + Optional. Field match expression used to + filter the results. + order_by (str): + Optional. Field by which to sort the results. + """ + + 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 ListRestoreTemplatesResponse(proto.Message): + r"""Response message for listing RestoreTemplates. + + Attributes: + restore_templates (MutableSequence[google.cloud.backupdr_v1beta.types.RestoreTemplate]): + The list of RestoreTemplates. + next_page_token (str): + A token which may be sent as ``page_token`` in a subsequent + ``ListRestoreTemplates`` call. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + restore_templates: MutableSequence["RestoreTemplate"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="RestoreTemplate", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_template_common.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_template_common.py new file mode 100644 index 000000000000..5d02f99d89e1 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_template_common.py @@ -0,0 +1,141 @@ +# -*- 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 google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "BackupSelectionConfig", + "PreRestoreConfig", + "PostRestoreConfig", + "VerificationConfig", + }, +) + + +class BackupSelectionConfig(proto.Message): + r"""Configuration for selecting a backup. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + data_source (str): + Required. Immutable. The fully qualified URI + of the backupdr data source. + + This field is a member of `oneof`_ ``source``. + """ + + data_source: str = proto.Field( + proto.STRING, + number=1, + oneof="source", + ) + + +class PreRestoreConfig(proto.Message): + r"""Configuration for Pre-Restore. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_run_job (str): + Cloud Run job action to execute. Format: + ``projects/{project}/locations/{location}/jobs/{job}`` + + This field is a member of `oneof`_ ``pre_restore_action``. + timeout (google.protobuf.duration_pb2.Duration): + Optional. The timeout for this phase. + If set, the timeout must be positive and less + than or equal to 24 hours (86400s). + """ + + cloud_run_job: str = proto.Field( + proto.STRING, + number=2, + oneof="pre_restore_action", + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + +class PostRestoreConfig(proto.Message): + r"""Configuration for Post-Restore. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_run_job (str): + Cloud Run job action to execute. Format: + ``projects/{project}/locations/{location}/jobs/{job}`` + + This field is a member of `oneof`_ ``post_restore_action``. + timeout (google.protobuf.duration_pb2.Duration): + Optional. The timeout for this phase. + If set, the timeout must be positive and less + than or equal to 24 hours (86400s). + """ + + cloud_run_job: str = proto.Field( + proto.STRING, + number=2, + oneof="post_restore_action", + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + +class VerificationConfig(proto.Message): + r"""Configuration for Verification. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_run_job (str): + Cloud Run job action to execute. Format: + ``projects/{project}/locations/{location}/jobs/{job}`` + + This field is a member of `oneof`_ ``verification_action``. + timeout (google.protobuf.duration_pb2.Duration): + Optional. The timeout for this phase. + If set, the timeout must be positive and less + than or equal to 24 hours (86400s). + """ + + cloud_run_job: str = proto.Field( + proto.STRING, + number=2, + oneof="verification_action", + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_template_execution.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_template_execution.py new file mode 100644 index 000000000000..94036e357ff9 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_template_execution.py @@ -0,0 +1,753 @@ +# -*- 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 google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.struct_pb2 as struct_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 + +from google.cloud.backupdr_v1beta.types import ( + restore_template_common, + restore_verification_plan, +) + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "PhaseState", + "RestoreTemplateExecution", + "PreparePhaseInfo", + "PreRestorePhaseInfo", + "RestorePhaseInfo", + "PostRestorePhaseInfo", + "VerificationPhaseInfo", + "CleanupPhaseInfo", + "GetRestoreTemplateExecutionRequest", + "TriggerRestoreCleanupRequest", + "ListRestoreTemplateExecutionsRequest", + "ListRestoreTemplateExecutionsResponse", + }, +) + + +class PhaseState(proto.Enum): + r"""Represents the state of a specific phase (RUNNING, SUCCEEDED, + FAILED, etc.). + + Values: + PHASE_STATE_UNSPECIFIED (0): + Phase state is not set. + PENDING (1): + This phase is pending execution. + RUNNING (2): + The phase is actively executing. + SUCCEEDED (3): + The phase completed successfully. + FAILED (4): + The phase encountered an error and failed. + TIMED_OUT (5): + The phase timed out. + SKIPPED (6): + The phase was skipped. + WAITING (7): + The phase is waiting to be executed. + """ + + PHASE_STATE_UNSPECIFIED = 0 + PENDING = 1 + RUNNING = 2 + SUCCEEDED = 3 + FAILED = 4 + TIMED_OUT = 5 + SKIPPED = 6 + WAITING = 7 + + +class RestoreTemplateExecution(proto.Message): + r"""A ``RestoreTemplateExecution`` represents a single historical or + active execution run. + + Attributes: + name (str): + Identifier. Resource name of the execution. + resource_type (str): + Output only. The workload resource type being restored. The + format is "{service_name}/{resource_kind}", for example, + "compute.googleapis.com/Instance". + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time of the execution. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Update time of the execution. + type_ (google.cloud.backupdr_v1beta.types.RestoreTemplateExecution.ExecutionType): + Output only. The type of the execution. + phase (google.cloud.backupdr_v1beta.types.RestoreTemplateExecution.ExecutionPhase): + Output only. The current active phase. + state (google.cloud.backupdr_v1beta.types.RestoreTemplateExecution.ExecutionState): + Output only. State of the execution. + prepare_phase_info (google.cloud.backupdr_v1beta.types.PreparePhaseInfo): + Output only. Info for the prepare phase. + pre_restore_phase_info (google.cloud.backupdr_v1beta.types.PreRestorePhaseInfo): + Output only. Info for the pre-restore phase. + restore_phase_info (google.cloud.backupdr_v1beta.types.RestorePhaseInfo): + Output only. Info for the restore phase. + post_restore_phase_info (google.cloud.backupdr_v1beta.types.PostRestorePhaseInfo): + Output only. Info for the post-restore phase. + verification_phase_info (google.cloud.backupdr_v1beta.types.VerificationPhaseInfo): + Output only. Info for the verification phase. + cleanup_phase_info (google.cloud.backupdr_v1beta.types.CleanupPhaseInfo): + Output only. Info for the cleanup phase. + """ + + class ExecutionType(proto.Enum): + r"""The type of execution. + + Values: + EXECUTION_TYPE_UNSPECIFIED (0): + Execution type not specified. + SCHEDULED (1): + Scheduled execution. + ON_DEMAND (2): + On-demand execution. + """ + + EXECUTION_TYPE_UNSPECIFIED = 0 + SCHEDULED = 1 + ON_DEMAND = 2 + + class ExecutionPhase(proto.Enum): + r"""The phase of execution. + + Values: + EXECUTION_PHASE_UNSPECIFIED (0): + Execution phase not specified. + PREPARING (1): + Preparing for execution. + EXECUTING_PRE_RESTORE_ACTION (2): + Executing pre-restore action. + RESTORING (3): + Restoring the resource. + EXECUTING_POST_RESTORE_ACTION (4): + Executing post-restore action. + VERIFYING (5): + Verifying the restored resource. + CLEANING_UP (6): + Cleaning up resources. + COMPLETED (7): + Execution completed. + """ + + EXECUTION_PHASE_UNSPECIFIED = 0 + PREPARING = 1 + EXECUTING_PRE_RESTORE_ACTION = 2 + RESTORING = 3 + EXECUTING_POST_RESTORE_ACTION = 4 + VERIFYING = 5 + CLEANING_UP = 6 + COMPLETED = 7 + + class ExecutionState(proto.Enum): + r"""State of the execution. + + Values: + EXECUTION_STATE_UNSPECIFIED (0): + State not set. + RUNNING (1): + Execution is running. + SUCCEEDED (2): + Execution succeeded. + FAILED (3): + Execution failed. + DELETING (4): + Resources are being deleted (cleanup). + """ + + EXECUTION_STATE_UNSPECIFIED = 0 + RUNNING = 1 + SUCCEEDED = 2 + FAILED = 3 + DELETING = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + resource_type: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + type_: ExecutionType = proto.Field( + proto.ENUM, + number=5, + enum=ExecutionType, + ) + phase: ExecutionPhase = proto.Field( + proto.ENUM, + number=6, + enum=ExecutionPhase, + ) + state: ExecutionState = proto.Field( + proto.ENUM, + number=7, + enum=ExecutionState, + ) + prepare_phase_info: "PreparePhaseInfo" = proto.Field( + proto.MESSAGE, + number=8, + message="PreparePhaseInfo", + ) + pre_restore_phase_info: "PreRestorePhaseInfo" = proto.Field( + proto.MESSAGE, + number=9, + message="PreRestorePhaseInfo", + ) + restore_phase_info: "RestorePhaseInfo" = proto.Field( + proto.MESSAGE, + number=10, + message="RestorePhaseInfo", + ) + post_restore_phase_info: "PostRestorePhaseInfo" = proto.Field( + proto.MESSAGE, + number=11, + message="PostRestorePhaseInfo", + ) + verification_phase_info: "VerificationPhaseInfo" = proto.Field( + proto.MESSAGE, + number=12, + message="VerificationPhaseInfo", + ) + cleanup_phase_info: "CleanupPhaseInfo" = proto.Field( + proto.MESSAGE, + number=13, + message="CleanupPhaseInfo", + ) + + +class PreparePhaseInfo(proto.Message): + r"""Info for Prepare phase execution. + + Attributes: + phase_state (google.cloud.backupdr_v1beta.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + backup_selection_config (google.cloud.backupdr_v1beta.types.BackupSelectionConfig): + Output only. Snapshot of config used in this + execution. + backup (str): + Output only. The source backup used for the + restore. The fully qualified URI of the backupdr + backup. + is_backup_explicitly_passed (bool): + Output only. Indicates whether the backup was + explicitly passed in the request. + restore_verification_plan_association (str): + Output only. The restore verification plan + association associated with the execution. + """ + + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + backup_selection_config: restore_template_common.BackupSelectionConfig = ( + proto.Field( + proto.MESSAGE, + number=5, + message=restore_template_common.BackupSelectionConfig, + ) + ) + backup: str = proto.Field( + proto.STRING, + number=6, + ) + is_backup_explicitly_passed: bool = proto.Field( + proto.BOOL, + number=7, + ) + restore_verification_plan_association: str = proto.Field( + proto.STRING, + number=8, + ) + + +class PreRestorePhaseInfo(proto.Message): + r"""Info for Pre-Restore phase execution. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_run_execution (str): + Output only. The fully qualified URI of the + Cloud Run Execution triggered for pre-restore + actions. + + This field is a member of `oneof`_ ``result``. + phase_state (google.cloud.backupdr_v1beta.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + pre_restore_config (google.cloud.backupdr_v1beta.types.PreRestoreConfig): + Output only. Snapshot of config that will be + executed before restore operation. + """ + + cloud_run_execution: str = proto.Field( + proto.STRING, + number=6, + oneof="result", + ) + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + pre_restore_config: restore_template_common.PreRestoreConfig = proto.Field( + proto.MESSAGE, + number=5, + message=restore_template_common.PreRestoreConfig, + ) + + +class RestorePhaseInfo(proto.Message): + r"""Info for Restore phase execution. + + Attributes: + phase_state (google.cloud.backupdr_v1beta.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + restore_properties (google.protobuf.struct_pb2.Struct): + Output only. Snapshot of environment config + used during restore of this + RestoreTemplateExecution. + restore_resource (str): + Output only. The resource created or restored + by this execution. + restore_duration (google.protobuf.duration_pb2.Duration): + Output only. Time taken to restore the + resource. + """ + + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + restore_properties: struct_pb2.Struct = proto.Field( + proto.MESSAGE, + number=5, + message=struct_pb2.Struct, + ) + restore_resource: str = proto.Field( + proto.STRING, + number=7, + ) + restore_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class PostRestorePhaseInfo(proto.Message): + r"""Info for Post-Restore phase execution. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_run_execution (str): + Output only. The fully qualified URI of the + Cloud Run Execution triggered for post-restore + actions. + + This field is a member of `oneof`_ ``result``. + phase_state (google.cloud.backupdr_v1beta.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + post_restore_config (google.cloud.backupdr_v1beta.types.PostRestoreConfig): + Output only. Snapshot of config that will be + executed after successful restore operation. + """ + + cloud_run_execution: str = proto.Field( + proto.STRING, + number=6, + oneof="result", + ) + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + post_restore_config: restore_template_common.PostRestoreConfig = proto.Field( + proto.MESSAGE, + number=5, + message=restore_template_common.PostRestoreConfig, + ) + + +class VerificationPhaseInfo(proto.Message): + r"""Info for Verification phase execution. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cloud_run_execution (str): + Output only. The fully qualified URI of the + Cloud Run Execution triggered for verification. + + This field is a member of `oneof`_ ``result``. + phase_state (google.cloud.backupdr_v1beta.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + verification_config (google.cloud.backupdr_v1beta.types.VerificationConfig): + Output only. Snapshot of config that will be + executed after successful post restore + validation. + """ + + cloud_run_execution: str = proto.Field( + proto.STRING, + number=6, + oneof="result", + ) + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + verification_config: restore_template_common.VerificationConfig = proto.Field( + proto.MESSAGE, + number=5, + message=restore_template_common.VerificationConfig, + ) + + +class CleanupPhaseInfo(proto.Message): + r"""Info for Cleanup phase execution. + + Attributes: + phase_state (google.cloud.backupdr_v1beta.types.PhaseState): + Output only. The state of this phase. + error (google.rpc.status_pb2.Status): + Output only. Error details if the phase + failed. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Start time of the phase. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. End time of the phase. + cleanup_duration (google.protobuf.duration_pb2.Duration): + Output only. Time taken to perform the + cleanup of restored resource. + success_cleanup_rule (google.cloud.backupdr_v1beta.types.RestoreVerificationCleanupRule): + Output only. Snapshot of cleanup rule + provided for this execution when execution is + successful. + failure_cleanup_rule (google.cloud.backupdr_v1beta.types.RestoreVerificationCleanupRule): + Output only. Snapshot of cleanup rule + provided for this execution when execution is + failed. + cleanup_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the resources will + be cleaned up. + """ + + phase_state: "PhaseState" = proto.Field( + proto.ENUM, + number=1, + enum="PhaseState", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + cleanup_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + success_cleanup_rule: restore_verification_plan.RestoreVerificationCleanupRule = ( + proto.Field( + proto.MESSAGE, + number=6, + message=restore_verification_plan.RestoreVerificationCleanupRule, + ) + ) + failure_cleanup_rule: restore_verification_plan.RestoreVerificationCleanupRule = ( + proto.Field( + proto.MESSAGE, + number=7, + message=restore_verification_plan.RestoreVerificationCleanupRule, + ) + ) + cleanup_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + + +class GetRestoreTemplateExecutionRequest(proto.Message): + r"""Request message for getting a RestoreTemplateExecution + instance. + + Attributes: + name (str): + Required. The name of the restore template execution to + retrieve. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_id}' + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class TriggerRestoreCleanupRequest(proto.Message): + r"""Request message for triggering a restore cleanup. + + Attributes: + name (str): + Required. Name of the restore template execution. Format: + 'projects/{project_id}/locations/{location}/restoreTemplates/{restore_template_id}/executions/{execution_id}' + 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. + + 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 ListRestoreTemplateExecutionsRequest(proto.Message): + r"""Request message for listing RestoreTemplateExecutions. + + Attributes: + parent (str): + Required. The project, location, and restore template for + which to retrieve executions information. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}``. + page_size (int): + Optional. Requested page size. + page_token (str): + Optional. A token identifying a page of + results. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + 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 ListRestoreTemplateExecutionsResponse(proto.Message): + r"""Response message for listing RestoreTemplateExecutions. + + Attributes: + restore_template_executions (MutableSequence[google.cloud.backupdr_v1beta.types.RestoreTemplateExecution]): + The list of RestoreTemplateExecution + instances. + next_page_token (str): + A token identifying a page of results. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + restore_template_executions: MutableSequence["RestoreTemplateExecution"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="RestoreTemplateExecution", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_verification_plan.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_verification_plan.py new file mode 100644 index 000000000000..ec7e1aca64d5 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_verification_plan.py @@ -0,0 +1,438 @@ +# -*- 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 google.protobuf.duration_pb2 as duration_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.backupdr.v1beta", + manifest={ + "RestoreVerificationPlan", + "RestoreVerificationCleanupRule", + "CreateRestoreVerificationPlanRequest", + "GetRestoreVerificationPlanRequest", + "ListRestoreVerificationPlansRequest", + "ListRestoreVerificationPlansResponse", + "DeleteRestoreVerificationPlanRequest", + }, +) + + +class RestoreVerificationPlan(proto.Message): + r"""A ``RestoreVerificationPlan`` specifies the scheduling and clean-up + template for automated restore verification. It contains a + ``schedule`` to dictate when the verifications should run, and a + ``RestoreVerificationCleanupRule`` for post-verification resource + deletion. + + Attributes: + name (str): + Output only. Identifier. The resource name of the + ``RestoreVerificationPlan``. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + description (str): + Optional. The description of the ``RestoreVerificationPlan`` + resource. + + The description allows for additional details about + ``RestoreVerificationPlan`` and its use cases to be + provided. An example description is the following: "This is + a restore verification plan that performs a daily + verification and cleans up the resources immediately after." + The description must be at most 2048 characters. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the ``RestoreVerificationPlan`` was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the ``RestoreVerificationPlan`` was last + updated. + labels (MutableMapping[str, str]): + Optional. User-defined labels. + state (google.cloud.backupdr_v1beta.types.RestoreVerificationPlan.State): + Output only. The ``State`` for the + ``RestoreVerificationPlan``. + schedule (str): + Required. Describes the schedule on which the restore + verification will be executed. + + The schedule is specified as a + `Crontab `__ + string. + time_zone (str): + Optional. Specifies the time zone to be used in interpreting + [schedule][google.cloud.backupdr.v1beta.RestoreVerificationPlan.schedule]. + The value of this field must be a time zone name from the + `tz database `__, + like "America/New_York" or "UTC". Defaults to ``UTC`` if not + specified. + success_cleanup_rule (google.cloud.backupdr_v1beta.types.RestoreVerificationCleanupRule): + Optional. The cleanup rule to apply if the + restore verification succeeds. + failure_cleanup_rule (google.cloud.backupdr_v1beta.types.RestoreVerificationCleanupRule): + Optional. The cleanup rule to apply if the + restore verification fails. + """ + + class State(proto.Enum): + r"""``State`` enumerates the possible states for a + ``RestoreVerificationPlan``. + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The resource is being created. + ACTIVE (2): + The resource has been created and is fully + usable. + DELETING (3): + The resource is being deleted. + INACTIVE (4): + The resource has been created but is not + usable. + UPDATING (5): + The resource is being updated. + ERROR (6): + The resource is in an error state due to a + configuration issue. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + INACTIVE = 4 + UPDATING = 5 + ERROR = 6 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=5, + ) + state: State = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + schedule: str = proto.Field( + proto.STRING, + number=7, + ) + time_zone: str = proto.Field( + proto.STRING, + number=8, + ) + success_cleanup_rule: "RestoreVerificationCleanupRule" = proto.Field( + proto.MESSAGE, + number=9, + message="RestoreVerificationCleanupRule", + ) + failure_cleanup_rule: "RestoreVerificationCleanupRule" = proto.Field( + proto.MESSAGE, + number=10, + message="RestoreVerificationCleanupRule", + ) + + +class RestoreVerificationCleanupRule(proto.Message): + r"""Defines the specific cleanup action. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cleanup_delay (google.protobuf.duration_pb2.Duration): + Optional. Duration after restore finishes + when cleanup triggers. Delay must be + non-negative and at most 30 days (2592000 + seconds). + skip_cleanup (bool): + Optional. If set to true, the restored + resource will not be cleaned up. + + This field is a member of `oneof`_ ``_skip_cleanup``. + """ + + cleanup_delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + skip_cleanup: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + +class CreateRestoreVerificationPlanRequest(proto.Message): + r"""The request message for creating a ``RestoreVerificationPlan``. + + Attributes: + parent (str): + Required. The ``RestoreVerificationPlan`` project and + location in the format + ``projects/{project}/locations/{location}``. In Google Cloud + Backup and DR locations map to Google Cloud regions, for + example **us-central1**. + restore_verification_plan_id (str): + Required. The name of the ``RestoreVerificationPlan`` to + create. The name must be unique for the specified project + and location. The name must start with a lowercase letter + followed by up to 62 lowercase letters, numbers, or hyphens. + Pattern, ``^[a-z]([-a-z0-9]*[a-z0-9])?$``. + restore_verification_plan (google.cloud.backupdr_v1beta.types.RestoreVerificationPlan): + Required. The ``RestoreVerificationPlan`` resource object 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, + ) + restore_verification_plan_id: str = proto.Field( + proto.STRING, + number=2, + ) + restore_verification_plan: "RestoreVerificationPlan" = proto.Field( + proto.MESSAGE, + number=3, + message="RestoreVerificationPlan", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetRestoreVerificationPlanRequest(proto.Message): + r"""The request message for getting a ``RestoreVerificationPlan``. + + Attributes: + name (str): + Required. The resource name of the + ``RestoreVerificationPlan`` to retrieve. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRestoreVerificationPlansRequest(proto.Message): + r"""The request message for getting a list of + ``RestoreVerificationPlans``. + + Attributes: + parent (str): + Required. The project and location for which to retrieve + ``RestoreVerificationPlans`` information. Format: + ``projects/{project}/locations/{location}``. In Google Cloud + Backup and DR, locations map to Google Cloud regions, for + example **us-central1**. To retrieve restore verification + plans for all locations, use "-" for the ``{location}`` + value. + page_size (int): + Optional. The maximum number of ``RestoreVerificationPlans`` + to return in a single response. If not specified, a default + value will be chosen by the service. Note that the response + may include a partial list and a caller should only rely on + the response's + [next_page_token][google.cloud.backupdr.v1beta.ListRestoreVerificationPlansResponse.next_page_token] + to determine if there are more instances left to be queried. + page_token (str): + Optional. The value of + [next_page_token][google.cloud.backupdr.v1beta.ListRestoreVerificationPlansResponse.next_page_token] + received from a previous ``ListRestoreVerificationPlans`` + call. Provide this to retrieve the subsequent page in a + multi-page list of results. When paginating, all other + parameters provided to ``ListRestoreVerificationPlans`` must + match the call that provided the page token. + filter (str): + Optional. Field match expression used to + filter the results. + order_by (str): + Optional. Field by which to sort the results. + """ + + 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 ListRestoreVerificationPlansResponse(proto.Message): + r"""The response message for getting a list of + ``RestoreVerificationPlans``. + + Attributes: + restore_verification_plans (MutableSequence[google.cloud.backupdr_v1beta.types.RestoreVerificationPlan]): + The list of ``RestoreVerificationPlans`` in the project for + the specified location. + + If the ``{location}`` value in the request is "-", the + response contains a list of resources from all locations. In + case any location is unreachable, the response will only + return restore verification plans in reachable locations and + the 'unreachable' field will be populated with a list of + unreachable locations. + next_page_token (str): + A token which may be sent as + [page_token][google.cloud.backupdr.v1beta.ListRestoreVerificationPlansRequest.page_token] + in a subsequent ``ListRestoreVerificationPlans`` call to + retrieve the next page of results. If this field is omitted + or empty, then there are no more results to return. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + restore_verification_plans: MutableSequence["RestoreVerificationPlan"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=1, + message="RestoreVerificationPlan", + ) + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DeleteRestoreVerificationPlanRequest(proto.Message): + r"""The request message for deleting a ``RestoreVerificationPlan``. + + Attributes: + name (str): + Required. The resource name of the + ``RestoreVerificationPlan`` to delete. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}`` + 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). + force (bool): + Optional. If set to true, any + RestoreVerificationPlanAssociations linked to + this RestoreVerificationPlan will also be + deleted. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_verification_plan_association.py b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_verification_plan_association.py new file mode 100644 index 000000000000..3ff2edb0afa1 --- /dev/null +++ b/packages/google-cloud-backupdr/google/cloud/backupdr_v1beta/types/restore_verification_plan_association.py @@ -0,0 +1,431 @@ +# -*- 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 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( + package="google.cloud.backupdr.v1beta", + manifest={ + "RestoreVerificationPlanAssociation", + "TriggerSummary", + "CreateRestoreVerificationPlanAssociationRequest", + "GetRestoreVerificationPlanAssociationRequest", + "ListRestoreVerificationPlanAssociationsRequest", + "ListRestoreVerificationPlanAssociationsResponse", + "DeleteRestoreVerificationPlanAssociationRequest", + "TriggerRestoreVerificationRequest", + "TriggerRestoreVerificationResponse", + }, +) + + +class RestoreVerificationPlanAssociation(proto.Message): + r"""A ``RestoreVerificationPlanAssociation`` binds a specific workload + to a ``RestoreVerificationPlan``. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + restore_template (str): + Required. Immutable. The canonical name of + the RestoreTemplate to trigger. + + This field is a member of `oneof`_ ``association``. + name (str): + Output only. Identifier. The resource name of the + ``RestoreVerificationPlanAssociation``. + + Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + description (str): + Optional. The description of the + ``RestoreVerificationPlanAssociation`` resource. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the association + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the association + was updated. + state (google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation.State): + Output only. The ``State`` for the + ``RestoreVerificationPlanAssociation``. + trigger_summary (google.cloud.backupdr_v1beta.types.TriggerSummary): + Output only. Results of the most recent + automated restore initiation and the next + scheduled execution time. + resource_type (str): + Required. Immutable. The type of the Google Cloud resource + (e.g., ``compute.googleapis.com/Instance``, + ``sqladmin.googleapis.com/Instance``). + labels (MutableMapping[str, str]): + Optional. User-defined labels. + """ + + class State(proto.Enum): + r"""``State`` enumerates the possible states for a + ``RestoreVerificationPlanAssociation``. + + Values: + STATE_UNSPECIFIED (0): + State not set. + CREATING (1): + The resource is being created. + ACTIVE (2): + The resource has been created and is fully + usable. + DELETING (3): + The resource is being deleted. + INACTIVE (4): + The resource has been created but is not + usable. + UPDATING (5): + The resource is being updated. + ERROR (6): + The resource is in an error state due to a + configuration issue. + """ + + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + INACTIVE = 4 + UPDATING = 5 + ERROR = 6 + + restore_template: str = proto.Field( + proto.STRING, + number=8, + oneof="association", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + description: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=5, + enum=State, + ) + trigger_summary: "TriggerSummary" = proto.Field( + proto.MESSAGE, + number=6, + message="TriggerSummary", + ) + resource_type: str = proto.Field( + proto.STRING, + number=7, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=9, + ) + + +class TriggerSummary(proto.Message): + r"""``TriggerSummary`` contains the results of the most recent automated + restore initiation and the next scheduled execution time. + + Attributes: + last_trigger_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time of the most recent + trigger initiation. + next_trigger_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The scheduled time of the next + trigger initiation. + last_trigger_error (google.rpc.status_pb2.Status): + Output only. The error status of the most + recent failed trigger. + last_verification_execution (str): + Output only. The resource name of the most recent initiated + RestoreTemplateExecution. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}`` + """ + + last_trigger_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + next_trigger_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + last_trigger_error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=3, + message=status_pb2.Status, + ) + last_verification_execution: str = proto.Field( + proto.STRING, + number=4, + ) + + +class CreateRestoreVerificationPlanAssociationRequest(proto.Message): + r"""Request message for CreateRestoreVerificationPlanAssociation. + + Attributes: + parent (str): + Required. The parent resource where this association will be + created. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + restore_verification_plan_association_id (str): + Required. The ID to use for the association, which will + become the final component of the association's resource + name. + + This value should be 1-63 characters, and valid characters + are /[a-z0-9\_-]/. + restore_verification_plan_association (google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation): + Required. The + RestoreVerificationPlanAssociation resource 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 that the server has already received the + duplicate request and can avoid responding with + an error. 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, + ) + restore_verification_plan_association_id: str = proto.Field( + proto.STRING, + number=2, + ) + restore_verification_plan_association: "RestoreVerificationPlanAssociation" = ( + proto.Field( + proto.MESSAGE, + number=3, + message="RestoreVerificationPlanAssociation", + ) + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class GetRestoreVerificationPlanAssociationRequest(proto.Message): + r"""Request message for GetRestoreVerificationPlanAssociation. + + Attributes: + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to retrieve. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRestoreVerificationPlanAssociationsRequest(proto.Message): + r"""Request message for ListRestoreVerificationPlanAssociations. + + Attributes: + parent (str): + Required. The parent RestoreVerificationPlan name. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}`` + page_size (int): + Optional. The maximum number of associations + to return. The service may return fewer than + this value. If unspecified, at most 500 + associations will be returned. The maximum value + is 1000; values above 1000 will be coerced to + 1000. + page_token (str): + Optional. A page token, received from a previous + ``ListRestoreVerificationPlanAssociations`` call. Provide + this to retrieve the subsequent page. + + When paginating, all other parameters provided to + ``ListRestoreVerificationPlanAssociations`` must match the + call that provided the page token. + filter (str): + Optional. Filtering results. + order_by (str): + Optional. Hint for how to order the results. + """ + + 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 ListRestoreVerificationPlanAssociationsResponse(proto.Message): + r"""Response message for ListRestoreVerificationPlanAssociations. + + Attributes: + restore_verification_plan_associations (MutableSequence[google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation]): + The list of + RestoreVerificationPlanAssociations. + 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]): + Unordered list. Locations that could not be + reached. + """ + + @property + def raw_page(self): + return self + + restore_verification_plan_associations: MutableSequence[ + "RestoreVerificationPlanAssociation" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="RestoreVerificationPlanAssociation", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class DeleteRestoreVerificationPlanAssociationRequest(proto.Message): + r"""Request message for DeleteRestoreVerificationPlanAssociation. + + Attributes: + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to delete. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + 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 that the server has already received the + duplicate request and can avoid responding with + an error. 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 TriggerRestoreVerificationRequest(proto.Message): + r"""Request message for TriggerRestoreVerification. + + Attributes: + name (str): + Required. The resource name of the + RestoreVerificationPlanAssociation to trigger. Format: + ``projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}`` + 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 that the server has already received the + duplicate request and can avoid responding with + an error. 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 TriggerRestoreVerificationResponse(proto.Message): + r"""Response message for TriggerRestoreVerification. + + Attributes: + restore_template_execution (str): + Output only. The resource name of the initiated + RestoreTemplateExecution. Format: + ``projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}`` + """ + + restore_template_execution: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_async.py new file mode 100644 index 000000000000..f2cf6c902d77 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_async.py @@ -0,0 +1,70 @@ +# -*- 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 CreateAutoProtectionPolicy +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicy_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 backupdr_v1 + + +async def sample_create_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = ( + "key_value" + ) + auto_protection_policy.criteria.matching_conditions.label_condition.values = [ + "values_value1", + "values_value2", + ] + + request = backupdr_v1.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = await client.create_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicy_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_async.py new file mode 100644 index 000000000000..a0b551a131ec --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_async.py @@ -0,0 +1,62 @@ +# -*- 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 CreateAutoProtectionPolicyBinding +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicyBinding_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 backupdr_v1 + + +async def sample_create_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy_binding = backupdr_v1.AutoProtectionPolicyBinding() + auto_protection_policy_binding.scope = "scope_value" + + request = backupdr_v1.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + auto_protection_policy_binding=auto_protection_policy_binding, + ) + + # Make the request + operation = await client.create_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicyBinding_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_sync.py new file mode 100644 index 000000000000..0d94c37979d7 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_sync.py @@ -0,0 +1,62 @@ +# -*- 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 CreateAutoProtectionPolicyBinding +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicyBinding_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 backupdr_v1 + + +def sample_create_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy_binding = backupdr_v1.AutoProtectionPolicyBinding() + auto_protection_policy_binding.scope = "scope_value" + + request = backupdr_v1.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + auto_protection_policy_binding=auto_protection_policy_binding, + ) + + # Make the request + operation = client.create_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicyBinding_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_sync.py new file mode 100644 index 000000000000..0b461bccfbab --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_auto_protection_policy_sync.py @@ -0,0 +1,70 @@ +# -*- 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 CreateAutoProtectionPolicy +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicy_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 backupdr_v1 + + +def sample_create_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = ( + "key_value" + ) + auto_protection_policy.criteria.matching_conditions.label_condition.values = [ + "values_value1", + "values_value2", + ] + + request = backupdr_v1.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = client.create_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicy_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_template_async.py new file mode 100644 index 000000000000..6501de7dcf19 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_template_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 CreateRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateRestoreTemplate_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 backupdr_v1 + + +async def sample_create_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_template = backupdr_v1.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + restore_template=restore_template, + ) + + # Make the request + operation = await client.create_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_template_sync.py new file mode 100644 index 000000000000..5b4f9a3ff22b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_template_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 CreateRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateRestoreTemplate_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 backupdr_v1 + + +def sample_create_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + restore_template = backupdr_v1.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + restore_template=restore_template, + ) + + # Make the request + operation = client.create_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_async.py new file mode 100644 index 000000000000..3870e8b0fffd --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_async.py @@ -0,0 +1,67 @@ +# -*- 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 CreateRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlanAssociation_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 backupdr_v1 + + +async def sample_create_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_verification_plan_association = ( + backupdr_v1.RestoreVerificationPlanAssociation() + ) + restore_verification_plan_association.restore_template = "restore_template_value" + restore_verification_plan_association.resource_type = "resource_type_value" + + request = backupdr_v1.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + restore_verification_plan_association=restore_verification_plan_association, + ) + + # Make the request + operation = await client.create_restore_verification_plan_association( + request=request + ) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_sync.py new file mode 100644 index 000000000000..a55a78258b8e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_sync.py @@ -0,0 +1,65 @@ +# -*- 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 CreateRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlanAssociation_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 backupdr_v1 + + +def sample_create_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + restore_verification_plan_association = ( + backupdr_v1.RestoreVerificationPlanAssociation() + ) + restore_verification_plan_association.restore_template = "restore_template_value" + restore_verification_plan_association.resource_type = "resource_type_value" + + request = backupdr_v1.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + restore_verification_plan_association=restore_verification_plan_association, + ) + + # Make the request + operation = client.create_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_async.py new file mode 100644 index 000000000000..6dd3f6830f5c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_async.py @@ -0,0 +1,62 @@ +# -*- 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 CreateRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlan_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 backupdr_v1 + + +async def sample_create_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_verification_plan = backupdr_v1.RestoreVerificationPlan() + restore_verification_plan.schedule = "schedule_value" + + request = backupdr_v1.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + restore_verification_plan=restore_verification_plan, + ) + + # Make the request + operation = await client.create_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_sync.py new file mode 100644 index 000000000000..3c478e7b9eb1 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_create_restore_verification_plan_sync.py @@ -0,0 +1,62 @@ +# -*- 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 CreateRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlan_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 backupdr_v1 + + +def sample_create_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + restore_verification_plan = backupdr_v1.RestoreVerificationPlan() + restore_verification_plan.schedule = "schedule_value" + + request = backupdr_v1.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + restore_verification_plan=restore_verification_plan, + ) + + # Make the request + operation = client.create_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_auto_protection_policy_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_auto_protection_policy_async.py new file mode 100644 index 000000000000..154974f2852d --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_auto_protection_policy_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 DeleteAutoProtectionPolicy +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_DeleteAutoProtectionPolicy_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 backupdr_v1 + + +async def sample_delete_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_DeleteAutoProtectionPolicy_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_auto_protection_policy_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_auto_protection_policy_sync.py new file mode 100644 index 000000000000..ee179ccd46f3 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_auto_protection_policy_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 DeleteAutoProtectionPolicy +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_DeleteAutoProtectionPolicy_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 backupdr_v1 + + +def sample_delete_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_DeleteAutoProtectionPolicy_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_template_async.py new file mode 100644 index 000000000000..193ef9aef151 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_template_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 DeleteRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_DeleteRestoreTemplate_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 backupdr_v1 + + +async def sample_delete_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_DeleteRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_template_sync.py new file mode 100644 index 000000000000..fa99d4629e64 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_template_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 DeleteRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_DeleteRestoreTemplate_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 backupdr_v1 + + +def sample_delete_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_DeleteRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_async.py new file mode 100644 index 000000000000..4a4bc2175719 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_async.py @@ -0,0 +1,59 @@ +# -*- 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 DeleteRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_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 backupdr_v1 + + +async def sample_delete_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_verification_plan_association( + request=request + ) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_sync.py new file mode 100644 index 000000000000..1a3cc1678545 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_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 DeleteRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_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 backupdr_v1 + + +def sample_delete_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_async.py new file mode 100644 index 000000000000..b3c80c58b4a3 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_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 DeleteRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlan_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 backupdr_v1 + + +async def sample_delete_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_sync.py new file mode 100644 index 000000000000..9742a1e20cfc --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_delete_restore_verification_plan_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 DeleteRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlan_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 backupdr_v1 + + +def sample_delete_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.DeleteRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_async.py new file mode 100644 index 000000000000..ea4a726107ad --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_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 GetAutoProtectionPolicy +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetAutoProtectionPolicy_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 backupdr_v1 + + +async def sample_get_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auto_protection_policy(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetAutoProtectionPolicy_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_async.py new file mode 100644 index 000000000000..ece0ea2639da --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_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 GetAutoProtectionPolicyBinding +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetAutoProtectionPolicyBinding_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 backupdr_v1 + + +async def sample_get_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auto_protection_policy_binding(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetAutoProtectionPolicyBinding_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_sync.py new file mode 100644 index 000000000000..88bbd82e0289 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_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 GetAutoProtectionPolicyBinding +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetAutoProtectionPolicyBinding_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 backupdr_v1 + + +def sample_get_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + response = client.get_auto_protection_policy_binding(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetAutoProtectionPolicyBinding_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_sync.py new file mode 100644 index 000000000000..40b77c719a4d --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_auto_protection_policy_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 GetAutoProtectionPolicy +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetAutoProtectionPolicy_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 backupdr_v1 + + +def sample_get_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Make the request + response = client.get_auto_protection_policy(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetAutoProtectionPolicy_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_async.py new file mode 100644 index 000000000000..6b17b7370bda --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_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 GetRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetRestoreTemplate_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 backupdr_v1 + + +async def sample_get_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_template(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_execution_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_execution_async.py new file mode 100644 index 000000000000..7a9a37a67318 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_execution_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 GetRestoreTemplateExecution +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetRestoreTemplateExecution_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 backupdr_v1 + + +async def sample_get_restore_template_execution(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_template_execution(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetRestoreTemplateExecution_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_execution_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_execution_sync.py new file mode 100644 index 000000000000..0342a0aa7679 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_execution_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 GetRestoreTemplateExecution +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetRestoreTemplateExecution_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 backupdr_v1 + + +def sample_get_restore_template_execution(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_template_execution(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetRestoreTemplateExecution_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_sync.py new file mode 100644 index 000000000000..855f2fd1bad6 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_template_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 GetRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetRestoreTemplate_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 backupdr_v1 + + +def sample_get_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_template(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_async.py new file mode 100644 index 000000000000..26e4523fc43a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_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 GetRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetRestoreVerificationPlanAssociation_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 backupdr_v1 + + +async def sample_get_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_verification_plan_association(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetRestoreVerificationPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_sync.py new file mode 100644 index 000000000000..e58dba48e533 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_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 GetRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetRestoreVerificationPlanAssociation_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 backupdr_v1 + + +def sample_get_restore_verification_plan_association(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_verification_plan_association(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetRestoreVerificationPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_async.py new file mode 100644 index 000000000000..60127ba37dc6 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_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 GetRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetRestoreVerificationPlan_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 backupdr_v1 + + +async def sample_get_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_verification_plan(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetRestoreVerificationPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_sync.py new file mode 100644 index 000000000000..620adb869681 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_get_restore_verification_plan_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 GetRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_GetRestoreVerificationPlan_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 backupdr_v1 + + +def sample_get_restore_verification_plan(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.GetRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_verification_plan(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_GetRestoreVerificationPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py new file mode 100644 index 000000000000..6c47cd13f611 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py @@ -0,0 +1,59 @@ +# -*- 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 InitiateDeleteAutoProtectionPolicyBinding +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_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 backupdr_v1 + + +async def sample_initiate_delete_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = await client.initiate_delete_auto_protection_policy_binding( + request=request + ) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py new file mode 100644 index 000000000000..53f277893cb8 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_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 InitiateDeleteAutoProtectionPolicyBinding +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_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 backupdr_v1 + + +def sample_initiate_delete_auto_protection_policy_binding(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Make the request + operation = client.initiate_delete_auto_protection_policy_binding(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_async.py new file mode 100644 index 000000000000..63b8c49d6366 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_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 ListAppliedAutoProtectionPolicies +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListAppliedAutoProtectionPolicies_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 backupdr_v1 + + +async def sample_list_applied_auto_protection_policies(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applied_auto_protection_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListAppliedAutoProtectionPolicies_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_sync.py new file mode 100644 index 000000000000..4f1f0f4519f1 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_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 ListAppliedAutoProtectionPolicies +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListAppliedAutoProtectionPolicies_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 backupdr_v1 + + +def sample_list_applied_auto_protection_policies(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_applied_auto_protection_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListAppliedAutoProtectionPolicies_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policies_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policies_async.py new file mode 100644 index 000000000000..4fadd7bef28c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policies_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 ListAutoProtectionPolicies +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListAutoProtectionPolicies_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 backupdr_v1 + + +async def sample_list_auto_protection_policies(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policies(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListAutoProtectionPolicies_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policies_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policies_sync.py new file mode 100644 index 000000000000..4cc7dacc4d00 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policies_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 ListAutoProtectionPolicies +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListAutoProtectionPolicies_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 backupdr_v1 + + +def sample_list_auto_protection_policies(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAutoProtectionPoliciesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListAutoProtectionPolicies_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_async.py new file mode 100644 index 000000000000..2062cd5bd24a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_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 ListAutoProtectionPolicyBindings +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListAutoProtectionPolicyBindings_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 backupdr_v1 + + +async def sample_list_auto_protection_policy_bindings(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policy_bindings(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListAutoProtectionPolicyBindings_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_sync.py new file mode 100644 index 000000000000..2f2d8e88d9f4 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_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 ListAutoProtectionPolicyBindings +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListAutoProtectionPolicyBindings_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 backupdr_v1 + + +def sample_list_auto_protection_policy_bindings(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auto_protection_policy_bindings(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListAutoProtectionPolicyBindings_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_binding_matching_resources_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_binding_matching_resources_async.py new file mode 100644 index 000000000000..96508a856f7e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_binding_matching_resources_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 ListBindingMatchingResources +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListBindingMatchingResources_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 backupdr_v1 + + +async def sample_list_binding_matching_resources(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListBindingMatchingResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_binding_matching_resources(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListBindingMatchingResources_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_binding_matching_resources_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_binding_matching_resources_sync.py new file mode 100644 index 000000000000..ce2eefcf1ed7 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_binding_matching_resources_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 ListBindingMatchingResources +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListBindingMatchingResources_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 backupdr_v1 + + +def sample_list_binding_matching_resources(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListBindingMatchingResourcesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_binding_matching_resources(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListBindingMatchingResources_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_template_executions_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_template_executions_async.py new file mode 100644 index 000000000000..ea234562fb52 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_template_executions_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 ListRestoreTemplateExecutions +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListRestoreTemplateExecutions_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 backupdr_v1 + + +async def sample_list_restore_template_executions(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_template_executions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListRestoreTemplateExecutions_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_template_executions_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_template_executions_sync.py new file mode 100644 index 000000000000..a504baf3724b --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_template_executions_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 ListRestoreTemplateExecutions +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListRestoreTemplateExecutions_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 backupdr_v1 + + +def sample_list_restore_template_executions(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_template_executions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListRestoreTemplateExecutions_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_templates_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_templates_async.py new file mode 100644 index 000000000000..c74bd444e6a2 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_templates_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 ListRestoreTemplates +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListRestoreTemplates_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 backupdr_v1 + + +async def sample_list_restore_templates(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreTemplatesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_templates(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListRestoreTemplates_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_templates_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_templates_sync.py new file mode 100644 index 000000000000..64ced815aa92 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_templates_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 ListRestoreTemplates +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListRestoreTemplates_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 backupdr_v1 + + +def sample_list_restore_templates(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreTemplatesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_templates(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListRestoreTemplates_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_async.py new file mode 100644 index 000000000000..72fa4147bc43 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_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 ListRestoreVerificationPlanAssociations +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListRestoreVerificationPlanAssociations_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 backupdr_v1 + + +async def sample_list_restore_verification_plan_associations(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plan_associations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListRestoreVerificationPlanAssociations_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_sync.py new file mode 100644 index 000000000000..e924375c6d3d --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_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 ListRestoreVerificationPlanAssociations +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListRestoreVerificationPlanAssociations_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 backupdr_v1 + + +def sample_list_restore_verification_plan_associations(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plan_associations(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListRestoreVerificationPlanAssociations_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plans_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plans_async.py new file mode 100644 index 000000000000..d5431339e1db --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plans_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 ListRestoreVerificationPlans +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListRestoreVerificationPlans_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 backupdr_v1 + + +async def sample_list_restore_verification_plans(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreVerificationPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plans(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListRestoreVerificationPlans_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plans_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plans_sync.py new file mode 100644 index 000000000000..ef2f4450b01e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_list_restore_verification_plans_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 ListRestoreVerificationPlans +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_ListRestoreVerificationPlans_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 backupdr_v1 + + +def sample_list_restore_verification_plans(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.ListRestoreVerificationPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plans(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1_generated_BackupDR_ListRestoreVerificationPlans_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_run_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_run_restore_template_async.py new file mode 100644 index 000000000000..4d7c123094c9 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_run_restore_template_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 RunRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_RunRestoreTemplate_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 backupdr_v1 + + +async def sample_run_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.RunRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = await client.run_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_RunRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_run_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_run_restore_template_sync.py new file mode 100644 index 000000000000..169d54b10d73 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_run_restore_template_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 RunRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_RunRestoreTemplate_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 backupdr_v1 + + +def sample_run_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.RunRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = client.run_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_RunRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_cleanup_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_cleanup_async.py new file mode 100644 index 000000000000..cbb4a3e2b3b7 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_cleanup_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 TriggerRestoreCleanup +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_TriggerRestoreCleanup_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 backupdr_v1 + + +async def sample_trigger_restore_cleanup(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.TriggerRestoreCleanupRequest( + name="name_value", + ) + + # Make the request + operation = await client.trigger_restore_cleanup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_TriggerRestoreCleanup_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_cleanup_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_cleanup_sync.py new file mode 100644 index 000000000000..2f50ce7c26a6 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_cleanup_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 TriggerRestoreCleanup +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_TriggerRestoreCleanup_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 backupdr_v1 + + +def sample_trigger_restore_cleanup(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.TriggerRestoreCleanupRequest( + name="name_value", + ) + + # Make the request + operation = client.trigger_restore_cleanup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_TriggerRestoreCleanup_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_verification_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_verification_async.py new file mode 100644 index 000000000000..31b62eb20bef --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_verification_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 TriggerRestoreVerification +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_TriggerRestoreVerification_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 backupdr_v1 + + +async def sample_trigger_restore_verification(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1.TriggerRestoreVerificationRequest( + name="name_value", + ) + + # Make the request + operation = await client.trigger_restore_verification(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_TriggerRestoreVerification_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_verification_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_verification_sync.py new file mode 100644 index 000000000000..ea9ce44253b2 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_trigger_restore_verification_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 TriggerRestoreVerification +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_TriggerRestoreVerification_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 backupdr_v1 + + +def sample_trigger_restore_verification(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1.TriggerRestoreVerificationRequest( + name="name_value", + ) + + # Make the request + operation = client.trigger_restore_verification(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_TriggerRestoreVerification_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_auto_protection_policy_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_auto_protection_policy_async.py new file mode 100644 index 000000000000..c5a49f3c968c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_auto_protection_policy_async.py @@ -0,0 +1,68 @@ +# -*- 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 UpdateAutoProtectionPolicy +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_UpdateAutoProtectionPolicy_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 backupdr_v1 + + +async def sample_update_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = ( + "key_value" + ) + auto_protection_policy.criteria.matching_conditions.label_condition.values = [ + "values_value1", + "values_value2", + ] + + request = backupdr_v1.UpdateAutoProtectionPolicyRequest( + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = await client.update_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_UpdateAutoProtectionPolicy_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_auto_protection_policy_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_auto_protection_policy_sync.py new file mode 100644 index 000000000000..d396ebd6cb90 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_auto_protection_policy_sync.py @@ -0,0 +1,68 @@ +# -*- 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 UpdateAutoProtectionPolicy +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_UpdateAutoProtectionPolicy_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 backupdr_v1 + + +def sample_update_auto_protection_policy(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + auto_protection_policy = backupdr_v1.AutoProtectionPolicy() + auto_protection_policy.backup_plan_details.resource_type = "resource_type_value" + auto_protection_policy.backup_plan_details.backup_plan = "backup_plan_value" + auto_protection_policy.criteria.matching_conditions.label_condition.key = ( + "key_value" + ) + auto_protection_policy.criteria.matching_conditions.label_condition.values = [ + "values_value1", + "values_value2", + ] + + request = backupdr_v1.UpdateAutoProtectionPolicyRequest( + auto_protection_policy=auto_protection_policy, + ) + + # Make the request + operation = client.update_auto_protection_policy(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_UpdateAutoProtectionPolicy_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_restore_template_async.py new file mode 100644 index 000000000000..49131ec2c636 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_restore_template_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_UpdateRestoreTemplate_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 backupdr_v1 + + +async def sample_update_restore_template(): + # Create a client + client = backupdr_v1.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_template = backupdr_v1.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1.UpdateRestoreTemplateRequest( + restore_template=restore_template, + ) + + # Make the request + operation = await client.update_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_UpdateRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_restore_template_sync.py new file mode 100644 index 000000000000..b64a14a60aab --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1_generated_backup_dr_update_restore_template_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1_generated_BackupDR_UpdateRestoreTemplate_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 backupdr_v1 + + +def sample_update_restore_template(): + # Create a client + client = backupdr_v1.BackupDRClient() + + # Initialize request argument(s) + restore_template = backupdr_v1.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1.UpdateRestoreTemplateRequest( + restore_template=restore_template, + ) + + # Make the request + operation = client.update_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1_generated_BackupDR_UpdateRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_template_async.py new file mode 100644 index 000000000000..748fb39faf3a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_template_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 CreateRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateRestoreTemplate_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 backupdr_v1beta + + +async def sample_create_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_template = backupdr_v1beta.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1beta.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + restore_template=restore_template, + ) + + # Make the request + operation = await client.create_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_template_sync.py new file mode 100644 index 000000000000..714c1c75046f --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_template_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 CreateRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateRestoreTemplate_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 backupdr_v1beta + + +def sample_create_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + restore_template = backupdr_v1beta.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1beta.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + restore_template=restore_template, + ) + + # Make the request + operation = client.create_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_async.py new file mode 100644 index 000000000000..1fc0fa68ce5c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_async.py @@ -0,0 +1,67 @@ +# -*- 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 CreateRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlanAssociation_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 backupdr_v1beta + + +async def sample_create_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_verification_plan_association = ( + backupdr_v1beta.RestoreVerificationPlanAssociation() + ) + restore_verification_plan_association.restore_template = "restore_template_value" + restore_verification_plan_association.resource_type = "resource_type_value" + + request = backupdr_v1beta.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + restore_verification_plan_association=restore_verification_plan_association, + ) + + # Make the request + operation = await client.create_restore_verification_plan_association( + request=request + ) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_sync.py new file mode 100644 index 000000000000..7dffc9c0cf4c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_sync.py @@ -0,0 +1,65 @@ +# -*- 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 CreateRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlanAssociation_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 backupdr_v1beta + + +def sample_create_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + restore_verification_plan_association = ( + backupdr_v1beta.RestoreVerificationPlanAssociation() + ) + restore_verification_plan_association.restore_template = "restore_template_value" + restore_verification_plan_association.resource_type = "resource_type_value" + + request = backupdr_v1beta.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + restore_verification_plan_association=restore_verification_plan_association, + ) + + # Make the request + operation = client.create_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_async.py new file mode 100644 index 000000000000..dd388b3c5f1c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_async.py @@ -0,0 +1,62 @@ +# -*- 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 CreateRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlan_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 backupdr_v1beta + + +async def sample_create_restore_verification_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_verification_plan = backupdr_v1beta.RestoreVerificationPlan() + restore_verification_plan.schedule = "schedule_value" + + request = backupdr_v1beta.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + restore_verification_plan=restore_verification_plan, + ) + + # Make the request + operation = await client.create_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_sync.py new file mode 100644 index 000000000000..b3a4a1bf2865 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_sync.py @@ -0,0 +1,62 @@ +# -*- 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 CreateRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlan_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 backupdr_v1beta + + +def sample_create_restore_verification_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + restore_verification_plan = backupdr_v1beta.RestoreVerificationPlan() + restore_verification_plan.schedule = "schedule_value" + + request = backupdr_v1beta.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + restore_verification_plan=restore_verification_plan, + ) + + # Make the request + operation = client.create_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_template_async.py new file mode 100644 index 000000000000..61743fca8a4a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_template_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 DeleteRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteRestoreTemplate_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 backupdr_v1beta + + +async def sample_delete_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_template_sync.py new file mode 100644 index 000000000000..d70f6e89b75a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_template_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 DeleteRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteRestoreTemplate_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 backupdr_v1beta + + +def sample_delete_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_async.py new file mode 100644 index 000000000000..c9b3714fe142 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_async.py @@ -0,0 +1,59 @@ +# -*- 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 DeleteRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_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 backupdr_v1beta + + +async def sample_delete_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_verification_plan_association( + request=request + ) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_sync.py new file mode 100644 index 000000000000..6be203063d91 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_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 DeleteRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_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 backupdr_v1beta + + +def sample_delete_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_verification_plan_association(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_async.py new file mode 100644 index 000000000000..0564358692fe --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_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 DeleteRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlan_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 backupdr_v1beta + + +async def sample_delete_restore_verification_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_sync.py new file mode 100644 index 000000000000..a94688c363c0 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_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 DeleteRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlan_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 backupdr_v1beta + + +def sample_delete_restore_verification_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.DeleteRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_restore_verification_plan(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_async.py new file mode 100644 index 000000000000..298f7b3ed3fb --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_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 GetRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetRestoreTemplate_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 backupdr_v1beta + + +async def sample_get_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_template(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_execution_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_execution_async.py new file mode 100644 index 000000000000..ce64a11e2c4d --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_execution_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 GetRestoreTemplateExecution +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetRestoreTemplateExecution_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 backupdr_v1beta + + +async def sample_get_restore_template_execution(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_template_execution(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetRestoreTemplateExecution_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_execution_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_execution_sync.py new file mode 100644 index 000000000000..4351d5b1823e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_execution_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 GetRestoreTemplateExecution +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetRestoreTemplateExecution_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 backupdr_v1beta + + +def sample_get_restore_template_execution(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_template_execution(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetRestoreTemplateExecution_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_sync.py new file mode 100644 index 000000000000..0fabcd30cc41 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_template_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 GetRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetRestoreTemplate_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 backupdr_v1beta + + +def sample_get_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_template(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_async.py new file mode 100644 index 000000000000..b2fcc29b63b5 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_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 GetRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlanAssociation_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 backupdr_v1beta + + +async def sample_get_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_verification_plan_association(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlanAssociation_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_sync.py new file mode 100644 index 000000000000..76e2be65c0f4 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_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 GetRestoreVerificationPlanAssociation +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlanAssociation_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 backupdr_v1beta + + +def sample_get_restore_verification_plan_association(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_verification_plan_association(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlanAssociation_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_async.py new file mode 100644 index 000000000000..1c7eac6acf7e --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_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 GetRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlan_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 backupdr_v1beta + + +async def sample_get_restore_verification_plan(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + response = await client.get_restore_verification_plan(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlan_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_sync.py new file mode 100644 index 000000000000..dbd197b21694 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_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 GetRestoreVerificationPlan +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlan_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 backupdr_v1beta + + +def sample_get_restore_verification_plan(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.GetRestoreVerificationPlanRequest( + name="name_value", + ) + + # Make the request + response = client.get_restore_verification_plan(request=request) + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlan_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_template_executions_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_template_executions_async.py new file mode 100644 index 000000000000..6e6a46d7f84c --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_template_executions_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 ListRestoreTemplateExecutions +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListRestoreTemplateExecutions_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 backupdr_v1beta + + +async def sample_list_restore_template_executions(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_template_executions(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListRestoreTemplateExecutions_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_template_executions_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_template_executions_sync.py new file mode 100644 index 000000000000..01a8768578f1 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_template_executions_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 ListRestoreTemplateExecutions +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListRestoreTemplateExecutions_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 backupdr_v1beta + + +def sample_list_restore_template_executions(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_template_executions(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListRestoreTemplateExecutions_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_templates_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_templates_async.py new file mode 100644 index 000000000000..57176a276b22 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_templates_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 ListRestoreTemplates +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListRestoreTemplates_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 backupdr_v1beta + + +async def sample_list_restore_templates(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreTemplatesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_templates(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListRestoreTemplates_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_templates_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_templates_sync.py new file mode 100644 index 000000000000..feeeedfa2636 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_templates_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 ListRestoreTemplates +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListRestoreTemplates_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 backupdr_v1beta + + +def sample_list_restore_templates(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreTemplatesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_templates(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListRestoreTemplates_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_async.py new file mode 100644 index 000000000000..1281684f4ea4 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_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 ListRestoreVerificationPlanAssociations +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlanAssociations_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 backupdr_v1beta + + +async def sample_list_restore_verification_plan_associations(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plan_associations(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlanAssociations_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_sync.py new file mode 100644 index 000000000000..6a56007b6956 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_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 ListRestoreVerificationPlanAssociations +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlanAssociations_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 backupdr_v1beta + + +def sample_list_restore_verification_plan_associations(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plan_associations(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlanAssociations_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_async.py new file mode 100644 index 000000000000..50b2de0afb28 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_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 ListRestoreVerificationPlans +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlans_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 backupdr_v1beta + + +async def sample_list_restore_verification_plans(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreVerificationPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plans(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlans_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_sync.py new file mode 100644 index 000000000000..a5975bfb0223 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_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 ListRestoreVerificationPlans +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlans_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 backupdr_v1beta + + +def sample_list_restore_verification_plans(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.ListRestoreVerificationPlansRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_restore_verification_plans(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlans_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_run_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_run_restore_template_async.py new file mode 100644 index 000000000000..7222ac3706e6 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_run_restore_template_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 RunRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_RunRestoreTemplate_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 backupdr_v1beta + + +async def sample_run_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.RunRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = await client.run_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_RunRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_run_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_run_restore_template_sync.py new file mode 100644 index 000000000000..738b3952d639 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_run_restore_template_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 RunRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_RunRestoreTemplate_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 backupdr_v1beta + + +def sample_run_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.RunRestoreTemplateRequest( + name="name_value", + ) + + # Make the request + operation = client.run_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_RunRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_async.py new file mode 100644 index 000000000000..b19cc64f950f --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_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 TriggerRestoreCleanup +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_TriggerRestoreCleanup_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 backupdr_v1beta + + +async def sample_trigger_restore_cleanup(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerRestoreCleanupRequest( + name="name_value", + ) + + # Make the request + operation = await client.trigger_restore_cleanup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_TriggerRestoreCleanup_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_sync.py new file mode 100644 index 000000000000..fcd2e380c8ba --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_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 TriggerRestoreCleanup +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_TriggerRestoreCleanup_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 backupdr_v1beta + + +def sample_trigger_restore_cleanup(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerRestoreCleanupRequest( + name="name_value", + ) + + # Make the request + operation = client.trigger_restore_cleanup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_TriggerRestoreCleanup_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_verification_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_verification_async.py new file mode 100644 index 000000000000..1755bfd8e12a --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_verification_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 TriggerRestoreVerification +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_TriggerRestoreVerification_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 backupdr_v1beta + + +async def sample_trigger_restore_verification(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerRestoreVerificationRequest( + name="name_value", + ) + + # Make the request + operation = await client.trigger_restore_verification(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_TriggerRestoreVerification_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_verification_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_verification_sync.py new file mode 100644 index 000000000000..ecf2c45671bd --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_trigger_restore_verification_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 TriggerRestoreVerification +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_TriggerRestoreVerification_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 backupdr_v1beta + + +def sample_trigger_restore_verification(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + request = backupdr_v1beta.TriggerRestoreVerificationRequest( + name="name_value", + ) + + # Make the request + operation = client.trigger_restore_verification(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_TriggerRestoreVerification_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_restore_template_async.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_restore_template_async.py new file mode 100644 index 000000000000..8027dd214ed8 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_restore_template_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateRestoreTemplate_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 backupdr_v1beta + + +async def sample_update_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRAsyncClient() + + # Initialize request argument(s) + restore_template = backupdr_v1beta.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1beta.UpdateRestoreTemplateRequest( + restore_template=restore_template, + ) + + # Make the request + operation = await client.update_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateRestoreTemplate_async] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_restore_template_sync.py b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_restore_template_sync.py new file mode 100644 index 000000000000..842108a84380 --- /dev/null +++ b/packages/google-cloud-backupdr/samples/generated_samples/backupdr_v1beta_generated_backup_dr_update_restore_template_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for UpdateRestoreTemplate +# 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-backupdr + + +# [START backupdr_v1beta_generated_BackupDR_UpdateRestoreTemplate_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 backupdr_v1beta + + +def sample_update_restore_template(): + # Create a client + client = backupdr_v1beta.BackupDRClient() + + # Initialize request argument(s) + restore_template = backupdr_v1beta.RestoreTemplate() + restore_template.resource_type = "resource_type_value" + restore_template.backup_selection_config.data_source = "data_source_value" + + request = backupdr_v1beta.UpdateRestoreTemplateRequest( + restore_template=restore_template, + ) + + # Make the request + operation = client.update_restore_template(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END backupdr_v1beta_generated_BackupDR_UpdateRestoreTemplate_sync] diff --git a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json index cad707f9343c..1fab81102fc1 100644 --- a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json +++ b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1.json @@ -19,30 +19,30 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_backup_plan_association", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_auto_protection_policy_binding", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateAutoProtectionPolicyBinding", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "CreateBackupPlanAssociation" + "shortName": "CreateAutoProtectionPolicyBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.CreateBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1.types.CreateAutoProtectionPolicyBindingRequest" }, { "name": "parent", "type": "str" }, { - "name": "backup_plan_association", - "type": "google.cloud.backupdr_v1.types.BackupPlanAssociation" + "name": "auto_protection_policy_binding", + "type": "google.cloud.backupdr_v1.types.AutoProtectionPolicyBinding" }, { - "name": "backup_plan_association_id", + "name": "auto_protection_policy_binding_id", "type": "str" }, { @@ -59,21 +59,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_backup_plan_association" + "shortName": "create_auto_protection_policy_binding" }, - "description": "Sample for CreateBackupPlanAssociation", - "file": "backupdr_v1_generated_backup_dr_create_backup_plan_association_async.py", + "description": "Sample for CreateAutoProtectionPolicyBinding", + "file": "backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlanAssociation_async", + "regionTag": "backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicyBinding_async", "segments": [ { - "end": 62, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 60, "start": 27, "type": "SHORT" }, @@ -83,22 +83,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_create_backup_plan_association_async.py" + "title": "backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_async.py" }, { "canonical": true, @@ -107,30 +107,30 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_backup_plan_association", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_auto_protection_policy_binding", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateAutoProtectionPolicyBinding", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "CreateBackupPlanAssociation" + "shortName": "CreateAutoProtectionPolicyBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.CreateBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1.types.CreateAutoProtectionPolicyBindingRequest" }, { "name": "parent", "type": "str" }, { - "name": "backup_plan_association", - "type": "google.cloud.backupdr_v1.types.BackupPlanAssociation" + "name": "auto_protection_policy_binding", + "type": "google.cloud.backupdr_v1.types.AutoProtectionPolicyBinding" }, { - "name": "backup_plan_association_id", + "name": "auto_protection_policy_binding_id", "type": "str" }, { @@ -147,21 +147,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_backup_plan_association" + "shortName": "create_auto_protection_policy_binding" }, - "description": "Sample for CreateBackupPlanAssociation", - "file": "backupdr_v1_generated_backup_dr_create_backup_plan_association_sync.py", + "description": "Sample for CreateAutoProtectionPolicyBinding", + "file": "backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlanAssociation_sync", + "regionTag": "backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicyBinding_sync", "segments": [ { - "end": 62, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 60, "start": 27, "type": "SHORT" }, @@ -171,22 +171,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_create_backup_plan_association_sync.py" + "title": "backupdr_v1_generated_backup_dr_create_auto_protection_policy_binding_sync.py" }, { "canonical": true, @@ -196,30 +196,30 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_backup_plan", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_auto_protection_policy", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupPlan", + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateAutoProtectionPolicy", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "CreateBackupPlan" + "shortName": "CreateAutoProtectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.CreateBackupPlanRequest" + "type": "google.cloud.backupdr_v1.types.CreateAutoProtectionPolicyRequest" }, { "name": "parent", "type": "str" }, { - "name": "backup_plan", - "type": "google.cloud.backupdr_v1.types.BackupPlan" + "name": "auto_protection_policy", + "type": "google.cloud.backupdr_v1.types.AutoProtectionPolicy" }, { - "name": "backup_plan_id", + "name": "auto_protection_policy_id", "type": "str" }, { @@ -236,21 +236,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_backup_plan" + "shortName": "create_auto_protection_policy" }, - "description": "Sample for CreateBackupPlan", - "file": "backupdr_v1_generated_backup_dr_create_backup_plan_async.py", + "description": "Sample for CreateAutoProtectionPolicy", + "file": "backupdr_v1_generated_backup_dr_create_auto_protection_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlan_async", + "regionTag": "backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicy_async", "segments": [ { - "end": 67, + "end": 63, "start": 27, "type": "FULL" }, { - "end": 67, + "end": 63, "start": 27, "type": "SHORT" }, @@ -260,22 +260,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 57, + "end": 53, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 64, - "start": 58, + "end": 60, + "start": 54, "type": "REQUEST_EXECUTION" }, { - "end": 68, - "start": 65, + "end": 64, + "start": 61, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_create_backup_plan_async.py" + "title": "backupdr_v1_generated_backup_dr_create_auto_protection_policy_async.py" }, { "canonical": true, @@ -284,30 +284,30 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_backup_plan", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_auto_protection_policy", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupPlan", + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateAutoProtectionPolicy", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "CreateBackupPlan" + "shortName": "CreateAutoProtectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.CreateBackupPlanRequest" + "type": "google.cloud.backupdr_v1.types.CreateAutoProtectionPolicyRequest" }, { "name": "parent", "type": "str" }, { - "name": "backup_plan", - "type": "google.cloud.backupdr_v1.types.BackupPlan" + "name": "auto_protection_policy", + "type": "google.cloud.backupdr_v1.types.AutoProtectionPolicy" }, { - "name": "backup_plan_id", + "name": "auto_protection_policy_id", "type": "str" }, { @@ -324,21 +324,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_backup_plan" + "shortName": "create_auto_protection_policy" }, - "description": "Sample for CreateBackupPlan", - "file": "backupdr_v1_generated_backup_dr_create_backup_plan_sync.py", + "description": "Sample for CreateAutoProtectionPolicy", + "file": "backupdr_v1_generated_backup_dr_create_auto_protection_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlan_sync", + "regionTag": "backupdr_v1_generated_BackupDR_CreateAutoProtectionPolicy_sync", "segments": [ { - "end": 67, + "end": 63, "start": 27, "type": "FULL" }, { - "end": 67, + "end": 63, "start": 27, "type": "SHORT" }, @@ -348,22 +348,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 57, + "end": 53, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 64, - "start": 58, + "end": 60, + "start": 54, "type": "REQUEST_EXECUTION" }, { - "end": 68, - "start": 65, + "end": 64, + "start": 61, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_create_backup_plan_sync.py" + "title": "backupdr_v1_generated_backup_dr_create_auto_protection_policy_sync.py" }, { "canonical": true, @@ -373,30 +373,30 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_backup_vault", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_backup_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupVault", + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "CreateBackupVault" + "shortName": "CreateBackupPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.CreateBackupVaultRequest" + "type": "google.cloud.backupdr_v1.types.CreateBackupPlanAssociationRequest" }, { "name": "parent", "type": "str" }, { - "name": "backup_vault", - "type": "google.cloud.backupdr_v1.types.BackupVault" + "name": "backup_plan_association", + "type": "google.cloud.backupdr_v1.types.BackupPlanAssociation" }, { - "name": "backup_vault_id", + "name": "backup_plan_association_id", "type": "str" }, { @@ -413,21 +413,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_backup_vault" + "shortName": "create_backup_plan_association" }, - "description": "Sample for CreateBackupVault", - "file": "backupdr_v1_generated_backup_dr_create_backup_vault_async.py", + "description": "Sample for CreateBackupPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_create_backup_plan_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupVault_async", + "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlanAssociation_async", "segments": [ { - "end": 56, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 62, "start": 27, "type": "SHORT" }, @@ -437,22 +437,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_create_backup_vault_async.py" + "title": "backupdr_v1_generated_backup_dr_create_backup_plan_association_async.py" }, { "canonical": true, @@ -461,30 +461,30 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_backup_vault", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_backup_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupVault", + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "CreateBackupVault" + "shortName": "CreateBackupPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.CreateBackupVaultRequest" + "type": "google.cloud.backupdr_v1.types.CreateBackupPlanAssociationRequest" }, { "name": "parent", "type": "str" }, { - "name": "backup_vault", - "type": "google.cloud.backupdr_v1.types.BackupVault" + "name": "backup_plan_association", + "type": "google.cloud.backupdr_v1.types.BackupPlanAssociation" }, { - "name": "backup_vault_id", + "name": "backup_plan_association_id", "type": "str" }, { @@ -501,21 +501,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_backup_vault" + "shortName": "create_backup_plan_association" }, - "description": "Sample for CreateBackupVault", - "file": "backupdr_v1_generated_backup_dr_create_backup_vault_sync.py", + "description": "Sample for CreateBackupPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_create_backup_plan_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupVault_sync", + "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlanAssociation_sync", "segments": [ { - "end": 56, + "end": 62, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 62, "start": 27, "type": "SHORT" }, @@ -525,22 +525,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 59, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 63, + "start": 60, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_create_backup_vault_sync.py" + "title": "backupdr_v1_generated_backup_dr_create_backup_plan_association_sync.py" }, { "canonical": true, @@ -550,30 +550,30 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_management_server", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_backup_plan", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.CreateManagementServer", + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupPlan", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "CreateManagementServer" + "shortName": "CreateBackupPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.CreateManagementServerRequest" + "type": "google.cloud.backupdr_v1.types.CreateBackupPlanRequest" }, { "name": "parent", "type": "str" }, { - "name": "management_server", - "type": "google.cloud.backupdr_v1.types.ManagementServer" + "name": "backup_plan", + "type": "google.cloud.backupdr_v1.types.BackupPlan" }, { - "name": "management_server_id", + "name": "backup_plan_id", "type": "str" }, { @@ -590,21 +590,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_management_server" + "shortName": "create_backup_plan" }, - "description": "Sample for CreateManagementServer", - "file": "backupdr_v1_generated_backup_dr_create_management_server_async.py", + "description": "Sample for CreateBackupPlan", + "file": "backupdr_v1_generated_backup_dr_create_backup_plan_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_CreateManagementServer_async", + "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlan_async", "segments": [ { - "end": 56, + "end": 67, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 67, "start": 27, "type": "SHORT" }, @@ -614,22 +614,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 57, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 64, + "start": 58, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 68, + "start": 65, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_create_management_server_async.py" + "title": "backupdr_v1_generated_backup_dr_create_backup_plan_async.py" }, { "canonical": true, @@ -638,30 +638,4642 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_management_server", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_backup_plan", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.CreateManagementServer", + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupPlan", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "CreateManagementServer" + "shortName": "CreateBackupPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.CreateManagementServerRequest" + "type": "google.cloud.backupdr_v1.types.CreateBackupPlanRequest" }, { "name": "parent", "type": "str" }, { - "name": "management_server", - "type": "google.cloud.backupdr_v1.types.ManagementServer" + "name": "backup_plan", + "type": "google.cloud.backupdr_v1.types.BackupPlan" + }, + { + "name": "backup_plan_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_backup_plan" + }, + "description": "Sample for CreateBackupPlan", + "file": "backupdr_v1_generated_backup_dr_create_backup_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupPlan_sync", + "segments": [ + { + "end": 67, + "start": 27, + "type": "FULL" + }, + { + "end": 67, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 57, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 64, + "start": 58, + "type": "REQUEST_EXECUTION" + }, + { + "end": 68, + "start": 65, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_create_backup_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateBackupVaultRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup_vault", + "type": "google.cloud.backupdr_v1.types.BackupVault" + }, + { + "name": "backup_vault_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_backup_vault" + }, + "description": "Sample for CreateBackupVault", + "file": "backupdr_v1_generated_backup_dr_create_backup_vault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupVault_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": "backupdr_v1_generated_backup_dr_create_backup_vault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateBackupVaultRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "backup_vault", + "type": "google.cloud.backupdr_v1.types.BackupVault" + }, + { + "name": "backup_vault_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_backup_vault" + }, + "description": "Sample for CreateBackupVault", + "file": "backupdr_v1_generated_backup_dr_create_backup_vault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateBackupVault_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": "backupdr_v1_generated_backup_dr_create_backup_vault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateManagementServerRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "management_server", + "type": "google.cloud.backupdr_v1.types.ManagementServer" + }, + { + "name": "management_server_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_management_server" + }, + "description": "Sample for CreateManagementServer", + "file": "backupdr_v1_generated_backup_dr_create_management_server_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateManagementServer_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": "backupdr_v1_generated_backup_dr_create_management_server_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateManagementServerRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "management_server", + "type": "google.cloud.backupdr_v1.types.ManagementServer" + }, + { + "name": "management_server_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_management_server" + }, + "description": "Sample for CreateManagementServer", + "file": "backupdr_v1_generated_backup_dr_create_management_server_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateManagementServer_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": "backupdr_v1_generated_backup_dr_create_management_server_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateRestoreTemplateRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "restore_template", + "type": "google.cloud.backupdr_v1.types.RestoreTemplate" + }, + { + "name": "restore_template_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_restore_template" + }, + "description": "Sample for CreateRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_create_restore_template_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateRestoreTemplate_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_create_restore_template_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateRestoreTemplateRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "restore_template", + "type": "google.cloud.backupdr_v1.types.RestoreTemplate" + }, + { + "name": "restore_template_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_restore_template" + }, + "description": "Sample for CreateRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_create_restore_template_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateRestoreTemplate_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_create_restore_template_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_restore_verification_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateRestoreVerificationPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateRestoreVerificationPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateRestoreVerificationPlanAssociationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "restore_verification_plan_association", + "type": "google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation" + }, + { + "name": "restore_verification_plan_association_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_restore_verification_plan_association" + }, + "description": "Sample for CreateRestoreVerificationPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlanAssociation_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_restore_verification_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateRestoreVerificationPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateRestoreVerificationPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateRestoreVerificationPlanAssociationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "restore_verification_plan_association", + "type": "google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation" + }, + { + "name": "restore_verification_plan_association_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_restore_verification_plan_association" + }, + "description": "Sample for CreateRestoreVerificationPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlanAssociation_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_create_restore_verification_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.create_restore_verification_plan", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateRestoreVerificationPlan", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateRestoreVerificationPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateRestoreVerificationPlanRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "restore_verification_plan", + "type": "google.cloud.backupdr_v1.types.RestoreVerificationPlan" + }, + { + "name": "restore_verification_plan_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_restore_verification_plan" + }, + "description": "Sample for CreateRestoreVerificationPlan", + "file": "backupdr_v1_generated_backup_dr_create_restore_verification_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlan_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_create_restore_verification_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.create_restore_verification_plan", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.CreateRestoreVerificationPlan", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "CreateRestoreVerificationPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.CreateRestoreVerificationPlanRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "restore_verification_plan", + "type": "google.cloud.backupdr_v1.types.RestoreVerificationPlan" + }, + { + "name": "restore_verification_plan_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_restore_verification_plan" + }, + "description": "Sample for CreateRestoreVerificationPlan", + "file": "backupdr_v1_generated_backup_dr_create_restore_verification_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_CreateRestoreVerificationPlan_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_create_restore_verification_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteAutoProtectionPolicyRequest" + }, + { + "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_auto_protection_policy" + }, + "description": "Sample for DeleteAutoProtectionPolicy", + "file": "backupdr_v1_generated_backup_dr_delete_auto_protection_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteAutoProtectionPolicy_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": "backupdr_v1_generated_backup_dr_delete_auto_protection_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteAutoProtectionPolicyRequest" + }, + { + "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_auto_protection_policy" + }, + "description": "Sample for DeleteAutoProtectionPolicy", + "file": "backupdr_v1_generated_backup_dr_delete_auto_protection_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteAutoProtectionPolicy_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": "backupdr_v1_generated_backup_dr_delete_auto_protection_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteBackupPlanAssociationRequest" + }, + { + "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_plan_association" + }, + "description": "Sample for DeleteBackupPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_delete_backup_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupPlanAssociation_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": "backupdr_v1_generated_backup_dr_delete_backup_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteBackupPlanAssociationRequest" + }, + { + "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_plan_association" + }, + "description": "Sample for DeleteBackupPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_delete_backup_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupPlanAssociation_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": "backupdr_v1_generated_backup_dr_delete_backup_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteBackupPlanRequest" + }, + { + "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_plan" + }, + "description": "Sample for DeleteBackupPlan", + "file": "backupdr_v1_generated_backup_dr_delete_backup_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupPlan_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": "backupdr_v1_generated_backup_dr_delete_backup_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteBackupPlanRequest" + }, + { + "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_plan" + }, + "description": "Sample for DeleteBackupPlan", + "file": "backupdr_v1_generated_backup_dr_delete_backup_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupPlan_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": "backupdr_v1_generated_backup_dr_delete_backup_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteBackupVaultRequest" + }, + { + "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_vault" + }, + "description": "Sample for DeleteBackupVault", + "file": "backupdr_v1_generated_backup_dr_delete_backup_vault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupVault_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": "backupdr_v1_generated_backup_dr_delete_backup_vault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteBackupVaultRequest" + }, + { + "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_vault" + }, + "description": "Sample for DeleteBackupVault", + "file": "backupdr_v1_generated_backup_dr_delete_backup_vault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupVault_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": "backupdr_v1_generated_backup_dr_delete_backup_vault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_backup", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackup", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.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": "backupdr_v1_generated_backup_dr_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_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": "backupdr_v1_generated_backup_dr_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_backup", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackup", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.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": "backupdr_v1_generated_backup_dr_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_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": "backupdr_v1_generated_backup_dr_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteManagementServerRequest" + }, + { + "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_management_server" + }, + "description": "Sample for DeleteManagementServer", + "file": "backupdr_v1_generated_backup_dr_delete_management_server_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteManagementServer_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": "backupdr_v1_generated_backup_dr_delete_management_server_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteManagementServerRequest" + }, + { + "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_management_server" + }, + "description": "Sample for DeleteManagementServer", + "file": "backupdr_v1_generated_backup_dr_delete_management_server_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteManagementServer_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": "backupdr_v1_generated_backup_dr_delete_management_server_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteRestoreTemplateRequest" + }, + { + "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_restore_template" + }, + "description": "Sample for DeleteRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_delete_restore_template_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteRestoreTemplate_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": "backupdr_v1_generated_backup_dr_delete_restore_template_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteRestoreTemplateRequest" + }, + { + "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_restore_template" + }, + "description": "Sample for DeleteRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_delete_restore_template_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteRestoreTemplate_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": "backupdr_v1_generated_backup_dr_delete_restore_template_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_restore_verification_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteRestoreVerificationPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreVerificationPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteRestoreVerificationPlanAssociationRequest" + }, + { + "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_restore_verification_plan_association" + }, + "description": "Sample for DeleteRestoreVerificationPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_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": "backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_restore_verification_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteRestoreVerificationPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreVerificationPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteRestoreVerificationPlanAssociationRequest" + }, + { + "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_restore_verification_plan_association" + }, + "description": "Sample for DeleteRestoreVerificationPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_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": "backupdr_v1_generated_backup_dr_delete_restore_verification_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_restore_verification_plan", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteRestoreVerificationPlan", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreVerificationPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteRestoreVerificationPlanRequest" + }, + { + "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_restore_verification_plan" + }, + "description": "Sample for DeleteRestoreVerificationPlan", + "file": "backupdr_v1_generated_backup_dr_delete_restore_verification_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlan_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": "backupdr_v1_generated_backup_dr_delete_restore_verification_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_restore_verification_plan", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteRestoreVerificationPlan", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreVerificationPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.DeleteRestoreVerificationPlanRequest" + }, + { + "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_restore_verification_plan" + }, + "description": "Sample for DeleteRestoreVerificationPlan", + "file": "backupdr_v1_generated_backup_dr_delete_restore_verification_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_DeleteRestoreVerificationPlan_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": "backupdr_v1_generated_backup_dr_delete_restore_verification_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.fetch_backup_plan_associations_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.FetchBackupPlanAssociationsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupPlanAssociationsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.FetchBackupPlanAssociationsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager", + "shortName": "fetch_backup_plan_associations_for_resource_type" + }, + "description": "Sample for FetchBackupPlanAssociationsForResourceType", + "file": "backupdr_v1_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.fetch_backup_plan_associations_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.FetchBackupPlanAssociationsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupPlanAssociationsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.FetchBackupPlanAssociationsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypePager", + "shortName": "fetch_backup_plan_associations_for_resource_type" + }, + "description": "Sample for FetchBackupPlanAssociationsForResourceType", + "file": "backupdr_v1_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_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": "backupdr_v1_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.fetch_backups_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.FetchBackupsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.FetchBackupsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1.services.backup_dr.pagers.FetchBackupsForResourceTypeAsyncPager", + "shortName": "fetch_backups_for_resource_type" + }, + "description": "Sample for FetchBackupsForResourceType", + "file": "backupdr_v1_generated_backup_dr_fetch_backups_for_resource_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_FetchBackupsForResourceType_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_fetch_backups_for_resource_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.fetch_backups_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.FetchBackupsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.FetchBackupsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1.services.backup_dr.pagers.FetchBackupsForResourceTypePager", + "shortName": "fetch_backups_for_resource_type" + }, + "description": "Sample for FetchBackupsForResourceType", + "file": "backupdr_v1_generated_backup_dr_fetch_backups_for_resource_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_FetchBackupsForResourceType_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": "backupdr_v1_generated_backup_dr_fetch_backups_for_resource_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.fetch_data_source_references_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.FetchDataSourceReferencesForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchDataSourceReferencesForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.FetchDataSourceReferencesForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypeAsyncPager", + "shortName": "fetch_data_source_references_for_resource_type" + }, + "description": "Sample for FetchDataSourceReferencesForResourceType", + "file": "backupdr_v1_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_FetchDataSourceReferencesForResourceType_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.fetch_data_source_references_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.FetchDataSourceReferencesForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchDataSourceReferencesForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.FetchDataSourceReferencesForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypePager", + "shortName": "fetch_data_source_references_for_resource_type" + }, + "description": "Sample for FetchDataSourceReferencesForResourceType", + "file": "backupdr_v1_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_FetchDataSourceReferencesForResourceType_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": "backupdr_v1_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.fetch_usable_backup_vaults", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.FetchUsableBackupVaults", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchUsableBackupVaults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.FetchUsableBackupVaultsRequest" + }, + { + "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.backupdr_v1.services.backup_dr.pagers.FetchUsableBackupVaultsAsyncPager", + "shortName": "fetch_usable_backup_vaults" + }, + "description": "Sample for FetchUsableBackupVaults", + "file": "backupdr_v1_generated_backup_dr_fetch_usable_backup_vaults_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_FetchUsableBackupVaults_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": "backupdr_v1_generated_backup_dr_fetch_usable_backup_vaults_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.fetch_usable_backup_vaults", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.FetchUsableBackupVaults", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchUsableBackupVaults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.FetchUsableBackupVaultsRequest" + }, + { + "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.backupdr_v1.services.backup_dr.pagers.FetchUsableBackupVaultsPager", + "shortName": "fetch_usable_backup_vaults" + }, + "description": "Sample for FetchUsableBackupVaults", + "file": "backupdr_v1_generated_backup_dr_fetch_usable_backup_vaults_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_FetchUsableBackupVaults_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": "backupdr_v1_generated_backup_dr_fetch_usable_backup_vaults_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetAutoProtectionPolicyBindingRequest" + }, + { + "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.backupdr_v1.types.AutoProtectionPolicyBinding", + "shortName": "get_auto_protection_policy_binding" + }, + "description": "Sample for GetAutoProtectionPolicyBinding", + "file": "backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetAutoProtectionPolicyBinding_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": "backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetAutoProtectionPolicyBindingRequest" + }, + { + "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.backupdr_v1.types.AutoProtectionPolicyBinding", + "shortName": "get_auto_protection_policy_binding" + }, + "description": "Sample for GetAutoProtectionPolicyBinding", + "file": "backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetAutoProtectionPolicyBinding_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": "backupdr_v1_generated_backup_dr_get_auto_protection_policy_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetAutoProtectionPolicyRequest" + }, + { + "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.backupdr_v1.types.AutoProtectionPolicy", + "shortName": "get_auto_protection_policy" + }, + "description": "Sample for GetAutoProtectionPolicy", + "file": "backupdr_v1_generated_backup_dr_get_auto_protection_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetAutoProtectionPolicy_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": "backupdr_v1_generated_backup_dr_get_auto_protection_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetAutoProtectionPolicyRequest" + }, + { + "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.backupdr_v1.types.AutoProtectionPolicy", + "shortName": "get_auto_protection_policy" + }, + "description": "Sample for GetAutoProtectionPolicy", + "file": "backupdr_v1_generated_backup_dr_get_auto_protection_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetAutoProtectionPolicy_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": "backupdr_v1_generated_backup_dr_get_auto_protection_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetBackupPlanAssociationRequest" + }, + { + "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.backupdr_v1.types.BackupPlanAssociation", + "shortName": "get_backup_plan_association" + }, + "description": "Sample for GetBackupPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_get_backup_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlanAssociation_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": "backupdr_v1_generated_backup_dr_get_backup_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetBackupPlanAssociationRequest" + }, + { + "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.backupdr_v1.types.BackupPlanAssociation", + "shortName": "get_backup_plan_association" + }, + "description": "Sample for GetBackupPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_get_backup_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlanAssociation_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": "backupdr_v1_generated_backup_dr_get_backup_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup_plan_revision", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlanRevision", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetBackupPlanRevisionRequest" + }, + { + "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.backupdr_v1.types.BackupPlanRevision", + "shortName": "get_backup_plan_revision" + }, + "description": "Sample for GetBackupPlanRevision", + "file": "backupdr_v1_generated_backup_dr_get_backup_plan_revision_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlanRevision_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": "backupdr_v1_generated_backup_dr_get_backup_plan_revision_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup_plan_revision", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlanRevision", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetBackupPlanRevisionRequest" + }, + { + "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.backupdr_v1.types.BackupPlanRevision", + "shortName": "get_backup_plan_revision" + }, + "description": "Sample for GetBackupPlanRevision", + "file": "backupdr_v1_generated_backup_dr_get_backup_plan_revision_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlanRevision_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": "backupdr_v1_generated_backup_dr_get_backup_plan_revision_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetBackupPlanRequest" + }, + { + "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.backupdr_v1.types.BackupPlan", + "shortName": "get_backup_plan" + }, + "description": "Sample for GetBackupPlan", + "file": "backupdr_v1_generated_backup_dr_get_backup_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlan_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": "backupdr_v1_generated_backup_dr_get_backup_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetBackupPlanRequest" + }, + { + "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.backupdr_v1.types.BackupPlan", + "shortName": "get_backup_plan" + }, + "description": "Sample for GetBackupPlan", + "file": "backupdr_v1_generated_backup_dr_get_backup_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlan_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": "backupdr_v1_generated_backup_dr_get_backup_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetBackupVaultRequest" + }, + { + "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.backupdr_v1.types.BackupVault", + "shortName": "get_backup_vault" + }, + "description": "Sample for GetBackupVault", + "file": "backupdr_v1_generated_backup_dr_get_backup_vault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetBackupVault_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": "backupdr_v1_generated_backup_dr_get_backup_vault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetBackupVaultRequest" + }, + { + "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.backupdr_v1.types.BackupVault", + "shortName": "get_backup_vault" + }, + "description": "Sample for GetBackupVault", + "file": "backupdr_v1_generated_backup_dr_get_backup_vault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetBackupVault_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": "backupdr_v1_generated_backup_dr_get_backup_vault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackup", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.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.backupdr_v1.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "backupdr_v1_generated_backup_dr_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_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": "backupdr_v1_generated_backup_dr_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackup", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.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.backupdr_v1.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "backupdr_v1_generated_backup_dr_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_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": "backupdr_v1_generated_backup_dr_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_data_source_reference", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetDataSourceReference", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetDataSourceReference" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetDataSourceReferenceRequest" + }, + { + "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.backupdr_v1.types.DataSourceReference", + "shortName": "get_data_source_reference" + }, + "description": "Sample for GetDataSourceReference", + "file": "backupdr_v1_generated_backup_dr_get_data_source_reference_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetDataSourceReference_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": "backupdr_v1_generated_backup_dr_get_data_source_reference_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_data_source_reference", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetDataSourceReference", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetDataSourceReference" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetDataSourceReferenceRequest" + }, + { + "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.backupdr_v1.types.DataSourceReference", + "shortName": "get_data_source_reference" + }, + "description": "Sample for GetDataSourceReference", + "file": "backupdr_v1_generated_backup_dr_get_data_source_reference_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetDataSourceReference_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": "backupdr_v1_generated_backup_dr_get_data_source_reference_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_data_source", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetDataSource", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetDataSourceRequest" + }, + { + "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.backupdr_v1.types.DataSource", + "shortName": "get_data_source" + }, + "description": "Sample for GetDataSource", + "file": "backupdr_v1_generated_backup_dr_get_data_source_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetDataSource_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": "backupdr_v1_generated_backup_dr_get_data_source_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_data_source", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetDataSource", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetDataSource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetDataSourceRequest" + }, + { + "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.backupdr_v1.types.DataSource", + "shortName": "get_data_source" + }, + "description": "Sample for GetDataSource", + "file": "backupdr_v1_generated_backup_dr_get_data_source_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetDataSource_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": "backupdr_v1_generated_backup_dr_get_data_source_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetManagementServerRequest" + }, + { + "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.backupdr_v1.types.ManagementServer", + "shortName": "get_management_server" + }, + "description": "Sample for GetManagementServer", + "file": "backupdr_v1_generated_backup_dr_get_management_server_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_GetManagementServer_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": "backupdr_v1_generated_backup_dr_get_management_server_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.GetManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.GetManagementServerRequest" }, { - "name": "management_server_id", + "name": "name", "type": "str" }, { @@ -677,22 +5289,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_management_server" + "resultType": "google.cloud.backupdr_v1.types.ManagementServer", + "shortName": "get_management_server" }, - "description": "Sample for CreateManagementServer", - "file": "backupdr_v1_generated_backup_dr_create_management_server_sync.py", + "description": "Sample for GetManagementServer", + "file": "backupdr_v1_generated_backup_dr_get_management_server_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_CreateManagementServer_sync", + "regionTag": "backupdr_v1_generated_BackupDR_GetManagementServer_sync", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -702,22 +5314,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_create_management_server_sync.py" + "title": "backupdr_v1_generated_backup_dr_get_management_server_sync.py" }, { "canonical": true, @@ -727,19 +5339,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_backup_plan_association", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_restore_template_execution", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1.BackupDR.GetRestoreTemplateExecution", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupPlanAssociation" + "shortName": "GetRestoreTemplateExecution" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1.types.GetRestoreTemplateExecutionRequest" }, { "name": "name", @@ -758,22 +5370,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_backup_plan_association" + "resultType": "google.cloud.backupdr_v1.types.RestoreTemplateExecution", + "shortName": "get_restore_template_execution" }, - "description": "Sample for DeleteBackupPlanAssociation", - "file": "backupdr_v1_generated_backup_dr_delete_backup_plan_association_async.py", + "description": "Sample for GetRestoreTemplateExecution", + "file": "backupdr_v1_generated_backup_dr_get_restore_template_execution_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupPlanAssociation_async", + "regionTag": "backupdr_v1_generated_BackupDR_GetRestoreTemplateExecution_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -788,17 +5400,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_backup_plan_association_async.py" + "title": "backupdr_v1_generated_backup_dr_get_restore_template_execution_async.py" }, { "canonical": true, @@ -807,19 +5419,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_backup_plan_association", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_restore_template_execution", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1.BackupDR.GetRestoreTemplateExecution", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupPlanAssociation" + "shortName": "GetRestoreTemplateExecution" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1.types.GetRestoreTemplateExecutionRequest" }, { "name": "name", @@ -838,22 +5450,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_backup_plan_association" + "resultType": "google.cloud.backupdr_v1.types.RestoreTemplateExecution", + "shortName": "get_restore_template_execution" }, - "description": "Sample for DeleteBackupPlanAssociation", - "file": "backupdr_v1_generated_backup_dr_delete_backup_plan_association_sync.py", + "description": "Sample for GetRestoreTemplateExecution", + "file": "backupdr_v1_generated_backup_dr_get_restore_template_execution_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupPlanAssociation_sync", + "regionTag": "backupdr_v1_generated_BackupDR_GetRestoreTemplateExecution_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -868,17 +5480,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_backup_plan_association_sync.py" + "title": "backupdr_v1_generated_backup_dr_get_restore_template_execution_sync.py" }, { "canonical": true, @@ -888,19 +5500,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_backup_plan", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupPlan", + "fullName": "google.cloud.backupdr.v1.BackupDR.GetRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupPlan" + "shortName": "GetRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteBackupPlanRequest" + "type": "google.cloud.backupdr_v1.types.GetRestoreTemplateRequest" }, { "name": "name", @@ -919,22 +5531,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_backup_plan" + "resultType": "google.cloud.backupdr_v1.types.RestoreTemplate", + "shortName": "get_restore_template" }, - "description": "Sample for DeleteBackupPlan", - "file": "backupdr_v1_generated_backup_dr_delete_backup_plan_async.py", + "description": "Sample for GetRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_get_restore_template_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupPlan_async", + "regionTag": "backupdr_v1_generated_BackupDR_GetRestoreTemplate_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -949,17 +5561,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_backup_plan_async.py" + "title": "backupdr_v1_generated_backup_dr_get_restore_template_async.py" }, { "canonical": true, @@ -968,19 +5580,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_backup_plan", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupPlan", + "fullName": "google.cloud.backupdr.v1.BackupDR.GetRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupPlan" + "shortName": "GetRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteBackupPlanRequest" + "type": "google.cloud.backupdr_v1.types.GetRestoreTemplateRequest" }, { "name": "name", @@ -999,22 +5611,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_backup_plan" + "resultType": "google.cloud.backupdr_v1.types.RestoreTemplate", + "shortName": "get_restore_template" }, - "description": "Sample for DeleteBackupPlan", - "file": "backupdr_v1_generated_backup_dr_delete_backup_plan_sync.py", + "description": "Sample for GetRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_get_restore_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupPlan_sync", + "regionTag": "backupdr_v1_generated_BackupDR_GetRestoreTemplate_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1029,17 +5641,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_backup_plan_sync.py" + "title": "backupdr_v1_generated_backup_dr_get_restore_template_sync.py" }, { "canonical": true, @@ -1049,19 +5661,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_backup_vault", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_restore_verification_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupVault", + "fullName": "google.cloud.backupdr.v1.BackupDR.GetRestoreVerificationPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupVault" + "shortName": "GetRestoreVerificationPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteBackupVaultRequest" + "type": "google.cloud.backupdr_v1.types.GetRestoreVerificationPlanAssociationRequest" }, { "name": "name", @@ -1080,22 +5692,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_backup_vault" + "resultType": "google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation", + "shortName": "get_restore_verification_plan_association" }, - "description": "Sample for DeleteBackupVault", - "file": "backupdr_v1_generated_backup_dr_delete_backup_vault_async.py", + "description": "Sample for GetRestoreVerificationPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupVault_async", + "regionTag": "backupdr_v1_generated_BackupDR_GetRestoreVerificationPlanAssociation_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1110,17 +5722,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_backup_vault_async.py" + "title": "backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_async.py" }, { "canonical": true, @@ -1129,19 +5741,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_backup_vault", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_restore_verification_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackupVault", + "fullName": "google.cloud.backupdr.v1.BackupDR.GetRestoreVerificationPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupVault" + "shortName": "GetRestoreVerificationPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteBackupVaultRequest" + "type": "google.cloud.backupdr_v1.types.GetRestoreVerificationPlanAssociationRequest" }, { "name": "name", @@ -1160,22 +5772,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_backup_vault" + "resultType": "google.cloud.backupdr_v1.types.RestoreVerificationPlanAssociation", + "shortName": "get_restore_verification_plan_association" }, - "description": "Sample for DeleteBackupVault", - "file": "backupdr_v1_generated_backup_dr_delete_backup_vault_sync.py", + "description": "Sample for GetRestoreVerificationPlanAssociation", + "file": "backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackupVault_sync", + "regionTag": "backupdr_v1_generated_BackupDR_GetRestoreVerificationPlanAssociation_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1190,17 +5802,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_backup_vault_sync.py" + "title": "backupdr_v1_generated_backup_dr_get_restore_verification_plan_association_sync.py" }, { "canonical": true, @@ -1210,19 +5822,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_backup", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_restore_verification_plan", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackup", + "fullName": "google.cloud.backupdr.v1.BackupDR.GetRestoreVerificationPlan", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackup" + "shortName": "GetRestoreVerificationPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteBackupRequest" + "type": "google.cloud.backupdr_v1.types.GetRestoreVerificationPlanRequest" }, { "name": "name", @@ -1241,22 +5853,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_backup" + "resultType": "google.cloud.backupdr_v1.types.RestoreVerificationPlan", + "shortName": "get_restore_verification_plan" }, - "description": "Sample for DeleteBackup", - "file": "backupdr_v1_generated_backup_dr_delete_backup_async.py", + "description": "Sample for GetRestoreVerificationPlan", + "file": "backupdr_v1_generated_backup_dr_get_restore_verification_plan_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackup_async", + "regionTag": "backupdr_v1_generated_BackupDR_GetRestoreVerificationPlan_async", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1271,17 +5883,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_backup_async.py" + "title": "backupdr_v1_generated_backup_dr_get_restore_verification_plan_async.py" }, { "canonical": true, @@ -1290,19 +5902,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_backup", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_restore_verification_plan", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteBackup", + "fullName": "google.cloud.backupdr.v1.BackupDR.GetRestoreVerificationPlan", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackup" + "shortName": "GetRestoreVerificationPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteBackupRequest" + "type": "google.cloud.backupdr_v1.types.GetRestoreVerificationPlanRequest" }, { "name": "name", @@ -1321,22 +5933,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_backup" + "resultType": "google.cloud.backupdr_v1.types.RestoreVerificationPlan", + "shortName": "get_restore_verification_plan" }, - "description": "Sample for DeleteBackup", - "file": "backupdr_v1_generated_backup_dr_delete_backup_sync.py", + "description": "Sample for GetRestoreVerificationPlan", + "file": "backupdr_v1_generated_backup_dr_get_restore_verification_plan_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteBackup_sync", + "regionTag": "backupdr_v1_generated_BackupDR_GetRestoreVerificationPlan_sync", "segments": [ { - "end": 55, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1351,17 +5963,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_backup_sync.py" + "title": "backupdr_v1_generated_backup_dr_get_restore_verification_plan_sync.py" }, { "canonical": true, @@ -1371,23 +5983,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.delete_management_server", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.initialize_service", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteManagementServer", + "fullName": "google.cloud.backupdr.v1.BackupDR.InitializeService", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteManagementServer" + "shortName": "InitializeService" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteManagementServerRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.backupdr_v1.types.InitializeServiceRequest" }, { "name": "retry", @@ -1403,21 +6011,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_management_server" + "shortName": "initialize_service" }, - "description": "Sample for DeleteManagementServer", - "file": "backupdr_v1_generated_backup_dr_delete_management_server_async.py", + "description": "Sample for InitializeService", + "file": "backupdr_v1_generated_backup_dr_initialize_service_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteManagementServer_async", + "regionTag": "backupdr_v1_generated_BackupDR_InitializeService_async", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -1427,22 +6035,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_management_server_async.py" + "title": "backupdr_v1_generated_backup_dr_initialize_service_async.py" }, { "canonical": true, @@ -1451,23 +6059,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.delete_management_server", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.initialize_service", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.DeleteManagementServer", + "fullName": "google.cloud.backupdr.v1.BackupDR.InitializeService", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteManagementServer" + "shortName": "InitializeService" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.DeleteManagementServerRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.backupdr_v1.types.InitializeServiceRequest" }, { "name": "retry", @@ -1483,21 +6087,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_management_server" + "shortName": "initialize_service" }, - "description": "Sample for DeleteManagementServer", - "file": "backupdr_v1_generated_backup_dr_delete_management_server_sync.py", + "description": "Sample for InitializeService", + "file": "backupdr_v1_generated_backup_dr_initialize_service_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_DeleteManagementServer_sync", + "regionTag": "backupdr_v1_generated_BackupDR_InitializeService_sync", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -1507,22 +6111,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, - { - "end": 52, - "start": 46, + { + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_delete_management_server_sync.py" + "title": "backupdr_v1_generated_backup_dr_initialize_service_sync.py" }, { "canonical": true, @@ -1532,26 +6136,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.fetch_backup_plan_associations_for_resource_type", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.initiate_delete_auto_protection_policy_binding", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.FetchBackupPlanAssociationsForResourceType", + "fullName": "google.cloud.backupdr.v1.BackupDR.InitiateDeleteAutoProtectionPolicyBinding", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchBackupPlanAssociationsForResourceType" + "shortName": "InitiateDeleteAutoProtectionPolicyBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.FetchBackupPlanAssociationsForResourceTypeRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.backupdr_v1.types.InitiateDeleteAutoProtectionPolicyBindingRequest" }, { - "name": "resource_type", + "name": "name", "type": "str" }, { @@ -1567,22 +6167,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager", - "shortName": "fetch_backup_plan_associations_for_resource_type" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "initiate_delete_auto_protection_policy_binding" }, - "description": "Sample for FetchBackupPlanAssociationsForResourceType", - "file": "backupdr_v1_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py", + "description": "Sample for InitiateDeleteAutoProtectionPolicyBinding", + "file": "backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_async", + "regionTag": "backupdr_v1_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_async", "segments": [ { - "end": 53, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1592,22 +6192,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py" + "title": "backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py" }, { "canonical": true, @@ -1616,26 +6216,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.fetch_backup_plan_associations_for_resource_type", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.initiate_delete_auto_protection_policy_binding", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.FetchBackupPlanAssociationsForResourceType", + "fullName": "google.cloud.backupdr.v1.BackupDR.InitiateDeleteAutoProtectionPolicyBinding", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchBackupPlanAssociationsForResourceType" + "shortName": "InitiateDeleteAutoProtectionPolicyBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.FetchBackupPlanAssociationsForResourceTypeRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.backupdr_v1.types.InitiateDeleteAutoProtectionPolicyBindingRequest" }, { - "name": "resource_type", + "name": "name", "type": "str" }, { @@ -1651,22 +6247,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypePager", - "shortName": "fetch_backup_plan_associations_for_resource_type" + "resultType": "google.api_core.operation.Operation", + "shortName": "initiate_delete_auto_protection_policy_binding" }, - "description": "Sample for FetchBackupPlanAssociationsForResourceType", - "file": "backupdr_v1_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py", + "description": "Sample for InitiateDeleteAutoProtectionPolicyBinding", + "file": "backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_sync", + "regionTag": "backupdr_v1_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_sync", "segments": [ { - "end": 53, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 55, "start": 27, "type": "SHORT" }, @@ -1676,22 +6272,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py" + "title": "backupdr_v1_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py" }, { "canonical": true, @@ -1701,28 +6297,24 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.fetch_backups_for_resource_type", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_applied_auto_protection_policies", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.FetchBackupsForResourceType", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListAppliedAutoProtectionPolicies", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchBackupsForResourceType" + "shortName": "ListAppliedAutoProtectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.FetchBackupsForResourceTypeRequest" + "type": "google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "resource_type", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1736,22 +6328,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.FetchBackupsForResourceTypeAsyncPager", - "shortName": "fetch_backups_for_resource_type" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesAsyncPager", + "shortName": "list_applied_auto_protection_policies" }, - "description": "Sample for FetchBackupsForResourceType", - "file": "backupdr_v1_generated_backup_dr_fetch_backups_for_resource_type_async.py", + "description": "Sample for ListAppliedAutoProtectionPolicies", + "file": "backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_FetchBackupsForResourceType_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListAppliedAutoProtectionPolicies_async", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1761,22 +6353,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": 54, - "start": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_fetch_backups_for_resource_type_async.py" + "title": "backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_async.py" }, { "canonical": true, @@ -1785,28 +6377,24 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.fetch_backups_for_resource_type", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_applied_auto_protection_policies", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.FetchBackupsForResourceType", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListAppliedAutoProtectionPolicies", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchBackupsForResourceType" + "shortName": "ListAppliedAutoProtectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.FetchBackupsForResourceTypeRequest" + "type": "google.cloud.backupdr_v1.types.ListAppliedAutoProtectionPoliciesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "resource_type", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1820,22 +6408,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.FetchBackupsForResourceTypePager", - "shortName": "fetch_backups_for_resource_type" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesPager", + "shortName": "list_applied_auto_protection_policies" }, - "description": "Sample for FetchBackupsForResourceType", - "file": "backupdr_v1_generated_backup_dr_fetch_backups_for_resource_type_sync.py", + "description": "Sample for ListAppliedAutoProtectionPolicies", + "file": "backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_FetchBackupsForResourceType_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListAppliedAutoProtectionPolicies_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1845,22 +6433,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": 54, - "start": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_fetch_backups_for_resource_type_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_applied_auto_protection_policies_sync.py" }, { "canonical": true, @@ -1870,28 +6458,24 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.fetch_data_source_references_for_resource_type", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_auto_protection_policies", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.FetchDataSourceReferencesForResourceType", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListAutoProtectionPolicies", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchDataSourceReferencesForResourceType" + "shortName": "ListAutoProtectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.FetchDataSourceReferencesForResourceTypeRequest" + "type": "google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "resource_type", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1905,22 +6489,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypeAsyncPager", - "shortName": "fetch_data_source_references_for_resource_type" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListAutoProtectionPoliciesAsyncPager", + "shortName": "list_auto_protection_policies" }, - "description": "Sample for FetchDataSourceReferencesForResourceType", - "file": "backupdr_v1_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py", + "description": "Sample for ListAutoProtectionPolicies", + "file": "backupdr_v1_generated_backup_dr_list_auto_protection_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_FetchDataSourceReferencesForResourceType_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListAutoProtectionPolicies_async", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1930,22 +6514,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": 54, - "start": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py" + "title": "backupdr_v1_generated_backup_dr_list_auto_protection_policies_async.py" }, { "canonical": true, @@ -1954,28 +6538,24 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.fetch_data_source_references_for_resource_type", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_auto_protection_policies", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.FetchDataSourceReferencesForResourceType", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListAutoProtectionPolicies", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchDataSourceReferencesForResourceType" + "shortName": "ListAutoProtectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.FetchDataSourceReferencesForResourceTypeRequest" + "type": "google.cloud.backupdr_v1.types.ListAutoProtectionPoliciesRequest" }, { "name": "parent", "type": "str" }, - { - "name": "resource_type", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1989,22 +6569,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypePager", - "shortName": "fetch_data_source_references_for_resource_type" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListAutoProtectionPoliciesPager", + "shortName": "list_auto_protection_policies" }, - "description": "Sample for FetchDataSourceReferencesForResourceType", - "file": "backupdr_v1_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py", + "description": "Sample for ListAutoProtectionPolicies", + "file": "backupdr_v1_generated_backup_dr_list_auto_protection_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_FetchDataSourceReferencesForResourceType_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListAutoProtectionPolicies_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2014,22 +6594,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": 54, - "start": 50, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_auto_protection_policies_sync.py" }, { "canonical": true, @@ -2039,19 +6619,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.fetch_usable_backup_vaults", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_auto_protection_policy_bindings", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.FetchUsableBackupVaults", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListAutoProtectionPolicyBindings", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchUsableBackupVaults" + "shortName": "ListAutoProtectionPolicyBindings" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.FetchUsableBackupVaultsRequest" + "type": "google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsRequest" }, { "name": "parent", @@ -2070,14 +6650,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.FetchUsableBackupVaultsAsyncPager", - "shortName": "fetch_usable_backup_vaults" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsAsyncPager", + "shortName": "list_auto_protection_policy_bindings" }, - "description": "Sample for FetchUsableBackupVaults", - "file": "backupdr_v1_generated_backup_dr_fetch_usable_backup_vaults_async.py", + "description": "Sample for ListAutoProtectionPolicyBindings", + "file": "backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_FetchUsableBackupVaults_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListAutoProtectionPolicyBindings_async", "segments": [ { "end": 52, @@ -2110,7 +6690,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_fetch_usable_backup_vaults_async.py" + "title": "backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_async.py" }, { "canonical": true, @@ -2119,19 +6699,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.fetch_usable_backup_vaults", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_auto_protection_policy_bindings", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.FetchUsableBackupVaults", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListAutoProtectionPolicyBindings", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchUsableBackupVaults" + "shortName": "ListAutoProtectionPolicyBindings" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.FetchUsableBackupVaultsRequest" + "type": "google.cloud.backupdr_v1.types.ListAutoProtectionPolicyBindingsRequest" }, { "name": "parent", @@ -2150,14 +6730,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.FetchUsableBackupVaultsPager", - "shortName": "fetch_usable_backup_vaults" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsPager", + "shortName": "list_auto_protection_policy_bindings" }, - "description": "Sample for FetchUsableBackupVaults", - "file": "backupdr_v1_generated_backup_dr_fetch_usable_backup_vaults_sync.py", + "description": "Sample for ListAutoProtectionPolicyBindings", + "file": "backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_FetchUsableBackupVaults_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListAutoProtectionPolicyBindings_sync", "segments": [ { "end": 52, @@ -2190,7 +6770,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_fetch_usable_backup_vaults_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_auto_protection_policy_bindings_sync.py" }, { "canonical": true, @@ -2200,22 +6780,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup_plan_association", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backup_plan_associations", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlanAssociations", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlanAssociation" + "shortName": "ListBackupPlanAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupPlanAssociationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2231,22 +6811,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.BackupPlanAssociation", - "shortName": "get_backup_plan_association" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlanAssociationsAsyncPager", + "shortName": "list_backup_plan_associations" }, - "description": "Sample for GetBackupPlanAssociation", - "file": "backupdr_v1_generated_backup_dr_get_backup_plan_association_async.py", + "description": "Sample for ListBackupPlanAssociations", + "file": "backupdr_v1_generated_backup_dr_list_backup_plan_associations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlanAssociation_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlanAssociations_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2266,12 +6846,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_plan_association_async.py" + "title": "backupdr_v1_generated_backup_dr_list_backup_plan_associations_async.py" }, { "canonical": true, @@ -2280,22 +6860,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup_plan_association", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backup_plan_associations", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlanAssociations", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlanAssociation" + "shortName": "ListBackupPlanAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupPlanAssociationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2311,22 +6891,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.BackupPlanAssociation", - "shortName": "get_backup_plan_association" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlanAssociationsPager", + "shortName": "list_backup_plan_associations" }, - "description": "Sample for GetBackupPlanAssociation", - "file": "backupdr_v1_generated_backup_dr_get_backup_plan_association_sync.py", + "description": "Sample for ListBackupPlanAssociations", + "file": "backupdr_v1_generated_backup_dr_list_backup_plan_associations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlanAssociation_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlanAssociations_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2346,12 +6926,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_plan_association_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_backup_plan_associations_sync.py" }, { "canonical": true, @@ -2361,22 +6941,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup_plan_revision", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backup_plan_revisions", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlanRevision", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlanRevisions", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlanRevision" + "shortName": "ListBackupPlanRevisions" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupPlanRevisionRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupPlanRevisionsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2392,22 +6972,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.BackupPlanRevision", - "shortName": "get_backup_plan_revision" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlanRevisionsAsyncPager", + "shortName": "list_backup_plan_revisions" }, - "description": "Sample for GetBackupPlanRevision", - "file": "backupdr_v1_generated_backup_dr_get_backup_plan_revision_async.py", + "description": "Sample for ListBackupPlanRevisions", + "file": "backupdr_v1_generated_backup_dr_list_backup_plan_revisions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlanRevision_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlanRevisions_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2427,12 +7007,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_plan_revision_async.py" + "title": "backupdr_v1_generated_backup_dr_list_backup_plan_revisions_async.py" }, { "canonical": true, @@ -2441,22 +7021,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup_plan_revision", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backup_plan_revisions", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlanRevision", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlanRevisions", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlanRevision" + "shortName": "ListBackupPlanRevisions" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupPlanRevisionRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupPlanRevisionsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2472,22 +7052,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.BackupPlanRevision", - "shortName": "get_backup_plan_revision" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlanRevisionsPager", + "shortName": "list_backup_plan_revisions" }, - "description": "Sample for GetBackupPlanRevision", - "file": "backupdr_v1_generated_backup_dr_get_backup_plan_revision_sync.py", + "description": "Sample for ListBackupPlanRevisions", + "file": "backupdr_v1_generated_backup_dr_list_backup_plan_revisions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlanRevision_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlanRevisions_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2507,12 +7087,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_plan_revision_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_backup_plan_revisions_sync.py" }, { "canonical": true, @@ -2522,22 +7102,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup_plan", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backup_plans", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlan", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlans", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlan" + "shortName": "ListBackupPlans" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupPlanRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupPlansRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2553,22 +7133,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.BackupPlan", - "shortName": "get_backup_plan" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlansAsyncPager", + "shortName": "list_backup_plans" }, - "description": "Sample for GetBackupPlan", - "file": "backupdr_v1_generated_backup_dr_get_backup_plan_async.py", + "description": "Sample for ListBackupPlans", + "file": "backupdr_v1_generated_backup_dr_list_backup_plans_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlan_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlans_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2588,12 +7168,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_plan_async.py" + "title": "backupdr_v1_generated_backup_dr_list_backup_plans_async.py" }, { "canonical": true, @@ -2602,22 +7182,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup_plan", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backup_plans", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupPlan", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlans", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlan" + "shortName": "ListBackupPlans" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupPlanRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupPlansRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2633,22 +7213,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.BackupPlan", - "shortName": "get_backup_plan" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlansPager", + "shortName": "list_backup_plans" }, - "description": "Sample for GetBackupPlan", - "file": "backupdr_v1_generated_backup_dr_get_backup_plan_sync.py", + "description": "Sample for ListBackupPlans", + "file": "backupdr_v1_generated_backup_dr_list_backup_plans_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackupPlan_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlans_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2668,12 +7248,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_plan_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_backup_plans_sync.py" }, { "canonical": true, @@ -2683,22 +7263,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup_vault", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backup_vaults", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupVault", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupVaults", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupVault" + "shortName": "ListBackupVaults" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupVaultRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupVaultsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2714,22 +7294,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.BackupVault", - "shortName": "get_backup_vault" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupVaultsAsyncPager", + "shortName": "list_backup_vaults" }, - "description": "Sample for GetBackupVault", - "file": "backupdr_v1_generated_backup_dr_get_backup_vault_async.py", + "description": "Sample for ListBackupVaults", + "file": "backupdr_v1_generated_backup_dr_list_backup_vaults_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackupVault_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackupVaults_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2749,12 +7329,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_vault_async.py" + "title": "backupdr_v1_generated_backup_dr_list_backup_vaults_async.py" }, { "canonical": true, @@ -2763,22 +7343,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup_vault", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backup_vaults", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackupVault", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupVaults", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupVault" + "shortName": "ListBackupVaults" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupVaultRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupVaultsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2794,22 +7374,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.BackupVault", - "shortName": "get_backup_vault" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupVaultsPager", + "shortName": "list_backup_vaults" }, - "description": "Sample for GetBackupVault", - "file": "backupdr_v1_generated_backup_dr_get_backup_vault_sync.py", + "description": "Sample for ListBackupVaults", + "file": "backupdr_v1_generated_backup_dr_list_backup_vaults_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackupVault_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackupVaults_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2829,12 +7409,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_vault_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_backup_vaults_sync.py" }, { "canonical": true, @@ -2844,22 +7424,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_backup", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backups", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackup", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackups", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackup" + "shortName": "ListBackups" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2875,22 +7455,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.Backup", - "shortName": "get_backup" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" }, - "description": "Sample for GetBackup", - "file": "backupdr_v1_generated_backup_dr_get_backup_async.py", + "description": "Sample for ListBackups", + "file": "backupdr_v1_generated_backup_dr_list_backups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackup_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackups_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2910,12 +7490,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_async.py" + "title": "backupdr_v1_generated_backup_dr_list_backups_async.py" }, { "canonical": true, @@ -2924,22 +7504,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_backup", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backups", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetBackup", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackups", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackup" + "shortName": "ListBackups" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetBackupRequest" + "type": "google.cloud.backupdr_v1.types.ListBackupsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2955,22 +7535,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.Backup", - "shortName": "get_backup" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupsPager", + "shortName": "list_backups" }, - "description": "Sample for GetBackup", - "file": "backupdr_v1_generated_backup_dr_get_backup_sync.py", + "description": "Sample for ListBackups", + "file": "backupdr_v1_generated_backup_dr_list_backups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetBackup_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListBackups_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2990,12 +7570,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_backup_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_backups_sync.py" }, { "canonical": true, @@ -3005,22 +7585,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_data_source_reference", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_binding_matching_resources", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetDataSourceReference", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBindingMatchingResources", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetDataSourceReference" + "shortName": "ListBindingMatchingResources" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetDataSourceReferenceRequest" + "type": "google.cloud.backupdr_v1.types.ListBindingMatchingResourcesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3036,22 +7616,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.DataSourceReference", - "shortName": "get_data_source_reference" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBindingMatchingResourcesAsyncPager", + "shortName": "list_binding_matching_resources" }, - "description": "Sample for GetDataSourceReference", - "file": "backupdr_v1_generated_backup_dr_get_data_source_reference_async.py", + "description": "Sample for ListBindingMatchingResources", + "file": "backupdr_v1_generated_backup_dr_list_binding_matching_resources_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetDataSourceReference_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListBindingMatchingResources_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3071,12 +7651,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_data_source_reference_async.py" + "title": "backupdr_v1_generated_backup_dr_list_binding_matching_resources_async.py" }, { "canonical": true, @@ -3085,22 +7665,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_data_source_reference", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_binding_matching_resources", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetDataSourceReference", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListBindingMatchingResources", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetDataSourceReference" + "shortName": "ListBindingMatchingResources" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetDataSourceReferenceRequest" + "type": "google.cloud.backupdr_v1.types.ListBindingMatchingResourcesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3116,22 +7696,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.DataSourceReference", - "shortName": "get_data_source_reference" - }, - "description": "Sample for GetDataSourceReference", - "file": "backupdr_v1_generated_backup_dr_get_data_source_reference_sync.py", + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBindingMatchingResourcesPager", + "shortName": "list_binding_matching_resources" + }, + "description": "Sample for ListBindingMatchingResources", + "file": "backupdr_v1_generated_backup_dr_list_binding_matching_resources_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetDataSourceReference_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListBindingMatchingResources_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3151,12 +7731,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_data_source_reference_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_binding_matching_resources_sync.py" }, { "canonical": true, @@ -3166,22 +7746,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_data_source", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_data_source_references", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetDataSource", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListDataSourceReferences", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetDataSource" + "shortName": "ListDataSourceReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetDataSourceRequest" + "type": "google.cloud.backupdr_v1.types.ListDataSourceReferencesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3197,22 +7777,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.DataSource", - "shortName": "get_data_source" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListDataSourceReferencesAsyncPager", + "shortName": "list_data_source_references" }, - "description": "Sample for GetDataSource", - "file": "backupdr_v1_generated_backup_dr_get_data_source_async.py", + "description": "Sample for ListDataSourceReferences", + "file": "backupdr_v1_generated_backup_dr_list_data_source_references_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetDataSource_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListDataSourceReferences_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3232,12 +7812,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_data_source_async.py" + "title": "backupdr_v1_generated_backup_dr_list_data_source_references_async.py" }, { "canonical": true, @@ -3246,22 +7826,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_data_source", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_data_source_references", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetDataSource", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListDataSourceReferences", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetDataSource" + "shortName": "ListDataSourceReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetDataSourceRequest" + "type": "google.cloud.backupdr_v1.types.ListDataSourceReferencesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3277,22 +7857,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.DataSource", - "shortName": "get_data_source" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListDataSourceReferencesPager", + "shortName": "list_data_source_references" }, - "description": "Sample for GetDataSource", - "file": "backupdr_v1_generated_backup_dr_get_data_source_sync.py", + "description": "Sample for ListDataSourceReferences", + "file": "backupdr_v1_generated_backup_dr_list_data_source_references_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetDataSource_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListDataSourceReferences_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3312,12 +7892,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_data_source_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_data_source_references_sync.py" }, { "canonical": true, @@ -3327,22 +7907,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.get_management_server", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_data_sources", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetManagementServer", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListDataSources", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetManagementServer" + "shortName": "ListDataSources" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetManagementServerRequest" + "type": "google.cloud.backupdr_v1.types.ListDataSourcesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3358,22 +7938,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.ManagementServer", - "shortName": "get_management_server" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListDataSourcesAsyncPager", + "shortName": "list_data_sources" }, - "description": "Sample for GetManagementServer", - "file": "backupdr_v1_generated_backup_dr_get_management_server_async.py", + "description": "Sample for ListDataSources", + "file": "backupdr_v1_generated_backup_dr_list_data_sources_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetManagementServer_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListDataSources_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3393,12 +7973,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_management_server_async.py" + "title": "backupdr_v1_generated_backup_dr_list_data_sources_async.py" }, { "canonical": true, @@ -3407,22 +7987,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.get_management_server", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_data_sources", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.GetManagementServer", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListDataSources", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetManagementServer" + "shortName": "ListDataSources" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.GetManagementServerRequest" + "type": "google.cloud.backupdr_v1.types.ListDataSourcesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3438,22 +8018,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.types.ManagementServer", - "shortName": "get_management_server" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListDataSourcesPager", + "shortName": "list_data_sources" }, - "description": "Sample for GetManagementServer", - "file": "backupdr_v1_generated_backup_dr_get_management_server_sync.py", + "description": "Sample for ListDataSources", + "file": "backupdr_v1_generated_backup_dr_list_data_sources_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_GetManagementServer_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListDataSources_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3473,12 +8053,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_get_management_server_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_data_sources_sync.py" }, { "canonical": true, @@ -3488,19 +8068,23 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.initialize_service", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_management_servers", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.InitializeService", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListManagementServers", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "InitializeService" + "shortName": "ListManagementServers" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.InitializeServiceRequest" + "type": "google.cloud.backupdr_v1.types.ListManagementServersRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -3515,22 +8099,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "initialize_service" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListManagementServersAsyncPager", + "shortName": "list_management_servers" }, - "description": "Sample for InitializeService", - "file": "backupdr_v1_generated_backup_dr_initialize_service_async.py", + "description": "Sample for ListManagementServers", + "file": "backupdr_v1_generated_backup_dr_list_management_servers_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_InitializeService_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListManagementServers_async", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3540,22 +8124,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_initialize_service_async.py" + "title": "backupdr_v1_generated_backup_dr_list_management_servers_async.py" }, { "canonical": true, @@ -3564,19 +8148,23 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.initialize_service", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_management_servers", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.InitializeService", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListManagementServers", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "InitializeService" + "shortName": "ListManagementServers" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.InitializeServiceRequest" + "type": "google.cloud.backupdr_v1.types.ListManagementServersRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -3591,22 +8179,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "initialize_service" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListManagementServersPager", + "shortName": "list_management_servers" }, - "description": "Sample for InitializeService", - "file": "backupdr_v1_generated_backup_dr_initialize_service_sync.py", + "description": "Sample for ListManagementServers", + "file": "backupdr_v1_generated_backup_dr_list_management_servers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_InitializeService_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListManagementServers_sync", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3616,22 +8204,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_initialize_service_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_management_servers_sync.py" }, { "canonical": true, @@ -3641,19 +8229,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backup_plan_associations", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_restore_template_executions", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlanAssociations", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListRestoreTemplateExecutions", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlanAssociations" + "shortName": "ListRestoreTemplateExecutions" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupPlanAssociationsRequest" + "type": "google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsRequest" }, { "name": "parent", @@ -3672,14 +8260,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlanAssociationsAsyncPager", - "shortName": "list_backup_plan_associations" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListRestoreTemplateExecutionsAsyncPager", + "shortName": "list_restore_template_executions" }, - "description": "Sample for ListBackupPlanAssociations", - "file": "backupdr_v1_generated_backup_dr_list_backup_plan_associations_async.py", + "description": "Sample for ListRestoreTemplateExecutions", + "file": "backupdr_v1_generated_backup_dr_list_restore_template_executions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlanAssociations_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListRestoreTemplateExecutions_async", "segments": [ { "end": 52, @@ -3712,7 +8300,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backup_plan_associations_async.py" + "title": "backupdr_v1_generated_backup_dr_list_restore_template_executions_async.py" }, { "canonical": true, @@ -3721,19 +8309,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backup_plan_associations", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_restore_template_executions", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlanAssociations", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListRestoreTemplateExecutions", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlanAssociations" + "shortName": "ListRestoreTemplateExecutions" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupPlanAssociationsRequest" + "type": "google.cloud.backupdr_v1.types.ListRestoreTemplateExecutionsRequest" }, { "name": "parent", @@ -3752,14 +8340,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlanAssociationsPager", - "shortName": "list_backup_plan_associations" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListRestoreTemplateExecutionsPager", + "shortName": "list_restore_template_executions" }, - "description": "Sample for ListBackupPlanAssociations", - "file": "backupdr_v1_generated_backup_dr_list_backup_plan_associations_sync.py", + "description": "Sample for ListRestoreTemplateExecutions", + "file": "backupdr_v1_generated_backup_dr_list_restore_template_executions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlanAssociations_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListRestoreTemplateExecutions_sync", "segments": [ { "end": 52, @@ -3792,7 +8380,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backup_plan_associations_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_restore_template_executions_sync.py" }, { "canonical": true, @@ -3802,19 +8390,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backup_plan_revisions", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_restore_templates", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlanRevisions", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListRestoreTemplates", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlanRevisions" + "shortName": "ListRestoreTemplates" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupPlanRevisionsRequest" + "type": "google.cloud.backupdr_v1.types.ListRestoreTemplatesRequest" }, { "name": "parent", @@ -3833,14 +8421,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlanRevisionsAsyncPager", - "shortName": "list_backup_plan_revisions" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListRestoreTemplatesAsyncPager", + "shortName": "list_restore_templates" }, - "description": "Sample for ListBackupPlanRevisions", - "file": "backupdr_v1_generated_backup_dr_list_backup_plan_revisions_async.py", + "description": "Sample for ListRestoreTemplates", + "file": "backupdr_v1_generated_backup_dr_list_restore_templates_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlanRevisions_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListRestoreTemplates_async", "segments": [ { "end": 52, @@ -3873,7 +8461,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backup_plan_revisions_async.py" + "title": "backupdr_v1_generated_backup_dr_list_restore_templates_async.py" }, { "canonical": true, @@ -3882,19 +8470,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backup_plan_revisions", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_restore_templates", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlanRevisions", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListRestoreTemplates", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlanRevisions" + "shortName": "ListRestoreTemplates" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupPlanRevisionsRequest" + "type": "google.cloud.backupdr_v1.types.ListRestoreTemplatesRequest" }, { "name": "parent", @@ -3913,14 +8501,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlanRevisionsPager", - "shortName": "list_backup_plan_revisions" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListRestoreTemplatesPager", + "shortName": "list_restore_templates" }, - "description": "Sample for ListBackupPlanRevisions", - "file": "backupdr_v1_generated_backup_dr_list_backup_plan_revisions_sync.py", + "description": "Sample for ListRestoreTemplates", + "file": "backupdr_v1_generated_backup_dr_list_restore_templates_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlanRevisions_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListRestoreTemplates_sync", "segments": [ { "end": 52, @@ -3953,7 +8541,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backup_plan_revisions_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_restore_templates_sync.py" }, { "canonical": true, @@ -3963,19 +8551,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backup_plans", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_restore_verification_plan_associations", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlans", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListRestoreVerificationPlanAssociations", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlans" + "shortName": "ListRestoreVerificationPlanAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupPlansRequest" + "type": "google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsRequest" }, { "name": "parent", @@ -3994,14 +8582,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlansAsyncPager", - "shortName": "list_backup_plans" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListRestoreVerificationPlanAssociationsAsyncPager", + "shortName": "list_restore_verification_plan_associations" }, - "description": "Sample for ListBackupPlans", - "file": "backupdr_v1_generated_backup_dr_list_backup_plans_async.py", + "description": "Sample for ListRestoreVerificationPlanAssociations", + "file": "backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlans_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListRestoreVerificationPlanAssociations_async", "segments": [ { "end": 52, @@ -4034,7 +8622,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backup_plans_async.py" + "title": "backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_async.py" }, { "canonical": true, @@ -4043,19 +8631,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backup_plans", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_restore_verification_plan_associations", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupPlans", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListRestoreVerificationPlanAssociations", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlans" + "shortName": "ListRestoreVerificationPlanAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupPlansRequest" + "type": "google.cloud.backupdr_v1.types.ListRestoreVerificationPlanAssociationsRequest" }, { "name": "parent", @@ -4074,14 +8662,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupPlansPager", - "shortName": "list_backup_plans" - }, - "description": "Sample for ListBackupPlans", - "file": "backupdr_v1_generated_backup_dr_list_backup_plans_sync.py", + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListRestoreVerificationPlanAssociationsPager", + "shortName": "list_restore_verification_plan_associations" + }, + "description": "Sample for ListRestoreVerificationPlanAssociations", + "file": "backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackupPlans_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListRestoreVerificationPlanAssociations_sync", "segments": [ { "end": 52, @@ -4114,7 +8702,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backup_plans_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_restore_verification_plan_associations_sync.py" }, { "canonical": true, @@ -4124,19 +8712,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backup_vaults", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_restore_verification_plans", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupVaults", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListRestoreVerificationPlans", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupVaults" + "shortName": "ListRestoreVerificationPlans" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupVaultsRequest" + "type": "google.cloud.backupdr_v1.types.ListRestoreVerificationPlansRequest" }, { "name": "parent", @@ -4155,14 +8743,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupVaultsAsyncPager", - "shortName": "list_backup_vaults" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListRestoreVerificationPlansAsyncPager", + "shortName": "list_restore_verification_plans" }, - "description": "Sample for ListBackupVaults", - "file": "backupdr_v1_generated_backup_dr_list_backup_vaults_async.py", + "description": "Sample for ListRestoreVerificationPlans", + "file": "backupdr_v1_generated_backup_dr_list_restore_verification_plans_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackupVaults_async", + "regionTag": "backupdr_v1_generated_BackupDR_ListRestoreVerificationPlans_async", "segments": [ { "end": 52, @@ -4195,7 +8783,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backup_vaults_async.py" + "title": "backupdr_v1_generated_backup_dr_list_restore_verification_plans_async.py" }, { "canonical": true, @@ -4204,19 +8792,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backup_vaults", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_restore_verification_plans", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackupVaults", + "fullName": "google.cloud.backupdr.v1.BackupDR.ListRestoreVerificationPlans", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupVaults" + "shortName": "ListRestoreVerificationPlans" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupVaultsRequest" + "type": "google.cloud.backupdr_v1.types.ListRestoreVerificationPlansRequest" }, { "name": "parent", @@ -4235,14 +8823,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupVaultsPager", - "shortName": "list_backup_vaults" + "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListRestoreVerificationPlansPager", + "shortName": "list_restore_verification_plans" }, - "description": "Sample for ListBackupVaults", - "file": "backupdr_v1_generated_backup_dr_list_backup_vaults_sync.py", + "description": "Sample for ListRestoreVerificationPlans", + "file": "backupdr_v1_generated_backup_dr_list_restore_verification_plans_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackupVaults_sync", + "regionTag": "backupdr_v1_generated_BackupDR_ListRestoreVerificationPlans_sync", "segments": [ { "end": 52, @@ -4275,7 +8863,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backup_vaults_sync.py" + "title": "backupdr_v1_generated_backup_dr_list_restore_verification_plans_sync.py" }, { "canonical": true, @@ -4285,22 +8873,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_backups", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.restore_backup", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackups", + "fullName": "google.cloud.backupdr.v1.BackupDR.RestoreBackup", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackups" + "shortName": "RestoreBackup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupsRequest" + "type": "google.cloud.backupdr_v1.types.RestoreBackupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -4316,22 +8904,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupsAsyncPager", - "shortName": "list_backups" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "restore_backup" }, - "description": "Sample for ListBackups", - "file": "backupdr_v1_generated_backup_dr_list_backups_async.py", + "description": "Sample for RestoreBackup", + "file": "backupdr_v1_generated_backup_dr_restore_backup_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackups_async", + "regionTag": "backupdr_v1_generated_BackupDR_RestoreBackup_async", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -4341,22 +8929,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backups_async.py" + "title": "backupdr_v1_generated_backup_dr_restore_backup_async.py" }, { "canonical": true, @@ -4365,22 +8953,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_backups", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.restore_backup", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListBackups", + "fullName": "google.cloud.backupdr.v1.BackupDR.RestoreBackup", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackups" + "shortName": "RestoreBackup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListBackupsRequest" + "type": "google.cloud.backupdr_v1.types.RestoreBackupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -4396,22 +8984,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListBackupsPager", - "shortName": "list_backups" + "resultType": "google.api_core.operation.Operation", + "shortName": "restore_backup" }, - "description": "Sample for ListBackups", - "file": "backupdr_v1_generated_backup_dr_list_backups_sync.py", + "description": "Sample for RestoreBackup", + "file": "backupdr_v1_generated_backup_dr_restore_backup_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListBackups_sync", + "regionTag": "backupdr_v1_generated_BackupDR_RestoreBackup_sync", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -4421,22 +9009,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_backups_sync.py" + "title": "backupdr_v1_generated_backup_dr_restore_backup_sync.py" }, { "canonical": true, @@ -4446,22 +9034,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_data_source_references", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.run_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListDataSourceReferences", + "fullName": "google.cloud.backupdr.v1.BackupDR.RunRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListDataSourceReferences" + "shortName": "RunRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListDataSourceReferencesRequest" + "type": "google.cloud.backupdr_v1.types.RunRestoreTemplateRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -4477,22 +9065,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListDataSourceReferencesAsyncPager", - "shortName": "list_data_source_references" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "run_restore_template" }, - "description": "Sample for ListDataSourceReferences", - "file": "backupdr_v1_generated_backup_dr_list_data_source_references_async.py", + "description": "Sample for RunRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_run_restore_template_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListDataSourceReferences_async", + "regionTag": "backupdr_v1_generated_BackupDR_RunRestoreTemplate_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -4507,17 +9095,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_data_source_references_async.py" + "title": "backupdr_v1_generated_backup_dr_run_restore_template_async.py" }, { "canonical": true, @@ -4526,22 +9114,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_data_source_references", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.run_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListDataSourceReferences", + "fullName": "google.cloud.backupdr.v1.BackupDR.RunRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListDataSourceReferences" + "shortName": "RunRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListDataSourceReferencesRequest" + "type": "google.cloud.backupdr_v1.types.RunRestoreTemplateRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -4557,22 +9145,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListDataSourceReferencesPager", - "shortName": "list_data_source_references" + "resultType": "google.api_core.operation.Operation", + "shortName": "run_restore_template" }, - "description": "Sample for ListDataSourceReferences", - "file": "backupdr_v1_generated_backup_dr_list_data_source_references_sync.py", + "description": "Sample for RunRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_run_restore_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListDataSourceReferences_sync", + "regionTag": "backupdr_v1_generated_BackupDR_RunRestoreTemplate_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -4587,17 +9175,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_data_source_references_sync.py" + "title": "backupdr_v1_generated_backup_dr_run_restore_template_sync.py" }, { "canonical": true, @@ -4607,22 +9195,26 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_data_sources", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.trigger_backup", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListDataSources", + "fullName": "google.cloud.backupdr.v1.BackupDR.TriggerBackup", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListDataSources" + "shortName": "TriggerBackup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListDataSourcesRequest" + "type": "google.cloud.backupdr_v1.types.TriggerBackupRequest" }, { - "name": "parent", + "name": "name", + "type": "str" + }, + { + "name": "rule_id", "type": "str" }, { @@ -4638,22 +9230,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListDataSourcesAsyncPager", - "shortName": "list_data_sources" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "trigger_backup" }, - "description": "Sample for ListDataSources", - "file": "backupdr_v1_generated_backup_dr_list_data_sources_async.py", + "description": "Sample for TriggerBackup", + "file": "backupdr_v1_generated_backup_dr_trigger_backup_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListDataSources_async", + "regionTag": "backupdr_v1_generated_BackupDR_TriggerBackup_async", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -4663,22 +9255,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": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_data_sources_async.py" + "title": "backupdr_v1_generated_backup_dr_trigger_backup_async.py" }, { "canonical": true, @@ -4687,22 +9279,26 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_data_sources", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.trigger_backup", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListDataSources", + "fullName": "google.cloud.backupdr.v1.BackupDR.TriggerBackup", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListDataSources" + "shortName": "TriggerBackup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListDataSourcesRequest" + "type": "google.cloud.backupdr_v1.types.TriggerBackupRequest" }, { - "name": "parent", + "name": "name", + "type": "str" + }, + { + "name": "rule_id", "type": "str" }, { @@ -4718,22 +9314,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListDataSourcesPager", - "shortName": "list_data_sources" + "resultType": "google.api_core.operation.Operation", + "shortName": "trigger_backup" }, - "description": "Sample for ListDataSources", - "file": "backupdr_v1_generated_backup_dr_list_data_sources_sync.py", + "description": "Sample for TriggerBackup", + "file": "backupdr_v1_generated_backup_dr_trigger_backup_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListDataSources_sync", + "regionTag": "backupdr_v1_generated_BackupDR_TriggerBackup_sync", "segments": [ { - "end": 52, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 56, "start": 27, "type": "SHORT" }, @@ -4743,22 +9339,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": 53, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_data_sources_sync.py" + "title": "backupdr_v1_generated_backup_dr_trigger_backup_sync.py" }, { "canonical": true, @@ -4768,22 +9364,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.list_management_servers", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.trigger_restore_cleanup", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListManagementServers", + "fullName": "google.cloud.backupdr.v1.BackupDR.TriggerRestoreCleanup", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListManagementServers" + "shortName": "TriggerRestoreCleanup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListManagementServersRequest" + "type": "google.cloud.backupdr_v1.types.TriggerRestoreCleanupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -4799,22 +9395,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListManagementServersAsyncPager", - "shortName": "list_management_servers" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "trigger_restore_cleanup" }, - "description": "Sample for ListManagementServers", - "file": "backupdr_v1_generated_backup_dr_list_management_servers_async.py", + "description": "Sample for TriggerRestoreCleanup", + "file": "backupdr_v1_generated_backup_dr_trigger_restore_cleanup_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListManagementServers_async", + "regionTag": "backupdr_v1_generated_BackupDR_TriggerRestoreCleanup_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -4829,17 +9425,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_management_servers_async.py" + "title": "backupdr_v1_generated_backup_dr_trigger_restore_cleanup_async.py" }, { "canonical": true, @@ -4848,22 +9444,22 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.list_management_servers", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.trigger_restore_cleanup", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.ListManagementServers", + "fullName": "google.cloud.backupdr.v1.BackupDR.TriggerRestoreCleanup", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListManagementServers" + "shortName": "TriggerRestoreCleanup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.ListManagementServersRequest" + "type": "google.cloud.backupdr_v1.types.TriggerRestoreCleanupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -4879,22 +9475,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1.services.backup_dr.pagers.ListManagementServersPager", - "shortName": "list_management_servers" + "resultType": "google.api_core.operation.Operation", + "shortName": "trigger_restore_cleanup" }, - "description": "Sample for ListManagementServers", - "file": "backupdr_v1_generated_backup_dr_list_management_servers_sync.py", + "description": "Sample for TriggerRestoreCleanup", + "file": "backupdr_v1_generated_backup_dr_trigger_restore_cleanup_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_ListManagementServers_sync", + "regionTag": "backupdr_v1_generated_BackupDR_TriggerRestoreCleanup_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -4909,17 +9505,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_list_management_servers_sync.py" + "title": "backupdr_v1_generated_backup_dr_trigger_restore_cleanup_sync.py" }, { "canonical": true, @@ -4929,19 +9525,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.restore_backup", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.trigger_restore_verification", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.RestoreBackup", + "fullName": "google.cloud.backupdr.v1.BackupDR.TriggerRestoreVerification", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "RestoreBackup" + "shortName": "TriggerRestoreVerification" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.RestoreBackupRequest" + "type": "google.cloud.backupdr_v1.types.TriggerRestoreVerificationRequest" }, { "name": "name", @@ -4961,21 +9557,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "restore_backup" + "shortName": "trigger_restore_verification" }, - "description": "Sample for RestoreBackup", - "file": "backupdr_v1_generated_backup_dr_restore_backup_async.py", + "description": "Sample for TriggerRestoreVerification", + "file": "backupdr_v1_generated_backup_dr_trigger_restore_verification_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_RestoreBackup_async", + "regionTag": "backupdr_v1_generated_BackupDR_TriggerRestoreVerification_async", "segments": [ { - "end": 60, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 55, "start": 27, "type": "SHORT" }, @@ -4985,22 +9581,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_restore_backup_async.py" + "title": "backupdr_v1_generated_backup_dr_trigger_restore_verification_async.py" }, { "canonical": true, @@ -5009,19 +9605,19 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.restore_backup", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.trigger_restore_verification", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.RestoreBackup", + "fullName": "google.cloud.backupdr.v1.BackupDR.TriggerRestoreVerification", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "RestoreBackup" + "shortName": "TriggerRestoreVerification" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.RestoreBackupRequest" + "type": "google.cloud.backupdr_v1.types.TriggerRestoreVerificationRequest" }, { "name": "name", @@ -5041,21 +9637,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "restore_backup" + "shortName": "trigger_restore_verification" }, - "description": "Sample for RestoreBackup", - "file": "backupdr_v1_generated_backup_dr_restore_backup_sync.py", + "description": "Sample for TriggerRestoreVerification", + "file": "backupdr_v1_generated_backup_dr_trigger_restore_verification_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_RestoreBackup_sync", + "regionTag": "backupdr_v1_generated_BackupDR_TriggerRestoreVerification_sync", "segments": [ { - "end": 60, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 55, "start": 27, "type": "SHORT" }, @@ -5065,22 +9661,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_restore_backup_sync.py" + "title": "backupdr_v1_generated_backup_dr_trigger_restore_verification_sync.py" }, { "canonical": true, @@ -5090,27 +9686,27 @@ "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.trigger_backup", + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.update_auto_protection_policy", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.TriggerBackup", + "fullName": "google.cloud.backupdr.v1.BackupDR.UpdateAutoProtectionPolicy", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "TriggerBackup" + "shortName": "UpdateAutoProtectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.TriggerBackupRequest" + "type": "google.cloud.backupdr_v1.types.UpdateAutoProtectionPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "auto_protection_policy", + "type": "google.cloud.backupdr_v1.types.AutoProtectionPolicy" }, { - "name": "rule_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -5126,21 +9722,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "trigger_backup" + "shortName": "update_auto_protection_policy" }, - "description": "Sample for TriggerBackup", - "file": "backupdr_v1_generated_backup_dr_trigger_backup_async.py", + "description": "Sample for UpdateAutoProtectionPolicy", + "file": "backupdr_v1_generated_backup_dr_update_auto_protection_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_TriggerBackup_async", + "regionTag": "backupdr_v1_generated_BackupDR_UpdateAutoProtectionPolicy_async", "segments": [ { - "end": 56, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 61, "start": 27, "type": "SHORT" }, @@ -5150,22 +9746,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_trigger_backup_async.py" + "title": "backupdr_v1_generated_backup_dr_update_auto_protection_policy_async.py" }, { "canonical": true, @@ -5174,27 +9770,27 @@ "fullName": "google.cloud.backupdr_v1.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1.BackupDRClient.trigger_backup", + "fullName": "google.cloud.backupdr_v1.BackupDRClient.update_auto_protection_policy", "method": { - "fullName": "google.cloud.backupdr.v1.BackupDR.TriggerBackup", + "fullName": "google.cloud.backupdr.v1.BackupDR.UpdateAutoProtectionPolicy", "service": { "fullName": "google.cloud.backupdr.v1.BackupDR", "shortName": "BackupDR" }, - "shortName": "TriggerBackup" + "shortName": "UpdateAutoProtectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1.types.TriggerBackupRequest" + "type": "google.cloud.backupdr_v1.types.UpdateAutoProtectionPolicyRequest" }, { - "name": "name", - "type": "str" + "name": "auto_protection_policy", + "type": "google.cloud.backupdr_v1.types.AutoProtectionPolicy" }, { - "name": "rule_id", - "type": "str" + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" }, { "name": "retry", @@ -5210,21 +9806,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "trigger_backup" + "shortName": "update_auto_protection_policy" }, - "description": "Sample for TriggerBackup", - "file": "backupdr_v1_generated_backup_dr_trigger_backup_sync.py", + "description": "Sample for UpdateAutoProtectionPolicy", + "file": "backupdr_v1_generated_backup_dr_update_auto_protection_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1_generated_BackupDR_TriggerBackup_sync", + "regionTag": "backupdr_v1_generated_BackupDR_UpdateAutoProtectionPolicy_sync", "segments": [ { - "end": 56, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 61, "start": 27, "type": "SHORT" }, @@ -5234,22 +9830,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 47, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1_generated_backup_dr_trigger_backup_sync.py" + "title": "backupdr_v1_generated_backup_dr_update_auto_protection_policy_sync.py" }, { "canonical": true, @@ -6096,6 +10692,175 @@ ], "title": "backupdr_v1_generated_backup_dr_update_data_source_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRAsyncClient.update_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.UpdateRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.UpdateRestoreTemplateRequest" + }, + { + "name": "restore_template", + "type": "google.cloud.backupdr_v1.types.RestoreTemplate" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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": "update_restore_template" + }, + "description": "Sample for UpdateRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_update_restore_template_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_UpdateRestoreTemplate_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_update_restore_template_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1.BackupDRClient.update_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1.BackupDR.UpdateRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1.types.UpdateRestoreTemplateRequest" + }, + { + "name": "restore_template", + "type": "google.cloud.backupdr_v1.types.RestoreTemplate" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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": "update_restore_template" + }, + "description": "Sample for UpdateRestoreTemplate", + "file": "backupdr_v1_generated_backup_dr_update_restore_template_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1_generated_BackupDR_UpdateRestoreTemplate_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1_generated_backup_dr_update_restore_template_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1beta.json b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1beta.json index fde1e8488700..c40b0795baca 100644 --- a/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1beta.json +++ b/packages/google-cloud-backupdr/samples/generated_samples/snippet_metadata_google.cloud.backupdr.v1beta.json @@ -1081,22 +1081,30 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_auto_protection_policy", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.create_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteAutoProtectionPolicy", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteAutoProtectionPolicy" + "shortName": "CreateRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteAutoProtectionPolicyRequest" + "type": "google.cloud.backupdr_v1beta.types.CreateRestoreTemplateRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "restore_template", + "type": "google.cloud.backupdr_v1beta.types.RestoreTemplate" + }, + { + "name": "restore_template_id", "type": "str" }, { @@ -1113,21 +1121,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_auto_protection_policy" + "shortName": "create_restore_template" }, - "description": "Sample for DeleteAutoProtectionPolicy", - "file": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_async.py", + "description": "Sample for CreateRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_create_restore_template_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateRestoreTemplate_async", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -1137,22 +1145,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_async.py" + "title": "backupdr_v1beta_generated_backup_dr_create_restore_template_async.py" }, { "canonical": true, @@ -1161,22 +1169,30 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_auto_protection_policy", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.create_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteAutoProtectionPolicy", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteAutoProtectionPolicy" + "shortName": "CreateRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteAutoProtectionPolicyRequest" + "type": "google.cloud.backupdr_v1beta.types.CreateRestoreTemplateRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "restore_template", + "type": "google.cloud.backupdr_v1beta.types.RestoreTemplate" + }, + { + "name": "restore_template_id", "type": "str" }, { @@ -1193,21 +1209,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_auto_protection_policy" + "shortName": "create_restore_template" }, - "description": "Sample for DeleteAutoProtectionPolicy", - "file": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_sync.py", + "description": "Sample for CreateRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_create_restore_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateRestoreTemplate_sync", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -1217,22 +1233,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_create_restore_template_sync.py" }, { "canonical": true, @@ -1242,22 +1258,30 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup_plan_association", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.create_restore_verification_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateRestoreVerificationPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupPlanAssociation" + "shortName": "CreateRestoreVerificationPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1beta.types.CreateRestoreVerificationPlanAssociationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "restore_verification_plan_association", + "type": "google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation" + }, + { + "name": "restore_verification_plan_association_id", "type": "str" }, { @@ -1274,21 +1298,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_backup_plan_association" + "shortName": "create_restore_verification_plan_association" }, - "description": "Sample for DeleteBackupPlanAssociation", - "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_async.py", + "description": "Sample for CreateRestoreVerificationPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlanAssociation_async", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -1298,22 +1322,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_async.py" + "title": "backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_async.py" }, { "canonical": true, @@ -1322,22 +1346,30 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan_association", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.create_restore_verification_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateRestoreVerificationPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupPlanAssociation" + "shortName": "CreateRestoreVerificationPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1beta.types.CreateRestoreVerificationPlanAssociationRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "restore_verification_plan_association", + "type": "google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation" + }, + { + "name": "restore_verification_plan_association_id", "type": "str" }, { @@ -1354,21 +1386,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_backup_plan_association" + "shortName": "create_restore_verification_plan_association" }, - "description": "Sample for DeleteBackupPlanAssociation", - "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_sync.py", + "description": "Sample for CreateRestoreVerificationPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlanAssociation_sync", "segments": [ { - "end": 55, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 61, "start": 27, "type": "SHORT" }, @@ -1378,22 +1410,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_association_sync.py" }, { "canonical": true, @@ -1403,22 +1435,30 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup_plan", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.create_restore_verification_plan", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlan", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateRestoreVerificationPlan", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupPlan" + "shortName": "CreateRestoreVerificationPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanRequest" + "type": "google.cloud.backupdr_v1beta.types.CreateRestoreVerificationPlanRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "restore_verification_plan", + "type": "google.cloud.backupdr_v1beta.types.RestoreVerificationPlan" + }, + { + "name": "restore_verification_plan_id", "type": "str" }, { @@ -1435,21 +1475,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_backup_plan" + "shortName": "create_restore_verification_plan" }, - "description": "Sample for DeleteBackupPlan", - "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_async.py", + "description": "Sample for CreateRestoreVerificationPlan", + "file": "backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlan_async", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -1459,22 +1499,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_async.py" + "title": "backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_async.py" }, { "canonical": true, @@ -1483,22 +1523,30 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.create_restore_verification_plan", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlan", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.CreateRestoreVerificationPlan", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupPlan" + "shortName": "CreateRestoreVerificationPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanRequest" + "type": "google.cloud.backupdr_v1beta.types.CreateRestoreVerificationPlanRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "restore_verification_plan", + "type": "google.cloud.backupdr_v1beta.types.RestoreVerificationPlan" + }, + { + "name": "restore_verification_plan_id", "type": "str" }, { @@ -1515,21 +1563,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_backup_plan" + "shortName": "create_restore_verification_plan" }, - "description": "Sample for DeleteBackupPlan", - "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_sync.py", + "description": "Sample for CreateRestoreVerificationPlan", + "file": "backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_CreateRestoreVerificationPlan_sync", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -1539,22 +1587,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_create_restore_verification_plan_sync.py" }, { "canonical": true, @@ -1564,19 +1612,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup_vault", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_auto_protection_policy", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupVault", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteAutoProtectionPolicy", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupVault" + "shortName": "DeleteAutoProtectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteBackupVaultRequest" + "type": "google.cloud.backupdr_v1beta.types.DeleteAutoProtectionPolicyRequest" }, { "name": "name", @@ -1596,13 +1644,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_backup_vault" + "shortName": "delete_auto_protection_policy" }, - "description": "Sample for DeleteBackupVault", - "file": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_async.py", + "description": "Sample for DeleteAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupVault_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_async", "segments": [ { "end": 55, @@ -1635,7 +1683,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_async.py" + "title": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_async.py" }, { "canonical": true, @@ -1644,19 +1692,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_vault", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_auto_protection_policy", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupVault", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteAutoProtectionPolicy", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackupVault" + "shortName": "DeleteAutoProtectionPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteBackupVaultRequest" + "type": "google.cloud.backupdr_v1beta.types.DeleteAutoProtectionPolicyRequest" }, { "name": "name", @@ -1676,13 +1724,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_backup_vault" + "shortName": "delete_auto_protection_policy" }, - "description": "Sample for DeleteBackupVault", - "file": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_sync.py", + "description": "Sample for DeleteAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupVault_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteAutoProtectionPolicy_sync", "segments": [ { "end": 55, @@ -1715,7 +1763,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_delete_auto_protection_policy_sync.py" }, { "canonical": true, @@ -1725,19 +1773,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackup", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackup" + "shortName": "DeleteBackupPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteBackupRequest" + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanAssociationRequest" }, { "name": "name", @@ -1757,13 +1805,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_backup" + "shortName": "delete_backup_plan_association" }, - "description": "Sample for DeleteBackup", - "file": "backupdr_v1beta_generated_backup_dr_delete_backup_async.py", + "description": "Sample for DeleteBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackup_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_async", "segments": [ { "end": 55, @@ -1796,7 +1844,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_backup_async.py" + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_async.py" }, { "canonical": true, @@ -1805,19 +1853,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackup", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteBackup" + "shortName": "DeleteBackupPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteBackupRequest" + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanAssociationRequest" }, { "name": "name", @@ -1837,13 +1885,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_backup" + "shortName": "delete_backup_plan_association" }, - "description": "Sample for DeleteBackup", - "file": "backupdr_v1beta_generated_backup_dr_delete_backup_sync.py", + "description": "Sample for DeleteBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackup_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlanAssociation_sync", "segments": [ { "end": 55, @@ -1876,7 +1924,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_backup_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_association_sync.py" }, { "canonical": true, @@ -1886,19 +1934,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_management_server", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup_plan", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteManagementServer", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlan", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteManagementServer" + "shortName": "DeleteBackupPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest" + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanRequest" }, { "name": "name", @@ -1918,13 +1966,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_management_server" + "shortName": "delete_backup_plan" }, - "description": "Sample for DeleteManagementServer", - "file": "backupdr_v1beta_generated_backup_dr_delete_management_server_async.py", + "description": "Sample for DeleteBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteManagementServer_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_async", "segments": [ { "end": 55, @@ -1957,7 +2005,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_management_server_async.py" + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_async.py" }, { "canonical": true, @@ -1966,19 +2014,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_management_server", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_plan", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteManagementServer", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupPlan", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "DeleteManagementServer" + "shortName": "DeleteBackupPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest" + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupPlanRequest" }, { "name": "name", @@ -1998,13 +2046,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_management_server" + "shortName": "delete_backup_plan" }, - "description": "Sample for DeleteManagementServer", - "file": "backupdr_v1beta_generated_backup_dr_delete_management_server_sync.py", + "description": "Sample for DeleteBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteManagementServer_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupPlan_sync", "segments": [ { "end": 55, @@ -2037,7 +2085,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_delete_management_server_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_plan_sync.py" }, { "canonical": true, @@ -2047,26 +2095,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_backup_plan_associations_for_resource_type", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup_vault", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupPlanAssociationsForResourceType", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupVault", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchBackupPlanAssociationsForResourceType" + "shortName": "DeleteBackupVault" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupVaultRequest" }, { - "name": "resource_type", + "name": "name", "type": "str" }, { @@ -2082,22 +2126,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager", - "shortName": "fetch_backup_plan_associations_for_resource_type" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_backup_vault" }, - "description": "Sample for FetchBackupPlanAssociationsForResourceType", - "file": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py", + "description": "Sample for DeleteBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupVault_async", "segments": [ { - "end": 53, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 55, "start": 27, "type": "SHORT" }, @@ -2107,22 +2151,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py" + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_async.py" }, { "canonical": true, @@ -2131,26 +2175,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_backup_plan_associations_for_resource_type", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup_vault", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupPlanAssociationsForResourceType", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackupVault", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchBackupPlanAssociationsForResourceType" + "shortName": "DeleteBackupVault" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupVaultRequest" }, { - "name": "resource_type", + "name": "name", "type": "str" }, { @@ -2166,22 +2206,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypePager", - "shortName": "fetch_backup_plan_associations_for_resource_type" + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_backup_vault" }, - "description": "Sample for FetchBackupPlanAssociationsForResourceType", - "file": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py", + "description": "Sample for DeleteBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteBackupVault_sync", "segments": [ { - "end": 53, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 55, "start": 27, "type": "SHORT" }, @@ -2191,22 +2231,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 50, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_delete_backup_vault_sync.py" }, { "canonical": true, @@ -2216,26 +2256,2783 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_backups_for_resource_type", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_backup", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupsForResourceType", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackup", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchBackupsForResourceType" + "shortName": "DeleteBackup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest" + "type": "google.cloud.backupdr_v1beta.types.DeleteBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" }, { - "name": "parent", - "type": "str" + "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": "backupdr_v1beta_generated_backup_dr_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_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": "backupdr_v1beta_generated_backup_dr_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_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": "backupdr_v1beta_generated_backup_dr_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_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": "backupdr_v1beta_generated_backup_dr_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest" + }, + { + "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_management_server" + }, + "description": "Sample for DeleteManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_delete_management_server_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteManagementServer_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": "backupdr_v1beta_generated_backup_dr_delete_management_server_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_management_server", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteManagementServer", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteManagementServer" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteManagementServerRequest" + }, + { + "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_management_server" + }, + "description": "Sample for DeleteManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_delete_management_server_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteManagementServer_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": "backupdr_v1beta_generated_backup_dr_delete_management_server_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteRestoreTemplateRequest" + }, + { + "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_restore_template" + }, + "description": "Sample for DeleteRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_delete_restore_template_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteRestoreTemplate_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": "backupdr_v1beta_generated_backup_dr_delete_restore_template_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteRestoreTemplateRequest" + }, + { + "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_restore_template" + }, + "description": "Sample for DeleteRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_delete_restore_template_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteRestoreTemplate_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": "backupdr_v1beta_generated_backup_dr_delete_restore_template_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_restore_verification_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteRestoreVerificationPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreVerificationPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteRestoreVerificationPlanAssociationRequest" + }, + { + "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_restore_verification_plan_association" + }, + "description": "Sample for DeleteRestoreVerificationPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_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": "backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_restore_verification_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteRestoreVerificationPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreVerificationPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteRestoreVerificationPlanAssociationRequest" + }, + { + "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_restore_verification_plan_association" + }, + "description": "Sample for DeleteRestoreVerificationPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlanAssociation_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": "backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.delete_restore_verification_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteRestoreVerificationPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreVerificationPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteRestoreVerificationPlanRequest" + }, + { + "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_restore_verification_plan" + }, + "description": "Sample for DeleteRestoreVerificationPlan", + "file": "backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlan_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": "backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.delete_restore_verification_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.DeleteRestoreVerificationPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "DeleteRestoreVerificationPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.DeleteRestoreVerificationPlanRequest" + }, + { + "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_restore_verification_plan" + }, + "description": "Sample for DeleteRestoreVerificationPlan", + "file": "backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_DeleteRestoreVerificationPlan_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": "backupdr_v1beta_generated_backup_dr_delete_restore_verification_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_backup_plan_associations_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupPlanAssociationsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupPlanAssociationsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1beta.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager", + "shortName": "fetch_backup_plan_associations_for_resource_type" + }, + "description": "Sample for FetchBackupPlanAssociationsForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_backup_plan_associations_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupPlanAssociationsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupPlanAssociationsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchBackupPlanAssociationsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1beta.services.backup_dr.pagers.FetchBackupPlanAssociationsForResourceTypePager", + "shortName": "fetch_backup_plan_associations_for_resource_type" + }, + "description": "Sample for FetchBackupPlanAssociationsForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupPlanAssociationsForResourceType_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": "backupdr_v1beta_generated_backup_dr_fetch_backup_plan_associations_for_resource_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_backups_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1beta.services.backup_dr.pagers.FetchBackupsForResourceTypeAsyncPager", + "shortName": "fetch_backups_for_resource_type" + }, + "description": "Sample for FetchBackupsForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_backups_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupsForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchBackupsForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1beta.services.backup_dr.pagers.FetchBackupsForResourceTypePager", + "shortName": "fetch_backups_for_resource_type" + }, + "description": "Sample for FetchBackupsForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_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": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_data_source_references_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchDataSourceReferencesForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchDataSourceReferencesForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1beta.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypeAsyncPager", + "shortName": "fetch_data_source_references_for_resource_type" + }, + "description": "Sample for FetchDataSourceReferencesForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_data_source_references_for_resource_type", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchDataSourceReferencesForResourceType", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchDataSourceReferencesForResourceType" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "resource_type", + "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.backupdr_v1beta.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypePager", + "shortName": "fetch_data_source_references_for_resource_type" + }, + "description": "Sample for FetchDataSourceReferencesForResourceType", + "file": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_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": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_usable_backup_vaults", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchUsableBackupVaults", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchUsableBackupVaults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest" + }, + { + "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.backupdr_v1beta.services.backup_dr.pagers.FetchUsableBackupVaultsAsyncPager", + "shortName": "fetch_usable_backup_vaults" + }, + "description": "Sample for FetchUsableBackupVaults", + "file": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_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": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_usable_backup_vaults", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchUsableBackupVaults", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "FetchUsableBackupVaults" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest" + }, + { + "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.backupdr_v1beta.services.backup_dr.pagers.FetchUsableBackupVaultsPager", + "shortName": "fetch_usable_backup_vaults" + }, + "description": "Sample for FetchUsableBackupVaults", + "file": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_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": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyBindingRequest" + }, + { + "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.backupdr_v1beta.types.AutoProtectionPolicyBinding", + "shortName": "get_auto_protection_policy_binding" + }, + "description": "Sample for GetAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_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": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy_binding", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicyBinding", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicyBinding" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyBindingRequest" + }, + { + "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.backupdr_v1beta.types.AutoProtectionPolicyBinding", + "shortName": "get_auto_protection_policy_binding" + }, + "description": "Sample for GetAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_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": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyRequest" + }, + { + "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.backupdr_v1beta.types.AutoProtectionPolicy", + "shortName": "get_auto_protection_policy" + }, + "description": "Sample for GetAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_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": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicy", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetAutoProtectionPolicy" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyRequest" + }, + { + "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.backupdr_v1beta.types.AutoProtectionPolicy", + "shortName": "get_auto_protection_policy" + }, + "description": "Sample for GetAutoProtectionPolicy", + "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_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": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanAssociationRequest" + }, + { + "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.backupdr_v1beta.types.BackupPlanAssociation", + "shortName": "get_backup_plan_association" + }, + "description": "Sample for GetBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_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": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_association", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanAssociation", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanAssociationRequest" + }, + { + "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.backupdr_v1beta.types.BackupPlanAssociation", + "shortName": "get_backup_plan_association" + }, + "description": "Sample for GetBackupPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_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": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_plan_revision", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanRevision", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRevisionRequest" + }, + { + "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.backupdr_v1beta.types.BackupPlanRevision", + "shortName": "get_backup_plan_revision" + }, + "description": "Sample for GetBackupPlanRevision", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_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": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_revision", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanRevision", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlanRevision" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRevisionRequest" + }, + { + "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.backupdr_v1beta.types.BackupPlanRevision", + "shortName": "get_backup_plan_revision" + }, + "description": "Sample for GetBackupPlanRevision", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_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": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRequest" + }, + { + "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.backupdr_v1beta.types.BackupPlan", + "shortName": "get_backup_plan" + }, + "description": "Sample for GetBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlan_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": "backupdr_v1beta_generated_backup_dr_get_backup_plan_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlan", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupPlan" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRequest" + }, + { + "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.backupdr_v1beta.types.BackupPlan", + "shortName": "get_backup_plan" + }, + "description": "Sample for GetBackupPlan", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlan_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": "backupdr_v1beta_generated_backup_dr_get_backup_plan_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupVaultRequest" + }, + { + "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.backupdr_v1beta.types.BackupVault", + "shortName": "get_backup_vault" + }, + "description": "Sample for GetBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_vault_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupVault_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": "backupdr_v1beta_generated_backup_dr_get_backup_vault_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_vault", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupVault", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackupVault" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBackupVaultRequest" + }, + { + "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.backupdr_v1beta.types.BackupVault", + "shortName": "get_backup_vault" + }, + "description": "Sample for GetBackupVault", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_vault_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupVault_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": "backupdr_v1beta_generated_backup_dr_get_backup_vault_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_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.backupdr_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_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": "backupdr_v1beta_generated_backup_dr_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackup", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_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.backupdr_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "backupdr_v1beta_generated_backup_dr_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_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": "backupdr_v1beta_generated_backup_dr_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_binding_matching_resource", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBindingMatchingResource", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBindingMatchingResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBindingMatchingResourceRequest" + }, + { + "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.backupdr_v1beta.types.BindingMatchingResource", + "shortName": "get_binding_matching_resource" + }, + "description": "Sample for GetBindingMatchingResource", + "file": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_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": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_binding_matching_resource", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBindingMatchingResource", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetBindingMatchingResource" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetBindingMatchingResourceRequest" + }, + { + "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.backupdr_v1beta.types.BindingMatchingResource", + "shortName": "get_binding_matching_resource" + }, + "description": "Sample for GetBindingMatchingResource", + "file": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_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": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_data_source_reference", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSourceReference", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "GetDataSourceReference" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.GetDataSourceReferenceRequest" }, { - "name": "resource_type", + "name": "name", "type": "str" }, { @@ -2251,22 +5048,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupsForResourceTypeAsyncPager", - "shortName": "fetch_backups_for_resource_type" + "resultType": "google.cloud.backupdr_v1beta.types.DataSourceReference", + "shortName": "get_data_source_reference" }, - "description": "Sample for FetchBackupsForResourceType", - "file": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_async.py", + "description": "Sample for GetDataSourceReference", + "file": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSourceReference_async", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2276,22 +5073,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": 54, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_async.py" + "title": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_async.py" }, { "canonical": true, @@ -2300,26 +5097,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_backups_for_resource_type", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_data_source_reference", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchBackupsForResourceType", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSourceReference", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchBackupsForResourceType" + "shortName": "GetDataSourceReference" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.FetchBackupsForResourceTypeRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.backupdr_v1beta.types.GetDataSourceReferenceRequest" }, { - "name": "resource_type", + "name": "name", "type": "str" }, { @@ -2335,22 +5128,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchBackupsForResourceTypePager", - "shortName": "fetch_backups_for_resource_type" + "resultType": "google.cloud.backupdr_v1beta.types.DataSourceReference", + "shortName": "get_data_source_reference" }, - "description": "Sample for FetchBackupsForResourceType", - "file": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_sync.py", + "description": "Sample for GetDataSourceReference", + "file": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_FetchBackupsForResourceType_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSourceReference_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2360,22 +5153,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": 54, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_fetch_backups_for_resource_type_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_sync.py" }, { "canonical": true, @@ -2385,26 +5178,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_data_source_references_for_resource_type", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_data_source", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchDataSourceReferencesForResourceType", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSource", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchDataSourceReferencesForResourceType" + "shortName": "GetDataSource" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.backupdr_v1beta.types.GetDataSourceRequest" }, { - "name": "resource_type", + "name": "name", "type": "str" }, { @@ -2420,22 +5209,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypeAsyncPager", - "shortName": "fetch_data_source_references_for_resource_type" + "resultType": "google.cloud.backupdr_v1beta.types.DataSource", + "shortName": "get_data_source" }, - "description": "Sample for FetchDataSourceReferencesForResourceType", - "file": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py", + "description": "Sample for GetDataSource", + "file": "backupdr_v1beta_generated_backup_dr_get_data_source_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSource_async", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2445,22 +5234,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": 54, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_async.py" + "title": "backupdr_v1beta_generated_backup_dr_get_data_source_async.py" }, { "canonical": true, @@ -2469,26 +5258,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_data_source_references_for_resource_type", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_data_source", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchDataSourceReferencesForResourceType", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSource", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchDataSourceReferencesForResourceType" + "shortName": "GetDataSource" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.FetchDataSourceReferencesForResourceTypeRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.backupdr_v1beta.types.GetDataSourceRequest" }, { - "name": "resource_type", + "name": "name", "type": "str" }, { @@ -2504,22 +5289,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchDataSourceReferencesForResourceTypePager", - "shortName": "fetch_data_source_references_for_resource_type" + "resultType": "google.cloud.backupdr_v1beta.types.DataSource", + "shortName": "get_data_source" }, - "description": "Sample for FetchDataSourceReferencesForResourceType", - "file": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py", + "description": "Sample for GetDataSource", + "file": "backupdr_v1beta_generated_backup_dr_get_data_source_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_FetchDataSourceReferencesForResourceType_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSource_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2529,22 +5314,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": 54, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_fetch_data_source_references_for_resource_type_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_get_data_source_sync.py" }, { "canonical": true, @@ -2554,22 +5339,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.fetch_usable_backup_vaults", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_management_server", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchUsableBackupVaults", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetManagementServer", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchUsableBackupVaults" + "shortName": "GetManagementServer" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest" + "type": "google.cloud.backupdr_v1beta.types.GetManagementServerRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -2585,22 +5370,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchUsableBackupVaultsAsyncPager", - "shortName": "fetch_usable_backup_vaults" + "resultType": "google.cloud.backupdr_v1beta.types.ManagementServer", + "shortName": "get_management_server" }, - "description": "Sample for FetchUsableBackupVaults", - "file": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_async.py", + "description": "Sample for GetManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_get_management_server_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetManagementServer_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2620,12 +5405,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_async.py" + "title": "backupdr_v1beta_generated_backup_dr_get_management_server_async.py" }, { "canonical": true, @@ -2634,22 +5419,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.fetch_usable_backup_vaults", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_management_server", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.FetchUsableBackupVaults", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetManagementServer", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "FetchUsableBackupVaults" + "shortName": "GetManagementServer" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.FetchUsableBackupVaultsRequest" + "type": "google.cloud.backupdr_v1beta.types.GetManagementServerRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -2665,22 +5450,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.FetchUsableBackupVaultsPager", - "shortName": "fetch_usable_backup_vaults" + "resultType": "google.cloud.backupdr_v1beta.types.ManagementServer", + "shortName": "get_management_server" }, - "description": "Sample for FetchUsableBackupVaults", - "file": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_sync.py", + "description": "Sample for GetManagementServer", + "file": "backupdr_v1beta_generated_backup_dr_get_management_server_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_FetchUsableBackupVaults_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetManagementServer_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2700,12 +5485,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_fetch_usable_backup_vaults_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_get_management_server_sync.py" }, { "canonical": true, @@ -2715,19 +5500,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_auto_protection_policy_binding", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_restore_template_execution", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicyBinding", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetRestoreTemplateExecution", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetAutoProtectionPolicyBinding" + "shortName": "GetRestoreTemplateExecution" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyBindingRequest" + "type": "google.cloud.backupdr_v1beta.types.GetRestoreTemplateExecutionRequest" }, { "name": "name", @@ -2746,14 +5531,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding", - "shortName": "get_auto_protection_policy_binding" + "resultType": "google.cloud.backupdr_v1beta.types.RestoreTemplateExecution", + "shortName": "get_restore_template_execution" }, - "description": "Sample for GetAutoProtectionPolicyBinding", - "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_async.py", + "description": "Sample for GetRestoreTemplateExecution", + "file": "backupdr_v1beta_generated_backup_dr_get_restore_template_execution_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetRestoreTemplateExecution_async", "segments": [ { "end": 51, @@ -2786,7 +5571,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_async.py" + "title": "backupdr_v1beta_generated_backup_dr_get_restore_template_execution_async.py" }, { "canonical": true, @@ -2795,19 +5580,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy_binding", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_restore_template_execution", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicyBinding", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetRestoreTemplateExecution", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetAutoProtectionPolicyBinding" + "shortName": "GetRestoreTemplateExecution" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyBindingRequest" + "type": "google.cloud.backupdr_v1beta.types.GetRestoreTemplateExecutionRequest" }, { "name": "name", @@ -2826,14 +5611,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicyBinding", - "shortName": "get_auto_protection_policy_binding" + "resultType": "google.cloud.backupdr_v1beta.types.RestoreTemplateExecution", + "shortName": "get_restore_template_execution" }, - "description": "Sample for GetAutoProtectionPolicyBinding", - "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_sync.py", + "description": "Sample for GetRestoreTemplateExecution", + "file": "backupdr_v1beta_generated_backup_dr_get_restore_template_execution_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicyBinding_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetRestoreTemplateExecution_sync", "segments": [ { "end": 51, @@ -2866,7 +5651,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_binding_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_get_restore_template_execution_sync.py" }, { "canonical": true, @@ -2876,19 +5661,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_auto_protection_policy", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicy", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetAutoProtectionPolicy" + "shortName": "GetRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyRequest" + "type": "google.cloud.backupdr_v1beta.types.GetRestoreTemplateRequest" }, { "name": "name", @@ -2907,14 +5692,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicy", - "shortName": "get_auto_protection_policy" + "resultType": "google.cloud.backupdr_v1beta.types.RestoreTemplate", + "shortName": "get_restore_template" }, - "description": "Sample for GetAutoProtectionPolicy", - "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_async.py", + "description": "Sample for GetRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_get_restore_template_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetRestoreTemplate_async", "segments": [ { "end": 51, @@ -2947,7 +5732,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_async.py" + "title": "backupdr_v1beta_generated_backup_dr_get_restore_template_async.py" }, { "canonical": true, @@ -2956,19 +5741,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_auto_protection_policy", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetAutoProtectionPolicy", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetAutoProtectionPolicy" + "shortName": "GetRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetAutoProtectionPolicyRequest" + "type": "google.cloud.backupdr_v1beta.types.GetRestoreTemplateRequest" }, { "name": "name", @@ -2987,14 +5772,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.AutoProtectionPolicy", - "shortName": "get_auto_protection_policy" + "resultType": "google.cloud.backupdr_v1beta.types.RestoreTemplate", + "shortName": "get_restore_template" }, - "description": "Sample for GetAutoProtectionPolicy", - "file": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_sync.py", + "description": "Sample for GetRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_get_restore_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetAutoProtectionPolicy_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetRestoreTemplate_sync", "segments": [ { "end": 51, @@ -3027,7 +5812,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_auto_protection_policy_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_get_restore_template_sync.py" }, { "canonical": true, @@ -3037,19 +5822,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_plan_association", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_restore_verification_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetRestoreVerificationPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlanAssociation" + "shortName": "GetRestoreVerificationPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1beta.types.GetRestoreVerificationPlanAssociationRequest" }, { "name": "name", @@ -3067,15 +5852,15 @@ "name": "metadata", "type": "Sequence[Tuple[str, Union[str, bytes]]]" } - ], - "resultType": "google.cloud.backupdr_v1beta.types.BackupPlanAssociation", - "shortName": "get_backup_plan_association" + ], + "resultType": "google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation", + "shortName": "get_restore_verification_plan_association" }, - "description": "Sample for GetBackupPlanAssociation", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_async.py", + "description": "Sample for GetRestoreVerificationPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlanAssociation_async", "segments": [ { "end": 51, @@ -3108,7 +5893,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_async.py" + "title": "backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_async.py" }, { "canonical": true, @@ -3117,19 +5902,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_association", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_restore_verification_plan_association", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanAssociation", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetRestoreVerificationPlanAssociation", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlanAssociation" + "shortName": "GetRestoreVerificationPlanAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanAssociationRequest" + "type": "google.cloud.backupdr_v1beta.types.GetRestoreVerificationPlanAssociationRequest" }, { "name": "name", @@ -3148,14 +5933,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.BackupPlanAssociation", - "shortName": "get_backup_plan_association" + "resultType": "google.cloud.backupdr_v1beta.types.RestoreVerificationPlanAssociation", + "shortName": "get_restore_verification_plan_association" }, - "description": "Sample for GetBackupPlanAssociation", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_sync.py", + "description": "Sample for GetRestoreVerificationPlanAssociation", + "file": "backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanAssociation_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlanAssociation_sync", "segments": [ { "end": 51, @@ -3188,7 +5973,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_association_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_association_sync.py" }, { "canonical": true, @@ -3198,19 +5983,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_plan_revision", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_restore_verification_plan", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanRevision", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetRestoreVerificationPlan", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlanRevision" + "shortName": "GetRestoreVerificationPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRevisionRequest" + "type": "google.cloud.backupdr_v1beta.types.GetRestoreVerificationPlanRequest" }, { "name": "name", @@ -3229,14 +6014,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.BackupPlanRevision", - "shortName": "get_backup_plan_revision" + "resultType": "google.cloud.backupdr_v1beta.types.RestoreVerificationPlan", + "shortName": "get_restore_verification_plan" }, - "description": "Sample for GetBackupPlanRevision", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_async.py", + "description": "Sample for GetRestoreVerificationPlan", + "file": "backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlan_async", "segments": [ { "end": 51, @@ -3269,7 +6054,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_async.py" + "title": "backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_async.py" }, { "canonical": true, @@ -3278,19 +6063,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan_revision", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_restore_verification_plan", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlanRevision", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetRestoreVerificationPlan", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlanRevision" + "shortName": "GetRestoreVerificationPlan" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRevisionRequest" + "type": "google.cloud.backupdr_v1beta.types.GetRestoreVerificationPlanRequest" }, { "name": "name", @@ -3309,14 +6094,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.BackupPlanRevision", - "shortName": "get_backup_plan_revision" + "resultType": "google.cloud.backupdr_v1beta.types.RestoreVerificationPlan", + "shortName": "get_restore_verification_plan" }, - "description": "Sample for GetBackupPlanRevision", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_sync.py", + "description": "Sample for GetRestoreVerificationPlan", + "file": "backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlanRevision_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_GetRestoreVerificationPlan_sync", "segments": [ { "end": 51, @@ -3349,7 +6134,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_revision_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_get_restore_verification_plan_sync.py" }, { "canonical": true, @@ -3359,23 +6144,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_plan", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.initialize_service", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlan", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitializeService", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlan" + "shortName": "InitializeService" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.backupdr_v1beta.types.InitializeServiceRequest" }, { "name": "retry", @@ -3390,22 +6171,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.BackupPlan", - "shortName": "get_backup_plan" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "initialize_service" }, - "description": "Sample for GetBackupPlan", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_async.py", + "description": "Sample for InitializeService", + "file": "backupdr_v1beta_generated_backup_dr_initialize_service_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlan_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_InitializeService_async", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -3415,22 +6196,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_async.py" + "title": "backupdr_v1beta_generated_backup_dr_initialize_service_async.py" }, { "canonical": true, @@ -3439,23 +6220,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_plan", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.initialize_service", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupPlan", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitializeService", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupPlan" + "shortName": "InitializeService" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupPlanRequest" - }, - { - "name": "name", - "type": "str" + "type": "google.cloud.backupdr_v1beta.types.InitializeServiceRequest" }, { "name": "retry", @@ -3470,22 +6247,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.BackupPlan", - "shortName": "get_backup_plan" + "resultType": "google.api_core.operation.Operation", + "shortName": "initialize_service" }, - "description": "Sample for GetBackupPlan", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_plan_sync.py", + "description": "Sample for InitializeService", + "file": "backupdr_v1beta_generated_backup_dr_initialize_service_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupPlan_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_InitializeService_sync", "segments": [ { - "end": 51, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 60, "start": 27, "type": "SHORT" }, @@ -3495,22 +6272,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_plan_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_initialize_service_sync.py" }, { "canonical": true, @@ -3520,19 +6297,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup_vault", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.initiate_delete_auto_protection_policy_binding", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupVault", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitiateDeleteAutoProtectionPolicyBinding", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupVault" + "shortName": "InitiateDeleteAutoProtectionPolicyBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupVaultRequest" + "type": "google.cloud.backupdr_v1beta.types.InitiateDeleteAutoProtectionPolicyBindingRequest" }, { "name": "name", @@ -3551,22 +6328,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.BackupVault", - "shortName": "get_backup_vault" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "initiate_delete_auto_protection_policy_binding" }, - "description": "Sample for GetBackupVault", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_vault_async.py", + "description": "Sample for InitiateDeleteAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupVault_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_async", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -3581,17 +6358,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_vault_async.py" + "title": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py" }, { "canonical": true, @@ -3600,19 +6377,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup_vault", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.initiate_delete_auto_protection_policy_binding", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackupVault", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitiateDeleteAutoProtectionPolicyBinding", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackupVault" + "shortName": "InitiateDeleteAutoProtectionPolicyBinding" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupVaultRequest" + "type": "google.cloud.backupdr_v1beta.types.InitiateDeleteAutoProtectionPolicyBindingRequest" }, { "name": "name", @@ -3631,22 +6408,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.BackupVault", - "shortName": "get_backup_vault" + "resultType": "google.api_core.operation.Operation", + "shortName": "initiate_delete_auto_protection_policy_binding" }, - "description": "Sample for GetBackupVault", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_vault_sync.py", + "description": "Sample for InitiateDeleteAutoProtectionPolicyBinding", + "file": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackupVault_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_sync", "segments": [ { - "end": 51, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 55, "start": 27, "type": "SHORT" }, @@ -3661,17 +6438,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_vault_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py" }, { "canonical": true, @@ -3681,22 +6458,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_backup", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_applied_auto_protection_policies", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackup", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAppliedAutoProtectionPolicies", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackup" + "shortName": "ListAppliedAutoProtectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupRequest" + "type": "google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3712,22 +6489,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.Backup", - "shortName": "get_backup" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesAsyncPager", + "shortName": "list_applied_auto_protection_policies" }, - "description": "Sample for GetBackup", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_async.py", + "description": "Sample for ListAppliedAutoProtectionPolicies", + "file": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackup_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3747,12 +6524,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_async.py" }, { "canonical": true, @@ -3761,22 +6538,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_backup", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_applied_auto_protection_policies", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBackup", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAppliedAutoProtectionPolicies", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBackup" + "shortName": "ListAppliedAutoProtectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBackupRequest" + "type": "google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3792,22 +6569,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.Backup", - "shortName": "get_backup" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesPager", + "shortName": "list_applied_auto_protection_policies" }, - "description": "Sample for GetBackup", - "file": "backupdr_v1beta_generated_backup_dr_get_backup_sync.py", + "description": "Sample for ListAppliedAutoProtectionPolicies", + "file": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBackup_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3827,12 +6604,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_backup_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_sync.py" }, { "canonical": true, @@ -3842,22 +6619,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_binding_matching_resource", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_auto_protection_policies", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBindingMatchingResource", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicies", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBindingMatchingResource" + "shortName": "ListAutoProtectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBindingMatchingResourceRequest" + "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3873,22 +6650,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.BindingMatchingResource", - "shortName": "get_binding_matching_resource" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPoliciesAsyncPager", + "shortName": "list_auto_protection_policies" }, - "description": "Sample for GetBindingMatchingResource", - "file": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_async.py", + "description": "Sample for ListAutoProtectionPolicies", + "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3908,12 +6685,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_async.py" }, { "canonical": true, @@ -3922,22 +6699,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_binding_matching_resource", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policies", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetBindingMatchingResource", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicies", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetBindingMatchingResource" + "shortName": "ListAutoProtectionPolicies" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetBindingMatchingResourceRequest" + "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3953,22 +6730,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.BindingMatchingResource", - "shortName": "get_binding_matching_resource" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPoliciesPager", + "shortName": "list_auto_protection_policies" }, - "description": "Sample for GetBindingMatchingResource", - "file": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_sync.py", + "description": "Sample for ListAutoProtectionPolicies", + "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetBindingMatchingResource_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3988,12 +6765,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_binding_matching_resource_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_sync.py" }, { "canonical": true, @@ -4003,22 +6780,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_data_source_reference", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_auto_protection_policy_bindings", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSourceReference", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicyBindings", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetDataSourceReference" + "shortName": "ListAutoProtectionPolicyBindings" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetDataSourceReferenceRequest" + "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -4034,22 +6811,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.DataSourceReference", - "shortName": "get_data_source_reference" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsAsyncPager", + "shortName": "list_auto_protection_policy_bindings" }, - "description": "Sample for GetDataSourceReference", - "file": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_async.py", + "description": "Sample for ListAutoProtectionPolicyBindings", + "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSourceReference_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4069,12 +6846,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_async.py" }, { "canonical": true, @@ -4083,22 +6860,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_data_source_reference", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policy_bindings", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSourceReference", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicyBindings", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetDataSourceReference" + "shortName": "ListAutoProtectionPolicyBindings" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetDataSourceReferenceRequest" + "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -4114,22 +6891,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.DataSourceReference", - "shortName": "get_data_source_reference" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsPager", + "shortName": "list_auto_protection_policy_bindings" }, - "description": "Sample for GetDataSourceReference", - "file": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_sync.py", + "description": "Sample for ListAutoProtectionPolicyBindings", + "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSourceReference_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4149,12 +6926,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_data_source_reference_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_sync.py" }, { "canonical": true, @@ -4164,22 +6941,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_data_source", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_plan_associations", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSource", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanAssociations", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetDataSource" + "shortName": "ListBackupPlanAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetDataSourceRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -4195,22 +6972,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.DataSource", - "shortName": "get_data_source" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanAssociationsAsyncPager", + "shortName": "list_backup_plan_associations" }, - "description": "Sample for GetDataSource", - "file": "backupdr_v1beta_generated_backup_dr_get_data_source_async.py", + "description": "Sample for ListBackupPlanAssociations", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSource_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4230,12 +7007,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_data_source_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_async.py" }, { "canonical": true, @@ -4244,22 +7021,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_data_source", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_associations", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetDataSource", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanAssociations", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetDataSource" + "shortName": "ListBackupPlanAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetDataSourceRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -4275,22 +7052,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.DataSource", - "shortName": "get_data_source" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanAssociationsPager", + "shortName": "list_backup_plan_associations" }, - "description": "Sample for GetDataSource", - "file": "backupdr_v1beta_generated_backup_dr_get_data_source_sync.py", + "description": "Sample for ListBackupPlanAssociations", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetDataSource_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4310,12 +7087,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_data_source_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_sync.py" }, { "canonical": true, @@ -4325,22 +7102,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.get_management_server", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_plan_revisions", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetManagementServer", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanRevisions", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetManagementServer" + "shortName": "ListBackupPlanRevisions" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetManagementServerRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -4356,22 +7133,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.ManagementServer", - "shortName": "get_management_server" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanRevisionsAsyncPager", + "shortName": "list_backup_plan_revisions" }, - "description": "Sample for GetManagementServer", - "file": "backupdr_v1beta_generated_backup_dr_get_management_server_async.py", + "description": "Sample for ListBackupPlanRevisions", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetManagementServer_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4391,12 +7168,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_management_server_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_async.py" }, { "canonical": true, @@ -4405,22 +7182,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.get_management_server", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_revisions", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.GetManagementServer", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanRevisions", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "GetManagementServer" + "shortName": "ListBackupPlanRevisions" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.GetManagementServerRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -4436,22 +7213,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.types.ManagementServer", - "shortName": "get_management_server" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanRevisionsPager", + "shortName": "list_backup_plan_revisions" }, - "description": "Sample for GetManagementServer", - "file": "backupdr_v1beta_generated_backup_dr_get_management_server_sync.py", + "description": "Sample for ListBackupPlanRevisions", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_GetManagementServer_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4471,12 +7248,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_get_management_server_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_sync.py" }, { "canonical": true, @@ -4486,19 +7263,23 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.initialize_service", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_plans", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitializeService", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlans", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "InitializeService" + "shortName": "ListBackupPlans" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.InitializeServiceRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlansRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -4513,22 +7294,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "initialize_service" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlansAsyncPager", + "shortName": "list_backup_plans" }, - "description": "Sample for InitializeService", - "file": "backupdr_v1beta_generated_backup_dr_initialize_service_async.py", + "description": "Sample for ListBackupPlans", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plans_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_InitializeService_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlans_async", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4538,22 +7319,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_initialize_service_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plans_async.py" }, { "canonical": true, @@ -4562,19 +7343,23 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.initialize_service", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plans", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitializeService", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlans", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "InitializeService" + "shortName": "ListBackupPlans" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.InitializeServiceRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupPlansRequest" + }, + { + "name": "parent", + "type": "str" }, { "name": "retry", @@ -4589,22 +7374,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "initialize_service" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlansPager", + "shortName": "list_backup_plans" }, - "description": "Sample for InitializeService", - "file": "backupdr_v1beta_generated_backup_dr_initialize_service_sync.py", + "description": "Sample for ListBackupPlans", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_plans_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_InitializeService_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlans_sync", "segments": [ { - "end": 60, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4614,22 +7399,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_initialize_service_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backup_plans_sync.py" }, { "canonical": true, @@ -4639,22 +7424,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.initiate_delete_auto_protection_policy_binding", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_vaults", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitiateDeleteAutoProtectionPolicyBinding", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupVaults", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "InitiateDeleteAutoProtectionPolicyBinding" + "shortName": "ListBackupVaults" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.InitiateDeleteAutoProtectionPolicyBindingRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -4670,22 +7455,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "initiate_delete_auto_protection_policy_binding" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupVaultsAsyncPager", + "shortName": "list_backup_vaults" }, - "description": "Sample for InitiateDeleteAutoProtectionPolicyBinding", - "file": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py", + "description": "Sample for ListBackupVaults", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupVaults_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4700,17 +7485,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": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_async.py" }, { "canonical": true, @@ -4719,22 +7504,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.initiate_delete_auto_protection_policy_binding", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_vaults", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.InitiateDeleteAutoProtectionPolicyBinding", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupVaults", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "InitiateDeleteAutoProtectionPolicyBinding" + "shortName": "ListBackupVaults" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.InitiateDeleteAutoProtectionPolicyBindingRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -4750,22 +7535,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "initiate_delete_auto_protection_policy_binding" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupVaultsPager", + "shortName": "list_backup_vaults" }, - "description": "Sample for InitiateDeleteAutoProtectionPolicyBinding", - "file": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py", + "description": "Sample for ListBackupVaults", + "file": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_InitiateDeleteAutoProtectionPolicyBinding_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupVaults_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -4780,17 +7565,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": "backupdr_v1beta_generated_backup_dr_initiate_delete_auto_protection_policy_binding_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_sync.py" }, { "canonical": true, @@ -4800,19 +7585,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_applied_auto_protection_policies", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backups", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAppliedAutoProtectionPolicies", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackups", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListAppliedAutoProtectionPolicies" + "shortName": "ListBackups" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupsRequest" }, { "name": "parent", @@ -4831,14 +7616,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesAsyncPager", - "shortName": "list_applied_auto_protection_policies" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" }, - "description": "Sample for ListAppliedAutoProtectionPolicies", - "file": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_async.py", + "description": "Sample for ListBackups", + "file": "backupdr_v1beta_generated_backup_dr_list_backups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackups_async", "segments": [ { "end": 52, @@ -4871,7 +7656,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backups_async.py" }, { "canonical": true, @@ -4880,19 +7665,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_applied_auto_protection_policies", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backups", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAppliedAutoProtectionPolicies", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackups", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListAppliedAutoProtectionPolicies" + "shortName": "ListBackups" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListAppliedAutoProtectionPoliciesRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBackupsRequest" }, { "name": "parent", @@ -4911,14 +7696,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAppliedAutoProtectionPoliciesPager", - "shortName": "list_applied_auto_protection_policies" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupsPager", + "shortName": "list_backups" }, - "description": "Sample for ListAppliedAutoProtectionPolicies", - "file": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_sync.py", + "description": "Sample for ListBackups", + "file": "backupdr_v1beta_generated_backup_dr_list_backups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListAppliedAutoProtectionPolicies_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackups_sync", "segments": [ { "end": 52, @@ -4951,7 +7736,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_applied_auto_protection_policies_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_backups_sync.py" }, { "canonical": true, @@ -4961,19 +7746,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_auto_protection_policies", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_binding_matching_resources", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicies", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBindingMatchingResources", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListAutoProtectionPolicies" + "shortName": "ListBindingMatchingResources" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest" }, { "name": "parent", @@ -4992,14 +7777,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPoliciesAsyncPager", - "shortName": "list_auto_protection_policies" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBindingMatchingResourcesAsyncPager", + "shortName": "list_binding_matching_resources" }, - "description": "Sample for ListAutoProtectionPolicies", - "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_async.py", + "description": "Sample for ListBindingMatchingResources", + "file": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_async", "segments": [ { "end": 52, @@ -5032,7 +7817,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_async.py" }, { "canonical": true, @@ -5041,19 +7826,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policies", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_binding_matching_resources", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicies", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBindingMatchingResources", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListAutoProtectionPolicies" + "shortName": "ListBindingMatchingResources" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPoliciesRequest" + "type": "google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest" }, { "name": "parent", @@ -5072,14 +7857,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPoliciesPager", - "shortName": "list_auto_protection_policies" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBindingMatchingResourcesPager", + "shortName": "list_binding_matching_resources" }, - "description": "Sample for ListAutoProtectionPolicies", - "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_sync.py", + "description": "Sample for ListBindingMatchingResources", + "file": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicies_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_sync", "segments": [ { "end": 52, @@ -5112,7 +7897,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policies_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_sync.py" }, { "canonical": true, @@ -5122,19 +7907,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_auto_protection_policy_bindings", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_data_source_references", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicyBindings", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSourceReferences", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListAutoProtectionPolicyBindings" + "shortName": "ListDataSourceReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest" }, { "name": "parent", @@ -5153,14 +7938,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsAsyncPager", - "shortName": "list_auto_protection_policy_bindings" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourceReferencesAsyncPager", + "shortName": "list_data_source_references" }, - "description": "Sample for ListAutoProtectionPolicyBindings", - "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_async.py", + "description": "Sample for ListDataSourceReferences", + "file": "backupdr_v1beta_generated_backup_dr_list_data_source_references_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_async", "segments": [ { "end": 52, @@ -5193,7 +7978,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_data_source_references_async.py" }, { "canonical": true, @@ -5202,19 +7987,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_auto_protection_policy_bindings", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_data_source_references", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListAutoProtectionPolicyBindings", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSourceReferences", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListAutoProtectionPolicyBindings" + "shortName": "ListDataSourceReferences" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListAutoProtectionPolicyBindingsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest" }, { "name": "parent", @@ -5233,14 +8018,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListAutoProtectionPolicyBindingsPager", - "shortName": "list_auto_protection_policy_bindings" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourceReferencesPager", + "shortName": "list_data_source_references" }, - "description": "Sample for ListAutoProtectionPolicyBindings", - "file": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_sync.py", + "description": "Sample for ListDataSourceReferences", + "file": "backupdr_v1beta_generated_backup_dr_list_data_source_references_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListAutoProtectionPolicyBindings_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_sync", "segments": [ { "end": 52, @@ -5273,7 +8058,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_auto_protection_policy_bindings_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_data_source_references_sync.py" }, { "canonical": true, @@ -5283,19 +8068,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_plan_associations", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_data_sources", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanAssociations", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSources", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlanAssociations" + "shortName": "ListDataSources" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListDataSourcesRequest" }, { "name": "parent", @@ -5314,14 +8099,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanAssociationsAsyncPager", - "shortName": "list_backup_plan_associations" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourcesAsyncPager", + "shortName": "list_data_sources" }, - "description": "Sample for ListBackupPlanAssociations", - "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_async.py", + "description": "Sample for ListDataSources", + "file": "backupdr_v1beta_generated_backup_dr_list_data_sources_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSources_async", "segments": [ { "end": 52, @@ -5354,7 +8139,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_data_sources_async.py" }, { "canonical": true, @@ -5363,19 +8148,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_associations", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_data_sources", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanAssociations", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSources", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlanAssociations" + "shortName": "ListDataSources" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanAssociationsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListDataSourcesRequest" }, { "name": "parent", @@ -5394,14 +8179,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanAssociationsPager", - "shortName": "list_backup_plan_associations" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourcesPager", + "shortName": "list_data_sources" }, - "description": "Sample for ListBackupPlanAssociations", - "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_sync.py", + "description": "Sample for ListDataSources", + "file": "backupdr_v1beta_generated_backup_dr_list_data_sources_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanAssociations_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSources_sync", "segments": [ { "end": 52, @@ -5434,7 +8219,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_associations_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_data_sources_sync.py" }, { "canonical": true, @@ -5444,19 +8229,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_plan_revisions", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_management_servers", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanRevisions", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListManagementServers", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlanRevisions" + "shortName": "ListManagementServers" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListManagementServersRequest" }, { "name": "parent", @@ -5475,14 +8260,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanRevisionsAsyncPager", - "shortName": "list_backup_plan_revisions" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersAsyncPager", + "shortName": "list_management_servers" }, - "description": "Sample for ListBackupPlanRevisions", - "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_async.py", + "description": "Sample for ListManagementServers", + "file": "backupdr_v1beta_generated_backup_dr_list_management_servers_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListManagementServers_async", "segments": [ { "end": 52, @@ -5515,7 +8300,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_management_servers_async.py" }, { "canonical": true, @@ -5524,19 +8309,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plan_revisions", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_management_servers", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlanRevisions", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListManagementServers", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlanRevisions" + "shortName": "ListManagementServers" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupPlanRevisionsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListManagementServersRequest" }, { "name": "parent", @@ -5555,14 +8340,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlanRevisionsPager", - "shortName": "list_backup_plan_revisions" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersPager", + "shortName": "list_management_servers" }, - "description": "Sample for ListBackupPlanRevisions", - "file": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_sync.py", + "description": "Sample for ListManagementServers", + "file": "backupdr_v1beta_generated_backup_dr_list_management_servers_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlanRevisions_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListManagementServers_sync", "segments": [ { "end": 52, @@ -5595,7 +8380,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backup_plan_revisions_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_management_servers_sync.py" }, { "canonical": true, @@ -5605,19 +8390,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_plans", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_restore_template_executions", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlans", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListRestoreTemplateExecutions", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlans" + "shortName": "ListRestoreTemplateExecutions" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupPlansRequest" + "type": "google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsRequest" }, { "name": "parent", @@ -5636,14 +8421,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlansAsyncPager", - "shortName": "list_backup_plans" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreTemplateExecutionsAsyncPager", + "shortName": "list_restore_template_executions" }, - "description": "Sample for ListBackupPlans", - "file": "backupdr_v1beta_generated_backup_dr_list_backup_plans_async.py", + "description": "Sample for ListRestoreTemplateExecutions", + "file": "backupdr_v1beta_generated_backup_dr_list_restore_template_executions_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlans_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListRestoreTemplateExecutions_async", "segments": [ { "end": 52, @@ -5676,7 +8461,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backup_plans_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_restore_template_executions_async.py" }, { "canonical": true, @@ -5685,19 +8470,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_plans", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_restore_template_executions", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupPlans", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListRestoreTemplateExecutions", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupPlans" + "shortName": "ListRestoreTemplateExecutions" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupPlansRequest" + "type": "google.cloud.backupdr_v1beta.types.ListRestoreTemplateExecutionsRequest" }, { "name": "parent", @@ -5716,14 +8501,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupPlansPager", - "shortName": "list_backup_plans" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreTemplateExecutionsPager", + "shortName": "list_restore_template_executions" }, - "description": "Sample for ListBackupPlans", - "file": "backupdr_v1beta_generated_backup_dr_list_backup_plans_sync.py", + "description": "Sample for ListRestoreTemplateExecutions", + "file": "backupdr_v1beta_generated_backup_dr_list_restore_template_executions_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupPlans_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListRestoreTemplateExecutions_sync", "segments": [ { "end": 52, @@ -5756,7 +8541,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backup_plans_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_restore_template_executions_sync.py" }, { "canonical": true, @@ -5766,19 +8551,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backup_vaults", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_restore_templates", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupVaults", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListRestoreTemplates", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupVaults" + "shortName": "ListRestoreTemplates" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListRestoreTemplatesRequest" }, { "name": "parent", @@ -5797,14 +8582,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupVaultsAsyncPager", - "shortName": "list_backup_vaults" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreTemplatesAsyncPager", + "shortName": "list_restore_templates" }, - "description": "Sample for ListBackupVaults", - "file": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_async.py", + "description": "Sample for ListRestoreTemplates", + "file": "backupdr_v1beta_generated_backup_dr_list_restore_templates_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupVaults_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListRestoreTemplates_async", "segments": [ { "end": 52, @@ -5837,7 +8622,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_restore_templates_async.py" }, { "canonical": true, @@ -5846,19 +8631,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backup_vaults", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_restore_templates", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackupVaults", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListRestoreTemplates", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackupVaults" + "shortName": "ListRestoreTemplates" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupVaultsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListRestoreTemplatesRequest" }, { "name": "parent", @@ -5877,14 +8662,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupVaultsPager", - "shortName": "list_backup_vaults" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreTemplatesPager", + "shortName": "list_restore_templates" }, - "description": "Sample for ListBackupVaults", - "file": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_sync.py", + "description": "Sample for ListRestoreTemplates", + "file": "backupdr_v1beta_generated_backup_dr_list_restore_templates_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackupVaults_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListRestoreTemplates_sync", "segments": [ { "end": 52, @@ -5917,7 +8702,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backup_vaults_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_restore_templates_sync.py" }, { "canonical": true, @@ -5927,19 +8712,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_backups", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_restore_verification_plan_associations", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackups", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListRestoreVerificationPlanAssociations", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackups" + "shortName": "ListRestoreVerificationPlanAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsRequest" }, { "name": "parent", @@ -5958,14 +8743,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupsAsyncPager", - "shortName": "list_backups" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreVerificationPlanAssociationsAsyncPager", + "shortName": "list_restore_verification_plan_associations" }, - "description": "Sample for ListBackups", - "file": "backupdr_v1beta_generated_backup_dr_list_backups_async.py", + "description": "Sample for ListRestoreVerificationPlanAssociations", + "file": "backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackups_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlanAssociations_async", "segments": [ { "end": 52, @@ -5998,7 +8783,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backups_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_async.py" }, { "canonical": true, @@ -6007,19 +8792,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_backups", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_restore_verification_plan_associations", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBackups", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListRestoreVerificationPlanAssociations", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBackups" + "shortName": "ListRestoreVerificationPlanAssociations" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBackupsRequest" + "type": "google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlanAssociationsRequest" }, { "name": "parent", @@ -6038,14 +8823,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBackupsPager", - "shortName": "list_backups" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreVerificationPlanAssociationsPager", + "shortName": "list_restore_verification_plan_associations" }, - "description": "Sample for ListBackups", - "file": "backupdr_v1beta_generated_backup_dr_list_backups_sync.py", + "description": "Sample for ListRestoreVerificationPlanAssociations", + "file": "backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBackups_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlanAssociations_sync", "segments": [ { "end": 52, @@ -6078,7 +8863,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_backups_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_restore_verification_plan_associations_sync.py" }, { "canonical": true, @@ -6088,19 +8873,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_binding_matching_resources", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_restore_verification_plans", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBindingMatchingResources", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListRestoreVerificationPlans", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBindingMatchingResources" + "shortName": "ListRestoreVerificationPlans" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest" + "type": "google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansRequest" }, { "name": "parent", @@ -6119,14 +8904,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBindingMatchingResourcesAsyncPager", - "shortName": "list_binding_matching_resources" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreVerificationPlansAsyncPager", + "shortName": "list_restore_verification_plans" }, - "description": "Sample for ListBindingMatchingResources", - "file": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_async.py", + "description": "Sample for ListRestoreVerificationPlans", + "file": "backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlans_async", "segments": [ { "end": 52, @@ -6159,7 +8944,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_async.py" + "title": "backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_async.py" }, { "canonical": true, @@ -6168,19 +8953,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_binding_matching_resources", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_restore_verification_plans", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListBindingMatchingResources", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListRestoreVerificationPlans", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListBindingMatchingResources" + "shortName": "ListRestoreVerificationPlans" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListBindingMatchingResourcesRequest" + "type": "google.cloud.backupdr_v1beta.types.ListRestoreVerificationPlansRequest" }, { "name": "parent", @@ -6199,14 +8984,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListBindingMatchingResourcesPager", - "shortName": "list_binding_matching_resources" + "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListRestoreVerificationPlansPager", + "shortName": "list_restore_verification_plans" }, - "description": "Sample for ListBindingMatchingResources", - "file": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_sync.py", + "description": "Sample for ListRestoreVerificationPlans", + "file": "backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListBindingMatchingResources_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_ListRestoreVerificationPlans_sync", "segments": [ { "end": 52, @@ -6239,7 +9024,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_binding_matching_resources_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_list_restore_verification_plans_sync.py" }, { "canonical": true, @@ -6249,22 +9034,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_data_source_references", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.restore_backup", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSourceReferences", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.RestoreBackup", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListDataSourceReferences" + "shortName": "RestoreBackup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest" + "type": "google.cloud.backupdr_v1beta.types.RestoreBackupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6280,22 +9065,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourceReferencesAsyncPager", - "shortName": "list_data_source_references" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "restore_backup" }, - "description": "Sample for ListDataSourceReferences", - "file": "backupdr_v1beta_generated_backup_dr_list_data_source_references_async.py", + "description": "Sample for RestoreBackup", + "file": "backupdr_v1beta_generated_backup_dr_restore_backup_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_RestoreBackup_async", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -6305,22 +9090,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_data_source_references_async.py" + "title": "backupdr_v1beta_generated_backup_dr_restore_backup_async.py" }, { "canonical": true, @@ -6329,22 +9114,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_data_source_references", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.restore_backup", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSourceReferences", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.RestoreBackup", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListDataSourceReferences" + "shortName": "RestoreBackup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListDataSourceReferencesRequest" + "type": "google.cloud.backupdr_v1beta.types.RestoreBackupRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6360,22 +9145,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourceReferencesPager", - "shortName": "list_data_source_references" + "resultType": "google.api_core.operation.Operation", + "shortName": "restore_backup" }, - "description": "Sample for ListDataSourceReferences", - "file": "backupdr_v1beta_generated_backup_dr_list_data_source_references_sync.py", + "description": "Sample for RestoreBackup", + "file": "backupdr_v1beta_generated_backup_dr_restore_backup_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSourceReferences_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_RestoreBackup_sync", "segments": [ { - "end": 52, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 60, "start": 27, "type": "SHORT" }, @@ -6385,22 +9170,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_data_source_references_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_restore_backup_sync.py" }, { "canonical": true, @@ -6410,22 +9195,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_data_sources", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.run_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSources", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.RunRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListDataSources" + "shortName": "RunRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListDataSourcesRequest" + "type": "google.cloud.backupdr_v1beta.types.RunRestoreTemplateRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6441,22 +9226,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourcesAsyncPager", - "shortName": "list_data_sources" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "run_restore_template" }, - "description": "Sample for ListDataSources", - "file": "backupdr_v1beta_generated_backup_dr_list_data_sources_async.py", + "description": "Sample for RunRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_run_restore_template_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSources_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_RunRestoreTemplate_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6471,17 +9256,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_data_sources_async.py" + "title": "backupdr_v1beta_generated_backup_dr_run_restore_template_async.py" }, { "canonical": true, @@ -6490,22 +9275,22 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_data_sources", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.run_restore_template", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListDataSources", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.RunRestoreTemplate", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListDataSources" + "shortName": "RunRestoreTemplate" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListDataSourcesRequest" + "type": "google.cloud.backupdr_v1beta.types.RunRestoreTemplateRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -6521,22 +9306,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListDataSourcesPager", - "shortName": "list_data_sources" + "resultType": "google.api_core.operation.Operation", + "shortName": "run_restore_template" }, - "description": "Sample for ListDataSources", - "file": "backupdr_v1beta_generated_backup_dr_list_data_sources_sync.py", + "description": "Sample for RunRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_run_restore_template_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListDataSources_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_RunRestoreTemplate_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6551,17 +9336,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_data_sources_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_run_restore_template_sync.py" }, { "canonical": true, @@ -6571,22 +9356,26 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.list_management_servers", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.trigger_backup", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListManagementServers", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerBackup", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListManagementServers" + "shortName": "TriggerBackup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListManagementServersRequest" + "type": "google.cloud.backupdr_v1beta.types.TriggerBackupRequest" }, { - "name": "parent", + "name": "name", + "type": "str" + }, + { + "name": "rule_id", "type": "str" }, { @@ -6602,22 +9391,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersAsyncPager", - "shortName": "list_management_servers" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "trigger_backup" }, - "description": "Sample for ListManagementServers", - "file": "backupdr_v1beta_generated_backup_dr_list_management_servers_async.py", + "description": "Sample for TriggerBackup", + "file": "backupdr_v1beta_generated_backup_dr_trigger_backup_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListManagementServers_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerBackup_async", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6632,17 +9421,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_management_servers_async.py" + "title": "backupdr_v1beta_generated_backup_dr_trigger_backup_async.py" }, { "canonical": true, @@ -6651,22 +9440,26 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.list_management_servers", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.trigger_backup", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.ListManagementServers", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerBackup", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "ListManagementServers" + "shortName": "TriggerBackup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.ListManagementServersRequest" + "type": "google.cloud.backupdr_v1beta.types.TriggerBackupRequest" }, { - "name": "parent", + "name": "name", + "type": "str" + }, + { + "name": "rule_id", "type": "str" }, { @@ -6682,22 +9475,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.backupdr_v1beta.services.backup_dr.pagers.ListManagementServersPager", - "shortName": "list_management_servers" + "resultType": "google.api_core.operation.Operation", + "shortName": "trigger_backup" }, - "description": "Sample for ListManagementServers", - "file": "backupdr_v1beta_generated_backup_dr_list_management_servers_sync.py", + "description": "Sample for TriggerBackup", + "file": "backupdr_v1beta_generated_backup_dr_trigger_backup_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_ListManagementServers_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerBackup_sync", "segments": [ { - "end": 52, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6712,17 +9505,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 48, + "end": 52, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_list_management_servers_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_trigger_backup_sync.py" }, { "canonical": true, @@ -6732,19 +9525,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.restore_backup", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.trigger_restore_cleanup", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.RestoreBackup", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerRestoreCleanup", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "RestoreBackup" + "shortName": "TriggerRestoreCleanup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.RestoreBackupRequest" + "type": "google.cloud.backupdr_v1beta.types.TriggerRestoreCleanupRequest" }, { "name": "name", @@ -6764,21 +9557,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "restore_backup" + "shortName": "trigger_restore_cleanup" }, - "description": "Sample for RestoreBackup", - "file": "backupdr_v1beta_generated_backup_dr_restore_backup_async.py", + "description": "Sample for TriggerRestoreCleanup", + "file": "backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_RestoreBackup_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerRestoreCleanup_async", "segments": [ { - "end": 60, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6788,22 +9581,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_restore_backup_async.py" + "title": "backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_async.py" }, { "canonical": true, @@ -6812,19 +9605,19 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.restore_backup", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.trigger_restore_cleanup", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.RestoreBackup", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerRestoreCleanup", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "RestoreBackup" + "shortName": "TriggerRestoreCleanup" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.RestoreBackupRequest" + "type": "google.cloud.backupdr_v1beta.types.TriggerRestoreCleanupRequest" }, { "name": "name", @@ -6844,21 +9637,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "restore_backup" + "shortName": "trigger_restore_cleanup" }, - "description": "Sample for RestoreBackup", - "file": "backupdr_v1beta_generated_backup_dr_restore_backup_sync.py", + "description": "Sample for TriggerRestoreCleanup", + "file": "backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_RestoreBackup_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerRestoreCleanup_sync", "segments": [ { - "end": 60, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 55, "start": 27, "type": "SHORT" }, @@ -6868,22 +9661,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 52, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_restore_backup_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_trigger_restore_cleanup_sync.py" }, { "canonical": true, @@ -6893,28 +9686,24 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", "shortName": "BackupDRAsyncClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.trigger_backup", + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.trigger_restore_verification", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerBackup", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerRestoreVerification", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "TriggerBackup" + "shortName": "TriggerRestoreVerification" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.TriggerBackupRequest" + "type": "google.cloud.backupdr_v1beta.types.TriggerRestoreVerificationRequest" }, { "name": "name", "type": "str" }, - { - "name": "rule_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -6929,13 +9718,13 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "trigger_backup" + "shortName": "trigger_restore_verification" }, - "description": "Sample for TriggerBackup", - "file": "backupdr_v1beta_generated_backup_dr_trigger_backup_async.py", + "description": "Sample for TriggerRestoreVerification", + "file": "backupdr_v1beta_generated_backup_dr_trigger_restore_verification_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerBackup_async", + "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerRestoreVerification_async", "segments": [ { "end": 55, @@ -6968,7 +9757,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_trigger_backup_async.py" + "title": "backupdr_v1beta_generated_backup_dr_trigger_restore_verification_async.py" }, { "canonical": true, @@ -6977,28 +9766,24 @@ "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", "shortName": "BackupDRClient" }, - "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.trigger_backup", + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.trigger_restore_verification", "method": { - "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerBackup", + "fullName": "google.cloud.backupdr.v1beta.BackupDR.TriggerRestoreVerification", "service": { "fullName": "google.cloud.backupdr.v1beta.BackupDR", "shortName": "BackupDR" }, - "shortName": "TriggerBackup" + "shortName": "TriggerRestoreVerification" }, "parameters": [ { "name": "request", - "type": "google.cloud.backupdr_v1beta.types.TriggerBackupRequest" + "type": "google.cloud.backupdr_v1beta.types.TriggerRestoreVerificationRequest" }, { "name": "name", "type": "str" }, - { - "name": "rule_id", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -7013,13 +9798,13 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "trigger_backup" + "shortName": "trigger_restore_verification" }, - "description": "Sample for TriggerBackup", - "file": "backupdr_v1beta_generated_backup_dr_trigger_backup_sync.py", + "description": "Sample for TriggerRestoreVerification", + "file": "backupdr_v1beta_generated_backup_dr_trigger_restore_verification_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerBackup_sync", + "regionTag": "backupdr_v1beta_generated_BackupDR_TriggerRestoreVerification_sync", "segments": [ { "end": 55, @@ -7052,7 +9837,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "backupdr_v1beta_generated_backup_dr_trigger_backup_sync.py" + "title": "backupdr_v1beta_generated_backup_dr_trigger_restore_verification_sync.py" }, { "canonical": true, @@ -8068,6 +10853,175 @@ ], "title": "backupdr_v1beta_generated_backup_dr_update_data_source_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient", + "shortName": "BackupDRAsyncClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRAsyncClient.update_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateRestoreTemplateRequest" + }, + { + "name": "restore_template", + "type": "google.cloud.backupdr_v1beta.types.RestoreTemplate" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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": "update_restore_template" + }, + "description": "Sample for UpdateRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_update_restore_template_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateRestoreTemplate_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_restore_template_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient", + "shortName": "BackupDRClient" + }, + "fullName": "google.cloud.backupdr_v1beta.BackupDRClient.update_restore_template", + "method": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR.UpdateRestoreTemplate", + "service": { + "fullName": "google.cloud.backupdr.v1beta.BackupDR", + "shortName": "BackupDR" + }, + "shortName": "UpdateRestoreTemplate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.backupdr_v1beta.types.UpdateRestoreTemplateRequest" + }, + { + "name": "restore_template", + "type": "google.cloud.backupdr_v1beta.types.RestoreTemplate" + }, + { + "name": "update_mask", + "type": "google.protobuf.field_mask_pb2.FieldMask" + }, + { + "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": "update_restore_template" + }, + "description": "Sample for UpdateRestoreTemplate", + "file": "backupdr_v1beta_generated_backup_dr_update_restore_template_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "backupdr_v1beta_generated_BackupDR_UpdateRestoreTemplate_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "backupdr_v1beta_generated_backup_dr_update_restore_template_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py index c2127cd8d383..5c6443d3950f 100644 --- a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py +++ b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1/test_backup_dr.py @@ -44,6 +44,7 @@ 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.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore import google.rpc.status_pb2 as status_pb2 # type: ignore @@ -79,6 +80,9 @@ transports, ) from google.cloud.backupdr_v1.types import ( + appliedautoprotectionpolicy, + autoprotectionpolicy, + autoprotectionpolicybinding, backupdr, backupplan, backupplanassociation, @@ -88,7 +92,20 @@ backupvault_cloudsql, backupvault_disk, backupvault_gce, + bindingmatchingresource, datasourcereference, + restore_template, + restore_template_common, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) CRED_INFO_JSON = { @@ -12641,6 +12658,7 @@ def test_get_backup_plan_association(request_type, transport: str = "grpc"): data_source="data_source_value", backup_plan_revision_id="backup_plan_revision_id_value", backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", ) response = client.get_backup_plan_association(request) @@ -12660,6 +12678,10 @@ def test_get_backup_plan_association(request_type, transport: str = "grpc"): assert response.data_source == "data_source_value" assert response.backup_plan_revision_id == "backup_plan_revision_id_value" assert response.backup_plan_revision_name == "backup_plan_revision_name_value" + assert ( + response.auto_protection_policy_binding + == "auto_protection_policy_binding_value" + ) def test_get_backup_plan_association_non_empty_request_with_auto_populated_field(): @@ -12810,6 +12832,7 @@ async def test_get_backup_plan_association_async( data_source="data_source_value", backup_plan_revision_id="backup_plan_revision_id_value", backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", ) ) response = await client.get_backup_plan_association(request) @@ -12830,6 +12853,10 @@ async def test_get_backup_plan_association_async( assert response.data_source == "data_source_value" assert response.backup_plan_revision_id == "backup_plan_revision_id_value" assert response.backup_plan_revision_name == "backup_plan_revision_name_value" + assert ( + response.auto_protection_policy_binding + == "auto_protection_policy_binding_value" + ) def test_get_backup_plan_association_field_headers(): @@ -14206,6 +14233,7 @@ def test_delete_backup_plan_association_non_empty_request_with_auto_populated_fi # if they meet the requirements of AIP 4235. request = backupplanassociation.DeleteBackupPlanAssociationRequest( name="name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -14220,6 +14248,7 @@ def test_delete_backup_plan_association_non_empty_request_with_auto_populated_fi _, args, _ = call.mock_calls[0] request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest( name="name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", ) assert args[0] == request_msg @@ -16641,13 +16670,81 @@ async def test_initialize_service_field_headers_async(): ) in kw["metadata"] -def test_list_management_servers_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + {}, + ], +) +def test_create_auto_protection_policy(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_auto_protection_policy_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 = BackupDRClient( + 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + ) + assert args[0] == request_msg + + +def test_create_auto_protection_policy_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -16656,7 +16753,7 @@ def test_list_management_servers_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_management_servers + client._transport.create_auto_protection_policy in client._transport._wrapped_methods ) @@ -16666,238 +16763,376 @@ def test_list_management_servers_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_management_servers + client._transport.create_auto_protection_policy ] = mock_rpc - request = {} - client.list_management_servers(request) + client.create_auto_protection_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_management_servers(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.create_auto_protection_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_list_management_servers_rest_required_fields( - request_type=backupdr.ListManagementServersRequest, +@pytest.mark.asyncio +async def test_create_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.create_auto_protection_policy + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseListManagementServers, - "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_auto_protection_policy + ] = mock_rpc + + request = {} + await client.create_auto_protection_policy(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.create_auto_protection_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), {}, + ], +) +async def test_create_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - ) + response = await client.create_auto_protection_policy(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + +def test_create_auto_protection_policy_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupdr.ListManagementServersResponse() - # 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 + # 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() - response_value = Response() - response_value.status_code = 200 + request.parent = "parent_value" - # Convert return value to protobuf type - return_value = backupdr.ListManagementServersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.list_management_servers(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_create_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() -def test_list_management_servers_rest_flattened(): + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_auto_protection_policy_flattened(): client = BackupDRClient( 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 = backupdr.ListManagementServersResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_auto_protection_policy( + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # 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].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") + assert arg == mock_val + arg = args[0].auto_protection_policy_id + mock_val = "auto_protection_policy_id_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( + +def test_create_auto_protection_policy_flattened_error(): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_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 = backupdr.ListManagementServersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_management_servers(**mock_args) +@pytest.mark.asyncio +async def test_create_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_auto_protection_policy( + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_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/v1/{parent=projects/*/locations/*}/managementServers" - % client.transport._host, - args[1], - ) + 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].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") + assert arg == mock_val + arg = args[0].auto_protection_policy_id + mock_val = "auto_protection_policy_id_value" + assert arg == mock_val -def test_list_management_servers_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_create_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_management_servers( - backupdr.ListManagementServersRequest(), + await client.create_auto_protection_policy( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", ) -def test_list_management_servers_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + {}, + ], +) +def test_list_auto_protection_policies(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = ( - backupdr.ListManagementServersResponse( - management_servers=[ - backupdr.ManagementServer(), - backupdr.ManagementServer(), - backupdr.ManagementServer(), - ], - next_page_token="abc", - ), - backupdr.ListManagementServersResponse( - management_servers=[], - next_page_token="def", - ), - backupdr.ListManagementServersResponse( - management_servers=[ - backupdr.ManagementServer(), - ], - next_page_token="ghi", - ), - backupdr.ListManagementServersResponse( - management_servers=[ - backupdr.ManagementServer(), - backupdr.ManagementServer(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - backupdr.ListManagementServersResponse.to_json(x) for x in response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 + response = client.list_auto_protection_policies(request) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + assert args[0] == request - pager = client.list_management_servers(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPoliciesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - 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, backupdr.ManagementServer) for i in results) +def test_list_auto_protection_policies_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_management_servers(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest( + 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_auto_protection_policies), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_auto_protection_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg -def test_get_management_server_rest_use_cached_wrapped_rpc(): +def test_list_auto_protection_policies_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -16906,7 +17141,7 @@ def test_get_management_server_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_management_server + client._transport.list_auto_protection_policies in client._transport._wrapped_methods ) @@ -16915,165 +17150,553 @@ def test_get_management_server_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.get_management_server] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.list_auto_protection_policies + ] = mock_rpc request = {} - client.get_management_server(request) + client.list_auto_protection_policies(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_management_server(request) + client.list_auto_protection_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_get_management_server_rest_required_fields( - request_type=backupdr.GetManagementServerRequest, +@pytest.mark.asyncio +async def test_list_auto_protection_policies_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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_auto_protection_policies + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetManagementServer, - "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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_auto_protection_policies + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_auto_protection_policies(request) - jsonified_request["name"] = "name_value" + # 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_auto_protection_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + {}, + ], +) +async def test_list_auto_protection_policies_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + 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_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPoliciesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_auto_protection_policies_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupdr.ManagementServer() - # 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 + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() - response_value = Response() - response_value.status_code = 200 + request.parent = "parent_value" - # Convert return value to protobuf type - return_value = backupdr.ManagementServer.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + client.list_auto_protection_policies(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.get_management_server(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_list_auto_protection_policies_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_get_management_server_rest_flattened(): + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + ) + await client.list_auto_protection_policies(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_auto_protection_policies_flattened(): client = BackupDRClient( 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 = backupdr.ManagementServer() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_auto_protection_policies( + parent="parent_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/managementServers/sample3" - } + # 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 - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + +def test_list_auto_protection_policies_flattened_error(): + client = BackupDRClient( + 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_auto_protection_policies( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + 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 = backupdr.ManagementServer.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_management_server(**mock_args) +@pytest.mark.asyncio +async def test_list_auto_protection_policies_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_auto_protection_policies( + 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/v1/{name=projects/*/locations/*/managementServers/*}" - % client.transport._host, - args[1], + 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_auto_protection_policies_flattened_error_async(): + client = BackupDRAsyncClient( + 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_auto_protection_policies( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + parent="parent_value", ) -def test_get_management_server_rest_flattened_error(transport: str = "rest"): +def test_list_auto_protection_policies_pager(transport_name: str = "grpc"): + client = BackupDRClient( + 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_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_auto_protection_policies( + 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, autoprotectionpolicy.AutoProtectionPolicy) for i in results + ) + + +def test_list_auto_protection_policies_pages(transport_name: str = "grpc"): + client = BackupDRClient( + 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_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_auto_protection_policies(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_auto_protection_policies_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_auto_protection_policies( + 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, autoprotectionpolicy.AutoProtectionPolicy) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_auto_protection_policies_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_auto_protection_policies(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", + [ + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + {}, + ], +) +def test_get_auto_protection_policy(request_type, transport: str = "grpc"): client = BackupDRClient( 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_management_server( - backupdr.GetManagementServerRequest(), + # 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_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.AutoProtectionPolicy( name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_value", ) + response = client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicy.AutoProtectionPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING + assert response.etag == "etag_value" -def test_create_management_server_rest_use_cached_wrapped_rpc(): +def test_get_auto_protection_policy_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 = BackupDRClient( + 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 = autoprotectionpolicy.GetAutoProtectionPolicyRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_auto_protection_policy_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -17082,7 +17705,7 @@ def test_create_management_server_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_management_server + client._transport.get_auto_protection_policy in client._transport._wrapped_methods ) @@ -17092,189 +17715,332 @@ def test_create_management_server_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_management_server + client._transport.get_auto_protection_policy ] = mock_rpc - request = {} - client.create_management_server(request) + client.get_auto_protection_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.create_management_server(request) + client.get_auto_protection_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_create_management_server_rest_required_fields( - request_type=backupdr.CreateManagementServerRequest, +@pytest.mark.asyncio +async def test_get_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["management_server_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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped - assert "managementServerId" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.get_auto_protection_policy + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseCreateManagementServer, - "_BaseCreateManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.get_auto_protection_policy + ] = mock_rpc - # verify required fields with default values are now present - assert "managementServerId" in jsonified_request - assert ( - jsonified_request["managementServerId"] == request_init["management_server_id"] - ) + request = {} + await client.get_auto_protection_policy(request) - jsonified_request["parent"] = "parent_value" - jsonified_request["managementServerId"] = "management_server_id_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "managementServerId", - "requestId", - ) - ) + await client.get_auto_protection_policy(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "managementServerId" in jsonified_request - assert jsonified_request["managementServerId"] == "management_server_id_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + {}, + ], +) +async def test_get_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + 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": "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) + # 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.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy( + name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_value", + ) + ) + response = await client.get_auto_protection_policy(request) - response = client.create_management_server(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + assert args[0] == request - expected_params = [ - ( - "managementServerId", - "", - ), - ("$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, autoprotectionpolicy.AutoProtectionPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING + assert response.etag == "etag_value" -def test_create_management_server_rest_flattened(): +def test_get_auto_protection_policy_field_headers(): client = BackupDRClient( 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") + # 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 = autoprotectionpolicy.GetAutoProtectionPolicyRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - management_server=backupdr.ManagementServer(name="name_value"), - management_server_id="management_server_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + client.get_auto_protection_policy(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_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + 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 = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy() ) - mock_args.update(sample_request) + await client.get_auto_protection_policy(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.create_management_server(**mock_args) + # 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_auto_protection_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_auto_protection_policy( + name="name_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/v1/{parent=projects/*/locations/*}/managementServers" - % 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_create_management_server_rest_flattened_error(transport: str = "rest"): +def test_get_auto_protection_policy_flattened_error(): client = BackupDRClient( 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_management_server( - backupdr.CreateManagementServerRequest(), - parent="parent_value", - management_server=backupdr.ManagementServer(name="name_value"), - management_server_id="management_server_id_value", + client.get_auto_protection_policy( + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + name="name_value", ) -def test_delete_management_server_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_get_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_auto_protection_policy( + 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_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + 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_auto_protection_policy( + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + {}, + ], +) +def test_update_auto_protection_policy(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_auto_protection_policy_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 = BackupDRClient( + 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 = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request_msg + + +def test_update_auto_protection_policy_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -17283,7 +18049,7 @@ def test_delete_management_server_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_management_server + client._transport.update_auto_protection_policy in client._transport._wrapped_methods ) @@ -17293,365 +18059,357 @@ def test_delete_management_server_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_management_server + client._transport.update_auto_protection_policy ] = mock_rpc - request = {} - client.delete_management_server(request) + client.update_auto_protection_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 + # 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_management_server(request) + client.update_auto_protection_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_delete_management_server_rest_required_fields( - request_type=backupdr.DeleteManagementServerRequest, +@pytest.mark.asyncio +async def test_update_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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.update_auto_protection_policy + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseDeleteManagementServer, - "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_auto_protection_policy + ] = mock_rpc + + request = {} + await client.update_auto_protection_policy(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.update_auto_protection_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), {}, + ], +) +async def test_update_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__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.update_auto_protection_policy(request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_update_auto_protection_policy_field_headers(): client = BackupDRClient( 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 + # 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 = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.auto_protection_policy.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.update_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_auto_protection_policy(request) - response = client.delete_management_server(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", + "auto_protection_policy.name=name_value", + ) in kw["metadata"] -def test_delete_management_server_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_update_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/managementServers/sample3" - } + request.auto_protection_policy.name = "name_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.update_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.update_auto_protection_policy(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_management_server(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "auto_protection_policy.name=name_value", + ) in kw["metadata"] + + +def test_update_auto_protection_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__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.update_auto_protection_policy( + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + 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(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/managementServers/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(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_delete_management_server_rest_flattened_error(transport: str = "rest"): +def test_update_auto_protection_policy_flattened_error(): client = BackupDRClient( 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_management_server( - backupdr.DeleteManagementServerRequest(), - name="name_value", + client.update_auto_protection_policy( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_backup_vault_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 = BackupDRClient( - 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_update_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.create_backup_vault in client._transport._wrapped_methods - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # 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( + operations_pb2.Operation(name="operations/spam") ) - client._transport._wrapped_methods[client._transport.create_backup_vault] = ( - mock_rpc + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_auto_protection_policy( + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - request = {} - client.create_backup_vault(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].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(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 - # 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_backup_vault(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_backup_vault_rest_required_fields( - request_type=backupvault.CreateBackupVaultRequest, -): - transport_class = transports.BackupDRRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["backup_vault_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 "backupVaultId" not in jsonified_request - default_values = getattr( - transport_class._BaseCreateBackupVault, - "_BaseCreateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_update_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - assert "backupVaultId" in jsonified_request - assert jsonified_request["backupVaultId"] == request_init["backup_vault_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["backupVaultId"] = "backup_vault_id_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "backupVaultId", - "requestId", - "validateOnly", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_auto_protection_policy( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "backupVaultId" in jsonified_request - assert jsonified_request["backupVaultId"] == "backup_vault_id_value" +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + {}, + ], +) +def test_delete_auto_protection_policy(request_type, transport: str = "grpc"): client = BackupDRClient( 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": "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) + # 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.delete_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_auto_protection_policy(request) - response = client.create_backup_vault(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + assert args[0] == request - expected_params = [ - ( - "backupVaultId", - "", - ), - ("$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, future.Future) -def test_create_backup_vault_rest_flattened(): +def test_delete_auto_protection_policy_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 = BackupDRClient( 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 = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - backup_vault=backupvault.BackupVault(name="name_value"), - backup_vault_id="backup_vault_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_backup_vault(**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/*}/backupVaults" - % client.transport._host, - args[1], - ) - - -def test_create_backup_vault_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest( + name="name_value", + etag="etag_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_backup_vault( - backupvault.CreateBackupVaultRequest(), - parent="parent_value", - backup_vault=backupvault.BackupVault(name="name_value"), - backup_vault_id="backup_vault_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest( + name="name_value", + etag="etag_value", ) + assert args[0] == request_msg -def test_list_backup_vaults_rest_use_cached_wrapped_rpc(): +def test_delete_auto_protection_policy_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -17660,7 +18418,8 @@ def test_list_backup_vaults_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_backup_vaults in client._transport._wrapped_methods + client._transport.delete_auto_protection_policy + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -17668,240 +18427,340 @@ def test_list_backup_vaults_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_backup_vaults] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.delete_auto_protection_policy + ] = mock_rpc request = {} - client.list_backup_vaults(request) + client.delete_auto_protection_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backup_vaults(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.delete_auto_protection_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_list_backup_vaults_rest_required_fields( - request_type=backupvault.ListBackupVaultsRequest, +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.delete_auto_protection_policy + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseListBackupVaults, - "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_auto_protection_policy + ] = mock_rpc + + request = {} + await client.delete_auto_protection_policy(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_auto_protection_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), {}, + ], +) +async def test_delete_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "view", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__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_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_delete_auto_protection_policy_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupvault.ListBackupVaultsResponse() - # 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 + # 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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() - # Convert return value to protobuf type - return_value = backupvault.ListBackupVaultsResponse.pb(return_value) - 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.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_auto_protection_policy(request) - response = client.list_backup_vaults(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_list_backup_vaults_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + 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 = backupvault.ListBackupVaultsResponse() + # 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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.delete_auto_protection_policy(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 = backupvault.ListBackupVaultsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.list_backup_vaults(**mock_args) + # 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_auto_protection_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__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_auto_protection_policy( + name="name_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/v1/{parent=projects/*/locations/*}/backupVaults" - % 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_list_backup_vaults_rest_flattened_error(transport: str = "rest"): +def test_delete_auto_protection_policy_flattened_error(): client = BackupDRClient( 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_vaults( - backupvault.ListBackupVaultsRequest(), - parent="parent_value", + client.delete_auto_protection_policy( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + name="name_value", ) -def test_list_backup_vaults_rest_pager(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = ( - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - next_page_token="abc", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[], - next_page_token="def", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Wrap the values into proper Response objs - response = tuple( - backupvault.ListBackupVaultsResponse.to_json(x) for x in response + 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_auto_protection_policy( + 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"} + # 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 - pager = client.list_backup_vaults(request=sample_request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, backupvault.BackupVault) for i in results) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_auto_protection_policy( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + name="name_value", + ) - pages = list(client.list_backup_vaults(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + {}, + ], +) +def test_create_auto_protection_policy_binding(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_auto_protection_policy_binding(request) -def test_fetch_usable_backup_vaults_rest_use_cached_wrapped_rpc(): + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_auto_protection_policy_binding_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 = BackupDRClient( + 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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_auto_protection_policy_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + assert args[0] == request_msg + + +def test_create_auto_protection_policy_binding_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -17910,7 +18769,7 @@ def test_fetch_usable_backup_vaults_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_usable_backup_vaults + client._transport.create_auto_protection_policy_binding in client._transport._wrapped_methods ) @@ -17920,238 +18779,383 @@ def test_fetch_usable_backup_vaults_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_usable_backup_vaults + client._transport.create_auto_protection_policy_binding ] = mock_rpc - request = {} - client.fetch_usable_backup_vaults(request) + client.create_auto_protection_policy_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_usable_backup_vaults(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.create_auto_protection_policy_binding(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_fetch_usable_backup_vaults_rest_required_fields( - request_type=backupvault.FetchUsableBackupVaultsRequest, +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.create_auto_protection_policy_binding + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseFetchUsableBackupVaults, - "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_auto_protection_policy_binding + ] = mock_rpc + + request = {} + await client.create_auto_protection_policy_binding(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.create_auto_protection_policy_binding(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", + [ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), {}, + ], +) +async def test_create_auto_protection_policy_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - ) + response = await client.create_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_create_auto_protection_policy_binding_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupvault.FetchUsableBackupVaultsResponse() - # 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 + # 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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() - response_value = Response() - response_value.status_code = 200 + request.parent = "parent_value" - # Convert return value to protobuf type - return_value = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy_binding(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.fetch_usable_backup_vaults(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_fetch_usable_backup_vaults_rest_flattened(): + # 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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_auto_protection_policy_binding_flattened(): client = BackupDRClient( 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 = backupvault.FetchUsableBackupVaultsResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_auto_protection_policy_binding( + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # 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].auto_protection_policy_binding + mock_val = autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ) + assert arg == mock_val + arg = args[0].auto_protection_policy_binding_id + mock_val = "auto_protection_policy_binding_id_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( + +def test_create_auto_protection_policy_binding_flattened_error(): + client = BackupDRClient( + 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_auto_protection_policy_binding( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_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 = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.fetch_usable_backup_vaults(**mock_args) +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_auto_protection_policy_binding( + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_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/v1/{parent=projects/*/locations/*}/backupVaults:fetchUsable" - % client.transport._host, - args[1], + 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].auto_protection_policy_binding + mock_val = autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" ) + assert arg == mock_val + arg = args[0].auto_protection_policy_binding_id + mock_val = "auto_protection_policy_binding_id_value" + assert arg == mock_val -def test_fetch_usable_backup_vaults_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_usable_backup_vaults( - backupvault.FetchUsableBackupVaultsRequest(), + await client.create_auto_protection_policy_binding( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", ) -def test_fetch_usable_backup_vaults_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + {}, + ], +) +def test_get_auto_protection_policy_binding(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = ( - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - next_page_token="abc", - ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[], - next_page_token="def", - ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - ], - next_page_token="ghi", - ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - backupvault.FetchUsableBackupVaultsResponse.to_json(x) for x in response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_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 + response = client.get_auto_protection_policy_binding(request) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + assert args[0] == request - pager = client.fetch_usable_backup_vaults(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING + ) + assert response.scope == "scope_value" + assert response.etag == "etag_value" - 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, backupvault.BackupVault) for i in results) +def test_get_auto_protection_policy_binding_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.fetch_usable_backup_vaults(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_auto_protection_policy_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + assert args[0] == request_msg -def test_get_backup_vault_rest_use_cached_wrapped_rpc(): +def test_get_auto_protection_policy_binding_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -18159,175 +19163,367 @@ def test_get_backup_vault_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup_vault in client._transport._wrapped_methods + assert ( + client._transport.get_auto_protection_policy_binding + 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_vault] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.get_auto_protection_policy_binding + ] = mock_rpc request = {} - client.get_backup_vault(request) + client.get_auto_protection_policy_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup_vault(request) + client.get_auto_protection_policy_binding(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_vault_rest_required_fields( - request_type=backupvault.GetBackupVaultRequest, +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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.get_auto_protection_policy_binding + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetBackupVault, - "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.get_auto_protection_policy_binding + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.get_auto_protection_policy_binding(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + await client.get_auto_protection_policy_binding(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", + [ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + {}, + ], +) +async def test_get_auto_protection_policy_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + 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_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_value", + ) + ) + response = await client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING + ) + assert response.scope == "scope_value" + assert response.etag == "etag_value" - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_get_auto_protection_policy_binding_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupvault.BackupVault() - # 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 + # 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 = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() - response_value = Response() - response_value.status_code = 200 + request.name = "name_value" - # Convert return value to protobuf type - return_value = backupvault.BackupVault.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + client.get_auto_protection_policy_binding(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.get_backup_vault(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_get_backup_vault_rest_flattened(): + # 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 = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding() + ) + await client.get_auto_protection_policy_binding(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_auto_protection_policy_binding_flattened(): client = BackupDRClient( 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 = backupvault.BackupVault() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_auto_protection_policy_binding( + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3" - } + # 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 - # get truthy value for each flattened field - mock_args = dict( + +def test_get_auto_protection_policy_binding_flattened_error(): + client = BackupDRClient( + 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_auto_protection_policy_binding( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), 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 = backupvault.BackupVault.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_vault(**mock_args) +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_auto_protection_policy_binding( + name="name_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/v1/{name=projects/*/locations/*/backupVaults/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_get_backup_vault_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_backup_vault( - backupvault.GetBackupVaultRequest(), + await client.get_auto_protection_policy_binding( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), name="name_value", ) -def test_update_backup_vault_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + {}, + ], +) +def test_list_auto_protection_policy_bindings(request_type, transport: str = "grpc"): + client = BackupDRClient( + 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_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_auto_protection_policy_bindings_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 = BackupDRClient( + 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + 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_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_auto_protection_policy_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + ) + assert args[0] == request_msg + + +def test_list_auto_protection_policy_bindings_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -18336,7 +19532,8 @@ def test_update_backup_vault_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_backup_vault in client._transport._wrapped_methods + client._transport.list_auto_protection_policy_bindings + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -18344,361 +19541,567 @@ def test_update_backup_vault_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_backup_vault] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.list_auto_protection_policy_bindings + ] = mock_rpc request = {} - client.update_backup_vault(request) + client.list_auto_protection_policy_bindings(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_backup_vault(request) + client.list_auto_protection_policy_bindings(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_backup_vault_rest_required_fields( - request_type=backupvault.UpdateBackupVaultRequest, +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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_auto_protection_policy_bindings + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseUpdateBackupVault, - "_BaseUpdateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_auto_protection_policy_bindings + ] = mock_rpc + + request = {} + await client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_auto_protection_policy_bindings(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", + [ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), {}, + ], +) +async def test_list_auto_protection_policy_bindings_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "force", - "forceUpdateAccessRestriction", - "requestId", - "updateMask", - "validateOnly", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - ) + response = await client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - # verify required fields with non-default values are left alone +def test_list_auto_protection_policy_bindings_field_headers(): client = BackupDRClient( 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + client.list_auto_protection_policy_bindings(request) - response = client.update_backup_vault(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", + "parent=parent_value", + ) in kw["metadata"] -def test_update_backup_vault_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "backup_vault": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3" - } - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - backup_vault=backupvault.BackupVault(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.list_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() ) - mock_args.update(sample_request) + await client.list_auto_protection_policy_bindings(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.update_backup_vault(**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_auto_protection_policy_bindings_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_auto_protection_policy_bindings( + 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/v1/{backup_vault.name=projects/*/locations/*/backupVaults/*}" - % 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_update_backup_vault_rest_flattened_error(transport: str = "rest"): +def test_list_auto_protection_policy_bindings_flattened_error(): client = BackupDRClient( 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_backup_vault( - backupvault.UpdateBackupVaultRequest(), - backup_vault=backupvault.BackupVault(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_auto_protection_policy_bindings( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + parent="parent_value", ) -def test_delete_backup_vault_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 = BackupDRClient( - 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_auto_protection_policy_bindings_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.delete_backup_vault 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_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() ) - # 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( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() ) - client._transport._wrapped_methods[client._transport.delete_backup_vault] = ( - mock_rpc + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_auto_protection_policy_bindings( + parent="parent_value", ) - request = {} - client.delete_backup_vault(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() + # 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 - client.delete_backup_vault(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_auto_protection_policy_bindings_flattened_error_async(): + client = BackupDRAsyncClient( + 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_auto_protection_policy_bindings( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + parent="parent_value", + ) -def test_delete_backup_vault_rest_required_fields( - request_type=backupvault.DeleteBackupVaultRequest, -): - transport_class = transports.BackupDRRestTransport - 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_auto_protection_policy_bindings_pager(transport_name: str = "grpc"): + client = BackupDRClient( + 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_auto_protection_policy_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, + ) - default_values = getattr( - transport_class._BaseDeleteBackupVault, - "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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_auto_protection_policy_bindings( + 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__}<") - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allowMissing", - "etag", - "force", - "ignoreBackupPlanReferences", - "requestId", - "validateOnly", + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + 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_auto_protection_policy_bindings_pages(transport_name: str = "grpc"): client = BackupDRClient( 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": "delete", - "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_auto_protection_policy_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, + ) + pages = list(client.list_auto_protection_policy_bindings(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_auto_protection_policy_bindings_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - response = client.delete_backup_vault(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_auto_protection_policy_bindings( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - expected_params = [("$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, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + for i in responses + ) -def test_delete_backup_vault_rest_flattened(): +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_auto_protection_policy_bindings(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", + [ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + {}, + ], +) +def test_list_applied_auto_protection_policies(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3" - } + # 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( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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"} + response = client.list_applied_auto_protection_policies(request) - client.delete_backup_vault(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + 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/v1/{name=projects/*/locations/*/backupVaults/*}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppliedAutoProtectionPoliciesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_delete_backup_vault_rest_flattened_error(transport: str = "rest"): +def test_list_applied_auto_protection_policies_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 = BackupDRClient( 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.delete_backup_vault( - backupvault.DeleteBackupVaultRequest(), - 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + 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_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_applied_auto_protection_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) ) + assert args[0] == request_msg -def test_list_data_sources_rest_use_cached_wrapped_rpc(): +def test_list_applied_auto_protection_policies_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -18706,421 +20109,570 @@ def test_list_data_sources_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_data_sources in client._transport._wrapped_methods + assert ( + client._transport.list_applied_auto_protection_policies + 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_data_sources] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.list_applied_auto_protection_policies + ] = mock_rpc request = {} - client.list_data_sources(request) + client.list_applied_auto_protection_policies(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_sources(request) + client.list_applied_auto_protection_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_list_data_sources_rest_required_fields( - request_type=backupvault.ListDataSourcesRequest, +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport - - 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) - ) + # Clients should use _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 = BackupDRAsyncClient( + 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() - default_values = getattr( - transport_class._BaseListDataSources, - "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.list_applied_auto_protection_policies + 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_applied_auto_protection_policies + ] = mock_rpc - jsonified_request["parent"] = "parent_value" + request = {} + await client.list_applied_auto_protection_policies(request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) + # 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 "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + await client.list_applied_auto_protection_policies(request) - client = BackupDRClient( - 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 = backupvault.ListDataSourcesResponse() - # 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", + [ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + {}, + ], +) +async def test_list_applied_auto_protection_policies_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Convert return value to protobuf type - return_value = backupvault.ListDataSourcesResponse.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_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_applied_auto_protection_policies(request) - response = client.list_data_sources(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + 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.ListAppliedAutoProtectionPoliciesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_list_data_sources_rest_flattened(): +def test_list_applied_auto_protection_policies_field_headers(): client = BackupDRClient( 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 = backupvault.ListDataSourcesResponse() + # 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() ) - mock_args.update(sample_request) + client.list_applied_auto_protection_policies(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 = backupvault.ListDataSourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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] + assert args[0] == request - client.list_data_sources(**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"] + + +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_field_headers_async(): + client = BackupDRAsyncClient( + 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + await client.list_applied_auto_protection_policies(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_applied_auto_protection_policies_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_applied_auto_protection_policies( + 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/v1/{parent=projects/*/locations/*/backupVaults/*}/dataSources" - % 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_list_data_sources_rest_flattened_error(transport: str = "rest"): +def test_list_applied_auto_protection_policies_flattened_error(): client = BackupDRClient( 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_data_sources( - backupvault.ListDataSourcesRequest(), + client.list_applied_auto_protection_policies( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), parent="parent_value", ) -def test_list_data_sources_rest_pager(transport: str = "rest"): +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_applied_auto_protection_policies( + 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_applied_auto_protection_policies_flattened_error_async(): + client = BackupDRAsyncClient( + 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_applied_auto_protection_policies( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_applied_auto_protection_policies_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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 = ( - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), - backupvault.DataSource(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), ], next_page_token="abc", ), - backupvault.ListDataSourcesResponse( - data_sources=[], + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], next_page_token="def", ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), ], next_page_token="ghi", ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - backupvault.ListDataSourcesResponse.to_json(x) for x in response + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_applied_auto_protection_policies( + request={}, retry=retry, timeout=timeout ) - 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/backupVaults/sample3" - } - pager = client.list_data_sources(request=sample_request) + 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, backupvault.DataSource) for i in results) - - pages = list(client.list_data_sources(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_get_data_source_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + assert all( + isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + for i in results ) - # 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_data_source in client._transport._wrapped_methods +def test_list_applied_auto_protection_policies_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) - # 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. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, ) - client._transport._wrapped_methods[client._transport.get_data_source] = mock_rpc - - request = {} - client.get_data_source(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + pages = list(client.list_applied_auto_protection_policies(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - client.get_data_source(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_applied_auto_protection_policies_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_applied_auto_protection_policies( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") -def test_get_data_source_rest_required_fields( - request_type=backupvault.GetDataSourceRequest, -): - transport_class = transports.BackupDRRestTransport + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - 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) - ) + assert len(responses) == 6 + assert all( + isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + for i in responses + ) - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseGetDataSource, - "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_applied_auto_protection_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # 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", + [ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + {}, + ], +) +def test_initiate_delete_auto_protection_policy_binding( + request_type, transport: str = "grpc" +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupvault.DataSource() - # 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 = backupvault.DataSource.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.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.initiate_delete_auto_protection_policy_binding(request) - response = client.get_data_source(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + 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, future.Future) -def test_get_data_source_rest_flattened(): +def test_initiate_delete_auto_protection_policy_binding_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 = BackupDRClient( 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 = backupvault.DataSource() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( + # 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 = ( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( name="name_value", + etag="etag_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 = backupvault.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_data_source(**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/*/backupVaults/*/dataSources/*}" - % client.transport._host, - args[1], - ) - - -def test_get_data_source_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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_data_source( - backupvault.GetDataSourceRequest(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.initiate_delete_auto_protection_policy_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( name="name_value", + etag="etag_value", ) + assert args[0] == request_msg -def test_update_data_source_rest_use_cached_wrapped_rpc(): +def test_initiate_delete_auto_protection_policy_binding_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -19129,7 +20681,8 @@ def test_update_data_source_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_data_source in client._transport._wrapped_methods + client._transport.initiate_delete_auto_protection_policy_binding + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -19137,419 +20690,358 @@ def test_update_data_source_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_data_source] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.initiate_delete_auto_protection_policy_binding + ] = mock_rpc request = {} - client.update_data_source(request) + client.initiate_delete_auto_protection_policy_binding(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 + # 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.update_data_source(request) + client.initiate_delete_auto_protection_policy_binding(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_data_source_rest_required_fields( - request_type=backupvault.UpdateDataSourceRequest, +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.initiate_delete_auto_protection_policy_binding + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseUpdateDataSource, - "_BaseUpdateDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.initiate_delete_auto_protection_policy_binding + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.initiate_delete_auto_protection_policy_binding(request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allowMissing", - "requestId", - "updateMask", - ) - ) + # 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 - - client = BackupDRClient( - 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"} + # 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.update_data_source(request) + await client.initiate_delete_auto_protection_policy_binding(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_update_data_source_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + {}, + ], +) +async def test_initiate_delete_auto_protection_policy_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + 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 = { - "data_source": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } - } + # 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( - data_source=backupvault.DataSource(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.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - 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"} + response = await client.initiate_delete_auto_protection_policy_binding(request) - client.update_data_source(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + 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/v1/{data_source.name=projects/*/locations/*/backupVaults/*/dataSources/*}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_update_data_source_rest_flattened_error(transport: str = "rest"): +def test_initiate_delete_auto_protection_policy_binding_field_headers(): client = BackupDRClient( 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_data_source( - backupvault.UpdateDataSourceRequest(), - data_source=backupvault.DataSource(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = BackupDRClient( - 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 + # 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 = ( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + ) - # 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.name = "name_value" - request = {} - client.list_backups(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initiate_delete_auto_protection_policy_binding(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 + 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"] -def test_list_backups_rest_required_fields(request_type=backupvault.ListBackupsRequest): - transport_class = transports.BackupDRRestTransport - 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) +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped - - default_values = getattr( - transport_class._BaseListBackups, - "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, + # 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 = ( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + request.name = "name_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "view", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - ) + await client.initiate_delete_auto_protection_policy_binding(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"] - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_initiate_delete_auto_protection_policy_binding_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupvault.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 = backupvault.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) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__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.initiate_delete_auto_protection_policy_binding( + name="name_value", + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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_list_backups_rest_flattened(): +def test_initiate_delete_auto_protection_policy_binding_flattened_error(): client = BackupDRClient( 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 = backupvault.ListBackupsResponse() + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.initiate_delete_auto_protection_policy_binding( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = backupvault.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"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - client.list_backups(**mock_args) + 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.initiate_delete_auto_protection_policy_binding( + name="name_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/v1/{parent=projects/*/locations/*/backupVaults/*/dataSources/*}/backups" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_list_backups_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backups( - backupvault.ListBackupsRequest(), - parent="parent_value", + await client.initiate_delete_auto_protection_policy_binding( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + name="name_value", ) -def test_list_backups_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + {}, + ], +) +def test_list_binding_matching_resources(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = ( - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), - ], - next_page_token="abc", - ), - backupvault.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - ], - ), + # 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_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) ) - # Two responses for two calls - response = response + response + response = client.list_binding_matching_resources(request) - # Wrap the values into proper Response objs - response = tuple(backupvault.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 + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request - sample_request = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBindingMatchingResourcesPager) + assert response.next_page_token == "next_page_token_value" - pager = client.list_backups(request=sample_request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") +def test_list_binding_matching_resources_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, backupvault.Backup) 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) - 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_binding_matching_resources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg -def test_fetch_backups_for_resource_type_rest_use_cached_wrapped_rpc(): +def test_list_binding_matching_resources_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -19558,7 +21050,7 @@ def test_fetch_backups_for_resource_type_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_backups_for_resource_type + client._transport.list_binding_matching_resources in client._transport._wrapped_methods ) @@ -19568,263 +21060,551 @@ def test_fetch_backups_for_resource_type_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_backups_for_resource_type + client._transport.list_binding_matching_resources ] = mock_rpc - request = {} - client.fetch_backups_for_resource_type(request) + client.list_binding_matching_resources(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_backups_for_resource_type(request) + client.list_binding_matching_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_fetch_backups_for_resource_type_rest_required_fields( - request_type=backupvault.FetchBackupsForResourceTypeRequest, +@pytest.mark.asyncio +async def test_list_binding_matching_resources_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["resource_type"] = "" - 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 - assert "resourceType" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.list_binding_matching_resources + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseFetchBackupsForResourceType, - "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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_binding_matching_resources + ] = mock_rpc - # verify required fields with default values are now present - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == request_init["resource_type"] + request = {} + await client.list_binding_matching_resources(request) - jsonified_request["parent"] = "parent_value" - jsonified_request["resourceType"] = "resource_type_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "resourceType", - "view", - ) + await client.list_binding_matching_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + {}, + ], +) +async def test_list_binding_matching_resources_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == "resource_type_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 + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBindingMatchingResourcesAsyncPager) + assert response.next_page_token == "next_page_token_value" + +def test_list_binding_matching_resources_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupvault.FetchBackupsForResourceTypeResponse() - # 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 + # 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest() - response_value = Response() - response_value.status_code = 200 + request.parent = "parent_value" - # Convert return value to protobuf type - return_value = backupvault.FetchBackupsForResourceTypeResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + client.list_binding_matching_resources(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.fetch_backups_for_resource_type(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - expected_params = [ - ( - "resourceType", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_list_binding_matching_resources_field_headers_async(): + client = BackupDRAsyncClient( + 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest() -def test_fetch_backups_for_resource_type_rest_flattened(): + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + await client.list_binding_matching_resources(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_binding_matching_resources_flattened(): client = BackupDRClient( 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 = backupvault.FetchBackupsForResourceTypeResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_binding_matching_resources( + parent="parent_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } + # 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 - # get truthy value for each flattened field - mock_args = dict( + +def test_list_binding_matching_resources_flattened_error(): + client = BackupDRClient( + 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_binding_matching_resources( + bindingmatchingresource.ListBindingMatchingResourcesRequest(), parent="parent_value", - resource_type="resource_type_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 = backupvault.FetchBackupsForResourceTypeResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.fetch_backups_for_resource_type(**mock_args) +@pytest.mark.asyncio +async def test_list_binding_matching_resources_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_binding_matching_resources( + 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/v1/{parent=projects/*/locations/*/backupVaults/*/dataSources/*}/backups:fetchForResourceType" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_fetch_backups_for_resource_type_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_binding_matching_resources_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_backups_for_resource_type( - backupvault.FetchBackupsForResourceTypeRequest(), + await client.list_binding_matching_resources( + bindingmatchingresource.ListBindingMatchingResourcesRequest(), parent="parent_value", - resource_type="resource_type_value", ) -def test_fetch_backups_for_resource_type_rest_pager(transport: str = "rest"): +def test_list_binding_matching_resources_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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 = ( - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), ], next_page_token="abc", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[], + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], next_page_token="def", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), ], next_page_token="ghi", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - backupvault.FetchBackupsForResourceTypeResponse.to_json(x) for x in response + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_binding_matching_resources( + request={}, retry=retry, timeout=timeout ) - 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/backupVaults/sample3/dataSources/sample4" - } - pager = client.fetch_backups_for_resource_type(request=sample_request) + 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, backupvault.Backup) for i in results) + assert all( + isinstance(i, bindingmatchingresource.BindingMatchingResource) + for i in results + ) - pages = list( - client.fetch_backups_for_resource_type(request=sample_request).pages + +def test_list_binding_matching_resources_pages(transport_name: str = "grpc"): + client = BackupDRClient( + 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_binding_matching_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, ) + pages = list(client.list_binding_matching_resources(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(): +@pytest.mark.asyncio +async def test_list_binding_matching_resources_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_binding_matching_resources( + 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, bindingmatchingresource.BindingMatchingResource) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_binding_matching_resources_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_binding_matching_resources(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", + [ + gcb_restore_template.CreateRestoreTemplateRequest(), + {}, + ], +) +def test_create_restore_template(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_restore_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcb_restore_template.CreateRestoreTemplateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_restore_template_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 = BackupDRClient( + 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 = gcb_restore_template.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_restore_template(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.CreateRestoreTemplateRequest( + parent="parent_value", + restore_template_id="restore_template_id_value", + ) + assert args[0] == request_msg + + +def test_create_restore_template_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -19832,349 +21612,379 @@ def test_get_backup_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup in client._transport._wrapped_methods + assert ( + client._transport.create_restore_template + 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 - + client._transport._wrapped_methods[ + client._transport.create_restore_template + ] = mock_rpc request = {} - client.get_backup(request) + client.create_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup(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.create_restore_template(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=backupvault.GetBackupRequest): - transport_class = transports.BackupDRRestTransport +@pytest.mark.asyncio +async def test_create_restore_template_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 = BackupDRAsyncClient( + 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.create_restore_template + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetBackup, - "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.create_restore_template + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.create_restore_template(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + # 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() - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + await client.create_restore_template(request) - client = BackupDRClient( - 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 = backupvault.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 +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + gcb_restore_template.CreateRestoreTemplateRequest(), + {}, + ], +) +async def test_create_restore_template_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Convert return value to protobuf type - return_value = backupvault.Backup.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.create_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_restore_template(request) - response = client.get_backup(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcb_restore_template.CreateRestoreTemplateRequest() + 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, future.Future) -def test_get_backup_rest_flattened(): +def test_create_restore_template_field_headers(): client = BackupDRClient( 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 = backupvault.Backup() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" - } + # 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 = gcb_restore_template.CreateRestoreTemplateRequest() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + request.parent = "parent_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 = backupvault.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"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_template(request) - client.get_backup(**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 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/*/backupVaults/*/dataSources/*/backups/*}" - % client.transport._host, - args[1], - ) + # 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_get_backup_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_create_restore_template_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_backup( - backupvault.GetBackupRequest(), - name="name_value", - ) - - -def test_update_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # 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 = gcb_restore_template.CreateRestoreTemplateRequest() - # Ensure method has been cached - assert client._transport.update_backup in client._transport._wrapped_methods + request.parent = "parent_value" - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - client._transport._wrapped_methods[client._transport.update_backup] = mock_rpc - - request = {} - client.update_backup(request) + await client.create_restore_template(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() + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.update_backup(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # 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_restore_template_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) -def test_update_backup_rest_required_fields( - request_type=backupvault.UpdateBackupRequest, -): - transport_class = transports.BackupDRRestTransport + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_restore_template( + parent="parent_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", + ) - 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) - ) + # 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].restore_template + mock_val = gcb_restore_template.RestoreTemplate(name="name_value") + assert arg == mock_val + arg = args[0].restore_template_id + mock_val = "restore_template_id_value" + assert arg == mock_val - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseUpdateBackup, - "_BaseUpdateBackup__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +def test_create_restore_template_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_restore_template( + gcb_restore_template.CreateRestoreTemplateRequest(), + parent="parent_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", ) - ) - # verify required fields with non-default values are left alone - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_create_restore_template_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_restore_template( + parent="parent_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", + ) - response_value._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 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].restore_template + mock_val = gcb_restore_template.RestoreTemplate(name="name_value") + assert arg == mock_val + arg = args[0].restore_template_id + mock_val = "restore_template_id_value" + assert arg == mock_val - response = client.update_backup(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_create_restore_template_flattened_error_async(): + client = BackupDRAsyncClient( + 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_restore_template( + gcb_restore_template.CreateRestoreTemplateRequest(), + parent="parent_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", + ) -def test_update_backup_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + restore_template.GetRestoreTemplateRequest(), + {}, + ], +) +def test_get_restore_template(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = { - "backup": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" - } - } + # 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( - backup=backupvault.Backup(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_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_template.RestoreTemplate( + name="name_value", + description="description_value", + resource_type="resource_type_value", + state=restore_template.RestoreTemplate.State.CREATING, + etag="etag_value", ) - mock_args.update(sample_request) + response = client.get_restore_template(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_backup(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_template.GetRestoreTemplateRequest() + 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/v1/{backup.name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, restore_template.RestoreTemplate) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.resource_type == "resource_type_value" + assert response.state == restore_template.RestoreTemplate.State.CREATING + assert response.etag == "etag_value" -def test_update_backup_rest_flattened_error(transport: str = "rest"): +def test_get_restore_template_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 = BackupDRClient( 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.update_backup( - backupvault.UpdateBackupRequest(), - backup=backupvault.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = restore_template.GetRestoreTemplateRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_restore_template(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.GetRestoreTemplateRequest( + name="name_value", ) + assert args[0] == request_msg -def test_delete_backup_rest_use_cached_wrapped_rpc(): +def test_get_restore_template_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -20182,343 +21992,359 @@ def test_delete_backup_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_backup in client._transport._wrapped_methods + assert ( + client._transport.get_restore_template 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 - + client._transport._wrapped_methods[client._transport.get_restore_template] = ( + mock_rpc + ) request = {} - client.delete_backup(request) + client.get_restore_template(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) + client.get_restore_template(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=backupvault.DeleteBackupRequest, +@pytest.mark.asyncio +async def test_get_restore_template_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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.get_restore_template + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseDeleteBackup, - "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_restore_template + ] = mock_rpc + + request = {} + await client.get_restore_template(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_restore_template(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", + [ + restore_template.GetRestoreTemplateRequest(), {}, + ], +) +async def test_get_restore_template_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template.RestoreTemplate( + name="name_value", + description="description_value", + resource_type="resource_type_value", + state=restore_template.RestoreTemplate.State.CREATING, + etag="etag_value", + ) + ) + response = await client.get_restore_template(request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_template.GetRestoreTemplateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, restore_template.RestoreTemplate) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.resource_type == "resource_type_value" + assert response.state == restore_template.RestoreTemplate.State.CREATING + assert response.etag == "etag_value" - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_get_restore_template_field_headers(): client = BackupDRClient( 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 + # 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 = restore_template.GetRestoreTemplateRequest() - 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_restore_template), "__call__" + ) as call: + call.return_value = restore_template.RestoreTemplate() + client.get_restore_template(request) - 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] + 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_delete_backup_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_restore_template_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = restore_template.GetRestoreTemplateRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" - } + request.name = "name_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.get_restore_template), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template.RestoreTemplate() ) - mock_args.update(sample_request) + await client.get_restore_template(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_backup(**mock_args) + # 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_restore_template_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_template.RestoreTemplate() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_restore_template( + name="name_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/v1/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" - % 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_delete_backup_rest_flattened_error(transport: str = "rest"): +def test_get_restore_template_flattened_error(): client = BackupDRClient( 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( - backupvault.DeleteBackupRequest(), + client.get_restore_template( + restore_template.GetRestoreTemplateRequest(), name="name_value", ) -def test_restore_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 = BackupDRClient( - 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_restore_template_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.restore_backup 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_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_template.RestoreTemplate() - # 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( + restore_template.RestoreTemplate() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_restore_template( + name="name_value", ) - client._transport._wrapped_methods[client._transport.restore_backup] = mock_rpc - - request = {} - client.restore_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.restore_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_restore_backup_rest_required_fields( - request_type=backupvault.RestoreBackupRequest, -): - transport_class = transports.BackupDRRestTransport - 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) - ) + # 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 - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseRestoreBackup, - "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_get_restore_template_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["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.get_restore_template( + restore_template.GetRestoreTemplateRequest(), + 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", + [ + restore_template.ListRestoreTemplatesRequest(), + {}, + ], +) +def test_list_restore_templates(request_type, transport: str = "grpc"): client = BackupDRClient( 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": "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) + # 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_restore_templates), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_template.ListRestoreTemplatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_restore_templates(request) - response = client.restore_backup(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_template.ListRestoreTemplatesRequest() + 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.ListRestoreTemplatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_restore_backup_rest_flattened(): +def test_list_restore_templates_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 = BackupDRClient( 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/backupVaults/sample3/dataSources/sample4/backups/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.restore_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/v1/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}:restore" - % client.transport._host, - args[1], - ) - - -def test_restore_backup_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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 = restore_template.ListRestoreTemplatesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.restore_backup( - backupvault.RestoreBackupRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_restore_templates(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.ListRestoreTemplatesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) + assert args[0] == request_msg -def test_create_backup_plan_rest_use_cached_wrapped_rpc(): +def test_list_restore_templates_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -20527,7 +22353,8 @@ def test_create_backup_plan_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_backup_plan in client._transport._wrapped_methods + client._transport.list_restore_templates + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -20535,370 +22362,532 @@ def test_create_backup_plan_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.create_backup_plan] = ( + client._transport._wrapped_methods[client._transport.list_restore_templates] = ( mock_rpc ) - request = {} - client.create_backup_plan(request) + client.list_restore_templates(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_backup_plan(request) + client.list_restore_templates(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_backup_plan_rest_required_fields( - request_type=backupplan.CreateBackupPlanRequest, +@pytest.mark.asyncio +async def test_list_restore_templates_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["backup_plan_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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped - assert "backupPlanId" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.list_restore_templates + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseCreateBackupPlan, - "_BaseCreateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_restore_templates + ] = mock_rpc + + request = {} + await client.list_restore_templates(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_restore_templates(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", + [ + restore_template.ListRestoreTemplatesRequest(), {}, + ], +) +async def test_list_restore_templates_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "backupPlanId" in jsonified_request - assert jsonified_request["backupPlanId"] == request_init["backup_plan_id"] - jsonified_request["parent"] = "parent_value" - jsonified_request["backupPlanId"] = "backup_plan_id_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "backupPlanId", - "requestId", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template.ListRestoreTemplatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - ) + response = await client.list_restore_templates(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "backupPlanId" in jsonified_request - assert jsonified_request["backupPlanId"] == "backup_plan_id_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_template.ListRestoreTemplatesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreTemplatesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + +def test_list_restore_templates_field_headers(): client = BackupDRClient( 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 + # 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 = restore_template.ListRestoreTemplatesRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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_restore_templates), "__call__" + ) as call: + call.return_value = restore_template.ListRestoreTemplatesResponse() + client.list_restore_templates(request) - response = client.create_backup_plan(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 = [ - ( - "backupPlanId", - "", - ), - ("$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", + "parent=parent_value", + ) in kw["metadata"] -def test_create_backup_plan_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_restore_templates_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = restore_template.ListRestoreTemplatesRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - backup_plan=backupplan.BackupPlan(name="name_value"), - backup_plan_id="backup_plan_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template.ListRestoreTemplatesResponse() ) - mock_args.update(sample_request) + await client.list_restore_templates(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.create_backup_plan(**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_restore_templates_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_template.ListRestoreTemplatesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_restore_templates( + 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/v1/{parent=projects/*/locations/*}/backupPlans" - % 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_create_backup_plan_rest_flattened_error(transport: str = "rest"): +def test_list_restore_templates_flattened_error(): client = BackupDRClient( 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_backup_plan( - backupplan.CreateBackupPlanRequest(), + client.list_restore_templates( + restore_template.ListRestoreTemplatesRequest(), parent="parent_value", - backup_plan=backupplan.BackupPlan(name="name_value"), - backup_plan_id="backup_plan_id_value", ) -def test_update_backup_plan_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 = BackupDRClient( - 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_restore_templates_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.update_backup_plan 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_restore_templates), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_template.ListRestoreTemplatesResponse() - # 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( + restore_template.ListRestoreTemplatesResponse() ) - client._transport._wrapped_methods[client._transport.update_backup_plan] = ( - mock_rpc + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_restore_templates( + parent="parent_value", ) - request = {} - client.update_backup_plan(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_backup_plan(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_backup_plan_rest_required_fields( - request_type=backupplan.UpdateBackupPlanRequest, -): - transport_class = transports.BackupDRRestTransport - - 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) - ) + # 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 - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseUpdateBackupPlan, - "_BaseUpdateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_list_restore_templates_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_restore_templates( + restore_template.ListRestoreTemplatesRequest(), + parent="parent_value", ) - ) - # verify required fields with non-default values are left alone +def test_list_restore_templates_pager(transport_name: str = "grpc"): client = BackupDRClient( 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": "patch", - "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_restore_templates), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + next_page_token="abc", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], + next_page_token="def", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + ], + next_page_token="ghi", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + ), + RuntimeError, + ) - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_restore_templates(request={}, retry=retry, timeout=timeout) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - response = client.update_backup_plan(request) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, restore_template.RestoreTemplate) for i in results) -def test_update_backup_plan_rest_flattened(): +def test_list_restore_templates_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # 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") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + next_page_token="abc", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], + next_page_token="def", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + ], + next_page_token="ghi", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + ), + RuntimeError, + ) + pages = list(client.list_restore_templates(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # get arguments that satisfy an http rule for this method - sample_request = { - "backup_plan": { - "name": "projects/sample1/locations/sample2/backupPlans/sample3" - } - } - # get truthy value for each flattened field - mock_args = dict( - backup_plan=backupplan.BackupPlan(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), +@pytest.mark.asyncio +async def test_list_restore_templates_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + next_page_token="abc", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], + next_page_token="def", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + ], + next_page_token="ghi", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + ), + RuntimeError, ) - mock_args.update(sample_request) + async_pager = await client.list_restore_templates( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - # 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"} + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - client.update_backup_plan(**mock_args) + assert len(responses) == 6 + assert all(isinstance(i, restore_template.RestoreTemplate) for i in responses) - # 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/{backup_plan.name=projects/*/locations/*/backupPlans/*}" - % client.transport._host, - args[1], + +@pytest.mark.asyncio +async def test_list_restore_templates_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + next_page_token="abc", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], + next_page_token="def", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + ], + next_page_token="ghi", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_restore_templates(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_update_backup_plan_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + gcb_restore_template.UpdateRestoreTemplateRequest(), + {}, + ], +) +def test_update_restore_template(request_type, transport: str = "grpc"): client = BackupDRClient( 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_backup_plan( - backupplan.UpdateBackupPlanRequest(), - backup_plan=backupplan.BackupPlan(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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 + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_restore_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcb_restore_template.UpdateRestoreTemplateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_restore_template_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 = BackupDRClient( + 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 = gcb_restore_template.UpdateRestoreTemplateRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client.update_restore_template(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.UpdateRestoreTemplateRequest() + assert args[0] == request_msg -def test_get_backup_plan_rest_use_cached_wrapped_rpc(): +def test_update_restore_template_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -20906,417 +22895,406 @@ def test_get_backup_plan_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup_plan in client._transport._wrapped_methods + assert ( + client._transport.update_restore_template + 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_plan] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.update_restore_template + ] = mock_rpc request = {} - client.get_backup_plan(request) + client.update_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup_plan(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.update_restore_template(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_plan_rest_required_fields( - request_type=backupplan.GetBackupPlanRequest, +@pytest.mark.asyncio +async def test_update_restore_template_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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.update_restore_template + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetBackupPlan, - "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.update_restore_template + ] = mock_rpc + + request = {} + await client.update_restore_template(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.update_restore_template(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", + [ + gcb_restore_template.UpdateRestoreTemplateRequest(), {}, + ], +) +async def test_update_restore_template_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__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.update_restore_template(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcb_restore_template.UpdateRestoreTemplateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_update_restore_template_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupplan.BackupPlan() - # 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 + # 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 = gcb_restore_template.UpdateRestoreTemplateRequest() - response_value = Response() - response_value.status_code = 200 + request.restore_template.name = "name_value" - # Convert return value to protobuf type - return_value = backupplan.BackupPlan.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_restore_template(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"} - - response = client.get_backup_plan(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", + "restore_template.name=name_value", + ) in kw["metadata"] -def test_get_backup_plan_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_update_restore_template_field_headers_async(): + client = BackupDRAsyncClient( + 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 = backupplan.BackupPlan() + # 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 = gcb_restore_template.UpdateRestoreTemplateRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlans/sample3" - } + request.restore_template.name = "name_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.update_restore_template), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.update_restore_template(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 = backupplan.BackupPlan.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_backup_plan(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "restore_template.name=name_value", + ) in kw["metadata"] + + +def test_update_restore_template_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__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.update_restore_template( + restore_template=gcb_restore_template.RestoreTemplate(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(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/backupPlans/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].restore_template + mock_val = gcb_restore_template.RestoreTemplate(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_get_backup_plan_rest_flattened_error(transport: str = "rest"): +def test_update_restore_template_flattened_error(): client = BackupDRClient( 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_plan( - backupplan.GetBackupPlanRequest(), - name="name_value", + client.update_restore_template( + gcb_restore_template.UpdateRestoreTemplateRequest(), + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_backup_plans_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 = BackupDRClient( - 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_update_restore_template_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.list_backup_plans in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # 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( + operations_pb2.Operation(name="operations/spam") ) - client._transport._wrapped_methods[client._transport.list_backup_plans] = ( - mock_rpc + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_restore_template( + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - request = {} - client.list_backup_plans(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_backup_plans(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_plans_rest_required_fields( - request_type=backupplan.ListBackupPlansRequest, -): - transport_class = transports.BackupDRRestTransport - - 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) - ) + # 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].restore_template + mock_val = gcb_restore_template.RestoreTemplate(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 - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseListBackupPlans, - "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_update_restore_template_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_restore_template( + gcb_restore_template.UpdateRestoreTemplateRequest(), + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +@pytest.mark.parametrize( + "request_type", + [ + restore_template.DeleteRestoreTemplateRequest(), + {}, + ], +) +def test_delete_restore_template(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupplan.ListBackupPlansResponse() - # 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 = backupplan.ListBackupPlansResponse.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.delete_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_restore_template(request) - response = client.list_backup_plans(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_template.DeleteRestoreTemplateRequest() + 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, future.Future) -def test_list_backup_plans_rest_flattened(): +def test_delete_restore_template_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 = BackupDRClient( 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 = backupplan.ListBackupPlansResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # 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 = restore_template.DeleteRestoreTemplateRequest( + name="name_value", + ) - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - 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 = backupplan.ListBackupPlansResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_plans(**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/*}/backupPlans" - % client.transport._host, - args[1], + client.delete_restore_template(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.DeleteRestoreTemplateRequest( + name="name_value", ) + assert args[0] == request_msg -def test_list_backup_plans_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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_plans( - backupplan.ListBackupPlansRequest(), - parent="parent_value", +def test_delete_restore_template_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 = BackupDRClient( + 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_list_backup_plans_rest_pager(transport: str = "rest"): - client = BackupDRClient( - 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 = ( - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), - backupplan.BackupPlan(), - ], - next_page_token="abc", - ), - backupplan.ListBackupPlansResponse( - backup_plans=[], - next_page_token="def", - ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - ], - next_page_token="ghi", - ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), - ], - ), + # Ensure method has been cached + assert ( + client._transport.delete_restore_template + in client._transport._wrapped_methods ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - backupplan.ListBackupPlansResponse.to_json(x) for x in response + # 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. ) - 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"} + client._transport._wrapped_methods[ + client._transport.delete_restore_template + ] = mock_rpc + request = {} + client.delete_restore_template(request) - pager = client.list_backup_plans(request=sample_request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # 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() - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, backupplan.BackupPlan) for i in results) + client.delete_restore_template(request) - pages = list(client.list_backup_plans(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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_plan_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_delete_restore_template_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.wrap_method") as wrapper_fn: - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) # Should wrap all calls on client creation @@ -21325,351 +23303,301 @@ def test_delete_backup_plan_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_backup_plan in client._transport._wrapped_methods + client._client._transport.delete_restore_template + in client._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_plan] = ( - mock_rpc - ) + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_restore_template + ] = mock_rpc request = {} - client.delete_backup_plan(request) + await client.delete_restore_template(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 + # 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_plan(request) + await client.delete_restore_template(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_plan_rest_required_fields( - request_type=backupplan.DeleteBackupPlanRequest, +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + restore_template.DeleteRestoreTemplateRequest(), + {}, + ], +) +async def test_delete_restore_template_async( + request_type, transport: str = "grpc_asyncio" ): - transport_class = transports.BackupDRRestTransport - - 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) + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped - - default_values = getattr( - transport_class._BaseDeleteBackupPlan, - "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # 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 - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__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_restore_template(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_template.DeleteRestoreTemplateRequest() + assert args[0] == request - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_delete_restore_template_field_headers(): client = BackupDRClient( 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) + # 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 = restore_template.DeleteRestoreTemplateRequest() - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + request.name = "name_value" - response = client.delete_backup_plan(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_template(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 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"] -def test_delete_backup_plan_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_delete_restore_template_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = restore_template.DeleteRestoreTemplateRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlans/sample3" - } + request.name = "name_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.delete_restore_template), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.delete_restore_template(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_backup_plan(**mock_args) + # 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_restore_template_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__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_restore_template( + name="name_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/v1/{name=projects/*/locations/*/backupPlans/*}" - % 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_delete_backup_plan_rest_flattened_error(transport: str = "rest"): +def test_delete_restore_template_flattened_error(): client = BackupDRClient( 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_plan( - backupplan.DeleteBackupPlanRequest(), + client.delete_restore_template( + restore_template.DeleteRestoreTemplateRequest(), name="name_value", ) -def test_get_backup_plan_revision_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_delete_restore_template_flattened_async(): + client = BackupDRAsyncClient( + 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.delete_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Ensure method has been cached - assert ( - client._transport.get_backup_plan_revision - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - - # 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.delete_restore_template( + name="name_value", ) - client._transport._wrapped_methods[ - client._transport.get_backup_plan_revision - ] = mock_rpc - - request = {} - client.get_backup_plan_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_backup_plan_revision(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_get_backup_plan_revision_rest_required_fields( - request_type=backupplan.GetBackupPlanRevisionRequest, -): - transport_class = transports.BackupDRRestTransport - - 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 - default_values = getattr( - transport_class._BaseGetBackupPlanRevision, - "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_delete_restore_template_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - jsonified_request["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_restore_template( + restore_template.DeleteRestoreTemplateRequest(), + 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", + [ + restore_template.RunRestoreTemplateRequest(), + {}, + ], +) +def test_run_restore_template(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupplan.BackupPlanRevision() - # 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 = backupplan.BackupPlanRevision.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.run_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.run_restore_template(request) - response = client.get_backup_plan_revision(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_template.RunRestoreTemplateRequest() + 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, future.Future) -def test_get_backup_plan_revision_rest_flattened(): +def test_run_restore_template_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 = BackupDRClient( 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 = backupplan.BackupPlanRevision() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/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 = backupplan.BackupPlanRevision.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_plan_revision(**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/*/backupPlans/*/revisions/*}" - % client.transport._host, - args[1], - ) - - -def test_get_backup_plan_revision_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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 = restore_template.RunRestoreTemplateRequest( + name="name_value", + backup="backup_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_backup_plan_revision( - backupplan.GetBackupPlanRevisionRequest(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.run_restore_template(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.RunRestoreTemplateRequest( name="name_value", + backup="backup_value", ) + assert args[0] == request_msg -def test_list_backup_plan_revisions_rest_use_cached_wrapped_rpc(): +def test_run_restore_template_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -21678,8 +23606,7 @@ def test_list_backup_plan_revisions_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_backup_plan_revisions - in client._transport._wrapped_methods + client._transport.run_restore_template in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -21687,241 +23614,358 @@ def test_list_backup_plan_revisions_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_backup_plan_revisions - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.run_restore_template] = ( + mock_rpc + ) request = {} - client.list_backup_plan_revisions(request) + client.run_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backup_plan_revisions(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.run_restore_template(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_plan_revisions_rest_required_fields( - request_type=backupplan.ListBackupPlanRevisionsRequest, +@pytest.mark.asyncio +async def test_run_restore_template_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.run_restore_template + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseListBackupPlanRevisions, - "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.run_restore_template + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.run_restore_template(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "pageSize", - "pageToken", - ) - ) + # 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() - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + await client.run_restore_template(request) - client = BackupDRClient( - 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 = backupplan.ListBackupPlanRevisionsResponse() - # 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", + [ + restore_template.RunRestoreTemplateRequest(), + {}, + ], +) +async def test_run_restore_template_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Convert return value to protobuf type - return_value = backupplan.ListBackupPlanRevisionsResponse.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.run_restore_template), "__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.run_restore_template(request) - response = client.list_backup_plan_revisions(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_template.RunRestoreTemplateRequest() + 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, future.Future) -def test_list_backup_plan_revisions_rest_flattened(): +def test_run_restore_template_field_headers(): client = BackupDRClient( 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 = backupplan.ListBackupPlanRevisionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/backupPlans/sample3" - } + # 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 = restore_template.RunRestoreTemplateRequest() - # 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 = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.run_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.run_restore_template(request) - client.list_backup_plan_revisions(**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 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/*/backupPlans/*}/revisions" - % client.transport._host, - args[1], - ) + # 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_list_backup_plan_revisions_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_run_restore_template_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. + # 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 = restore_template.RunRestoreTemplateRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.run_restore_template(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_run_restore_template_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__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.run_restore_template( + 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_run_restore_template_flattened_error(): + client = BackupDRClient( + 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_backup_plan_revisions( - backupplan.ListBackupPlanRevisionsRequest(), - parent="parent_value", + client.run_restore_template( + restore_template.RunRestoreTemplateRequest(), + name="name_value", ) -def test_list_backup_plan_revisions_rest_pager(transport: str = "rest"): +@pytest.mark.asyncio +async def test_run_restore_template_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__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.run_restore_template( + 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_run_restore_template_flattened_error_async(): + client = BackupDRAsyncClient( + 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.run_restore_template( + restore_template.RunRestoreTemplateRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_template_execution.GetRestoreTemplateExecutionRequest(), + {}, + ], +) +def test_get_restore_template_execution(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = ( - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - next_page_token="abc", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[], - next_page_token="def", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - ], - next_page_token="ghi", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - backupplan.ListBackupPlanRevisionsResponse.to_json(x) for x in response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_template_execution.RestoreTemplateExecution( + name="name_value", + resource_type="resource_type_value", + type_=restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED, + phase=restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING, + state=restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING, ) - 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 + response = client.get_restore_template_execution(request) - sample_request = { - "parent": "projects/sample1/locations/sample2/backupPlans/sample3" - } + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_template_execution.GetRestoreTemplateExecutionRequest() + assert args[0] == request - pager = client.list_backup_plan_revisions(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, restore_template_execution.RestoreTemplateExecution) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert ( + response.type_ + == restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED + ) + assert ( + response.phase + == restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING + ) + assert ( + response.state + == restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING + ) - 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, backupplan.BackupPlanRevision) for i in results) +def test_get_restore_template_execution_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_backup_plan_revisions(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = restore_template_execution.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_restore_template_execution(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.GetRestoreTemplateExecutionRequest( + name="name_value", + ) + assert args[0] == request_msg -def test_create_backup_plan_association_rest_use_cached_wrapped_rpc(): +def test_get_restore_template_execution_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -21930,7 +23974,7 @@ def test_create_backup_plan_association_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_backup_plan_association + client._transport.get_restore_template_execution in client._transport._wrapped_methods ) @@ -21940,384 +23984,360 @@ def test_create_backup_plan_association_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_backup_plan_association + client._transport.get_restore_template_execution ] = mock_rpc - request = {} - client.create_backup_plan_association(request) + client.get_restore_template_execution(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_backup_plan_association(request) + client.get_restore_template_execution(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_backup_plan_association_rest_required_fields( - request_type=backupplanassociation.CreateBackupPlanAssociationRequest, +@pytest.mark.asyncio +async def test_get_restore_template_execution_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["backup_plan_association_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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped - assert "backupPlanAssociationId" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.get_restore_template_execution + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseCreateBackupPlanAssociation, - "_BaseCreateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.get_restore_template_execution + ] = mock_rpc - # verify required fields with default values are now present - assert "backupPlanAssociationId" in jsonified_request - assert ( - jsonified_request["backupPlanAssociationId"] - == request_init["backup_plan_association_id"] + request = {} + await client.get_restore_template_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_restore_template_execution(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", + [ + restore_template_execution.GetRestoreTemplateExecutionRequest(), + {}, + ], +) +async def test_get_restore_template_execution_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - jsonified_request["parent"] = "parent_value" - jsonified_request["backupPlanAssociationId"] = "backup_plan_association_id_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "backupPlanAssociationId", - "requestId", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.RestoreTemplateExecution( + name="name_value", + resource_type="resource_type_value", + type_=restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED, + phase=restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING, + state=restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING, + ) ) - ) + response = await client.get_restore_template_execution(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "backupPlanAssociationId" in jsonified_request + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_template_execution.GetRestoreTemplateExecutionRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, restore_template_execution.RestoreTemplateExecution) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" assert ( - jsonified_request["backupPlanAssociationId"] - == "backup_plan_association_id_value" + response.type_ + == restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED + ) + assert ( + response.phase + == restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING + ) + assert ( + response.state + == restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING ) + +def test_get_restore_template_execution_field_headers(): client = BackupDRClient( 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 + # 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 = restore_template_execution.GetRestoreTemplateExecutionRequest() - 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_restore_template_execution), "__call__" + ) as call: + call.return_value = restore_template_execution.RestoreTemplateExecution() + client.get_restore_template_execution(request) - response = client.create_backup_plan_association(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 = [ - ( - "backupPlanAssociationId", - "", - ), - ("$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_create_backup_plan_association_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_restore_template_execution_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = restore_template_execution.GetRestoreTemplateExecutionRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - backup_plan_association=backupplanassociation.BackupPlanAssociation( - name="name_value" - ), - backup_plan_association_id="backup_plan_association_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.RestoreTemplateExecution() ) - mock_args.update(sample_request) + await client.get_restore_template_execution(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.create_backup_plan_association(**mock_args) + # 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_restore_template_execution_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_template_execution.RestoreTemplateExecution() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_restore_template_execution( + name="name_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/v1/{parent=projects/*/locations/*}/backupPlanAssociations" - % 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_create_backup_plan_association_rest_flattened_error(transport: str = "rest"): +def test_get_restore_template_execution_flattened_error(): client = BackupDRClient( 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_backup_plan_association( - backupplanassociation.CreateBackupPlanAssociationRequest(), - parent="parent_value", - backup_plan_association=backupplanassociation.BackupPlanAssociation( - name="name_value" - ), - backup_plan_association_id="backup_plan_association_id_value", + client.get_restore_template_execution( + restore_template_execution.GetRestoreTemplateExecutionRequest(), + name="name_value", ) -def test_update_backup_plan_association_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_get_restore_template_execution_flattened_async(): + client = BackupDRAsyncClient( + 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.get_restore_template_execution), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_template_execution.RestoreTemplateExecution() - # Ensure method has been cached - assert ( - client._transport.update_backup_plan_association - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.RestoreTemplateExecution() ) - - # 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.get_restore_template_execution( + name="name_value", ) - client._transport._wrapped_methods[ - client._transport.update_backup_plan_association - ] = mock_rpc - request = {} - client.update_backup_plan_association(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].name + mock_val = "name_value" + assert arg == mock_val - # 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() +@pytest.mark.asyncio +async def test_get_restore_template_execution_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - client.update_backup_plan_association(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_backup_plan_association_rest_required_fields( - request_type=backupplanassociation.UpdateBackupPlanAssociationRequest, -): - transport_class = transports.BackupDRRestTransport - - 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 - - default_values = getattr( - transport_class._BaseUpdateBackupPlanAssociation, - "_BaseUpdateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_restore_template_execution( + restore_template_execution.GetRestoreTemplateExecutionRequest(), + name="name_value", ) - ) - # verify required fields with non-default values are left alone +@pytest.mark.parametrize( + "request_type", + [ + restore_template_execution.ListRestoreTemplateExecutionsRequest(), + {}, + ], +) +def test_list_restore_template_executions(request_type, transport: str = "grpc"): client = BackupDRClient( 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": "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) + # 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_restore_template_executions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = client.list_restore_template_executions(request) - response = client.update_backup_plan_association(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_template_execution.ListRestoreTemplateExecutionsRequest() + 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.ListRestoreTemplateExecutionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_update_backup_plan_association_rest_flattened(): +def test_list_restore_template_executions_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 = BackupDRClient( 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 = { - "backup_plan_association": { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" - } - } - - # get truthy value for each flattened field - mock_args = dict( - backup_plan_association=backupplanassociation.BackupPlanAssociation( - name="name_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_backup_plan_association(**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/{backup_plan_association.name=projects/*/locations/*/backupPlanAssociations/*}" - % client.transport._host, - args[1], - ) - - -def test_update_backup_plan_association_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_backup_plan_association( - backupplanassociation.UpdateBackupPlanAssociationRequest(), - backup_plan_association=backupplanassociation.BackupPlanAssociation( - 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.list_restore_template_executions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_restore_template_executions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) + assert args[0] == request_msg -def test_get_backup_plan_association_rest_use_cached_wrapped_rpc(): +def test_list_restore_template_executions_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -22326,7 +24346,7 @@ def test_get_backup_plan_association_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_backup_plan_association + client._transport.list_restore_template_executions in client._transport._wrapped_methods ) @@ -22336,420 +24356,551 @@ def test_get_backup_plan_association_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_backup_plan_association + client._transport.list_restore_template_executions ] = mock_rpc - request = {} - client.get_backup_plan_association(request) + client.list_restore_template_executions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup_plan_association(request) + client.list_restore_template_executions(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_plan_association_rest_required_fields( - request_type=backupplanassociation.GetBackupPlanAssociationRequest, +@pytest.mark.asyncio +async def test_list_restore_template_executions_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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_restore_template_executions + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetBackupPlanAssociation, - "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_restore_template_executions + ] = mock_rpc + + request = {} + await client.list_restore_template_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_restore_template_executions(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", + [ + restore_template_execution.ListRestoreTemplateExecutionsRequest(), {}, + ], +) +async def test_list_restore_template_executions_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_restore_template_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_template_execution.ListRestoreTemplateExecutionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreTemplateExecutionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_list_restore_template_executions_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupplanassociation.BackupPlanAssociation() - # 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 + # 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest() - # Convert return value to protobuf type - return_value = backupplanassociation.BackupPlanAssociation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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_restore_template_executions), "__call__" + ) as call: + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + client.list_restore_template_executions(request) - response = client.get_backup_plan_association(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", + "parent=parent_value", + ) in kw["metadata"] -def test_get_backup_plan_association_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_restore_template_executions_field_headers_async(): + client = BackupDRAsyncClient( + 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 = backupplanassociation.BackupPlanAssociation() + # 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/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_restore_template_executions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.ListRestoreTemplateExecutionsResponse() ) - mock_args.update(sample_request) + await client.list_restore_template_executions(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 = backupplanassociation.BackupPlanAssociation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_backup_plan_association(**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_restore_template_executions_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_restore_template_executions( + 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/v1/{name=projects/*/locations/*/backupPlanAssociations/*}" - % 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_backup_plan_association_rest_flattened_error(transport: str = "rest"): +def test_list_restore_template_executions_flattened_error(): client = BackupDRClient( 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_plan_association( - backupplanassociation.GetBackupPlanAssociationRequest(), - name="name_value", + client.list_restore_template_executions( + restore_template_execution.ListRestoreTemplateExecutionsRequest(), + parent="parent_value", ) -def test_list_backup_plan_associations_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 = BackupDRClient( - 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_restore_template_executions_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.list_backup_plan_associations - 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_restore_template_executions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() ) - # 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( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_restore_template_executions( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.list_backup_plan_associations - ] = mock_rpc - - request = {} - client.list_backup_plan_associations(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_backup_plan_associations(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_plan_associations_rest_required_fields( - request_type=backupplanassociation.ListBackupPlanAssociationsRequest, -): - transport_class = transports.BackupDRRestTransport - 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) - ) + # 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 - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseListBackupPlanAssociations, - "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_list_restore_template_executions_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "pageSize", - "pageToken", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_restore_template_executions( + restore_template_execution.ListRestoreTemplateExecutionsRequest(), + parent="parent_value", ) - ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_list_restore_template_executions_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupplanassociation.ListBackupPlanAssociationsResponse() - # 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="abc", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], + next_page_token="def", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="ghi", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + ), + RuntimeError, + ) - # Convert return value to protobuf type - return_value = backupplanassociation.ListBackupPlanAssociationsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_restore_template_executions( + request={}, retry=retry, timeout=timeout + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - response = client.list_backup_plan_associations(request) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, restore_template_execution.RestoreTemplateExecution) + for i in results + ) -def test_list_backup_plan_associations_rest_flattened(): +def test_list_restore_template_executions_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # 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 = backupplanassociation.ListBackupPlanAssociationsResponse() - - # 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 the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="abc", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], + next_page_token="def", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="ghi", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + ), + RuntimeError, ) - mock_args.update(sample_request) + pages = list(client.list_restore_template_executions(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 = backupplanassociation.ListBackupPlanAssociationsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_plan_associations(**mock_args) +@pytest.mark.asyncio +async def test_list_restore_template_executions_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # 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/*}/backupPlanAssociations" - % client.transport._host, - args[1], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="abc", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], + next_page_token="def", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="ghi", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + ), + RuntimeError, ) + async_pager = await client.list_restore_template_executions( + 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) -def test_list_backup_plan_associations_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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_plan_associations( - backupplanassociation.ListBackupPlanAssociationsRequest(), - parent="parent_value", + assert len(responses) == 6 + assert all( + isinstance(i, restore_template_execution.RestoreTemplateExecution) + for i in responses ) -def test_list_backup_plan_associations_rest_pager(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_restore_template_executions_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = ( - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="abc", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[], + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], next_page_token="def", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="ghi", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response + pages = [] + async for page_ in ( + await client.list_restore_template_executions(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Wrap the values into proper Response objs - response = tuple( - backupplanassociation.ListBackupPlanAssociationsResponse.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"} +@pytest.mark.parametrize( + "request_type", + [ + restore_template_execution.TriggerRestoreCleanupRequest(), + {}, + ], +) +def test_trigger_restore_cleanup(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - pager = client.list_backup_plan_associations(request=sample_request) + # 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 - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.trigger_restore_cleanup(request) - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_template_execution.TriggerRestoreCleanupRequest() + assert args[0] == request - pages = list(client.list_backup_plan_associations(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_fetch_backup_plan_associations_for_resource_type_rest_use_cached_wrapped_rpc(): +def test_trigger_restore_cleanup_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 = BackupDRClient( + 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 = restore_template_execution.TriggerRestoreCleanupRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.trigger_restore_cleanup(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.TriggerRestoreCleanupRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_trigger_restore_cleanup_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -22758,7 +24909,7 @@ def test_fetch_backup_plan_associations_for_resource_type_rest_use_cached_wrappe # Ensure method has been cached assert ( - client._transport.fetch_backup_plan_associations_for_resource_type + client._transport.trigger_restore_cleanup in client._transport._wrapped_methods ) @@ -22768,279 +24919,341 @@ def test_fetch_backup_plan_associations_for_resource_type_rest_use_cached_wrappe "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_backup_plan_associations_for_resource_type + client._transport.trigger_restore_cleanup ] = mock_rpc - request = {} - client.fetch_backup_plan_associations_for_resource_type(request) + client.trigger_restore_cleanup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_backup_plan_associations_for_resource_type(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.trigger_restore_cleanup(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_fetch_backup_plan_associations_for_resource_type_rest_required_fields( - request_type=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, +@pytest.mark.asyncio +async def test_trigger_restore_cleanup_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["resource_type"] = "" - 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 - assert "resourceType" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.trigger_restore_cleanup + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseFetchBackupPlanAssociationsForResourceType, - "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.trigger_restore_cleanup + ] = mock_rpc - # verify required fields with default values are now present - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == request_init["resource_type"] + request = {} + await client.trigger_restore_cleanup(request) - jsonified_request["parent"] = "parent_value" - jsonified_request["resourceType"] = "resource_type_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "resourceType", - ) - ) + # 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() - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == "resource_type_value" + await client.trigger_restore_cleanup(request) - client = BackupDRClient( - 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 = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - ) - # 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", + [ + restore_template_execution.TriggerRestoreCleanupRequest(), + {}, + ], +) +async def test_trigger_restore_cleanup_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Convert return value to protobuf type - return_value = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.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.trigger_restore_cleanup), "__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.trigger_restore_cleanup(request) - response = client.fetch_backup_plan_associations_for_resource_type(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_template_execution.TriggerRestoreCleanupRequest() + assert args[0] == request - expected_params = [ - ( - "resourceType", - "", - ), - ("$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, future.Future) -def test_fetch_backup_plan_associations_for_resource_type_rest_flattened(): +def test_trigger_restore_cleanup_field_headers(): client = BackupDRClient( 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 = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - ) - - # 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 = restore_template_execution.TriggerRestoreCleanupRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - resource_type="resource_type_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 = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.trigger_restore_cleanup), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_restore_cleanup(request) - client.fetch_backup_plan_associations_for_resource_type(**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 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/*}/backupPlanAssociations:fetchForResourceType" - % client.transport._host, - args[1], - ) + # 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_fetch_backup_plan_associations_for_resource_type_rest_flattened_error( - transport: str = "rest", -): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_trigger_restore_cleanup_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.fetch_backup_plan_associations_for_resource_type( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), - parent="parent_value", - resource_type="resource_type_value", - ) + # 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 = restore_template_execution.TriggerRestoreCleanupRequest() + request.name = "name_value" -def test_fetch_backup_plan_associations_for_resource_type_rest_pager( - transport: str = "rest", -): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.trigger_restore_cleanup(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_trigger_restore_cleanup_flattened(): client = BackupDRClient( 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 = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - ], - next_page_token="abc", - ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[], - next_page_token="def", - ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - ], - next_page_token="ghi", - ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - ], - ), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__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.trigger_restore_cleanup( + name="name_value", ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( - x - ) - for x in response + # 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_trigger_restore_cleanup_flattened_error(): + client = BackupDRClient( + 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.trigger_restore_cleanup( + restore_template_execution.TriggerRestoreCleanupRequest(), + 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.fetch_backup_plan_associations_for_resource_type( - request=sample_request +@pytest.mark.asyncio +async def test_trigger_restore_cleanup_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__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.trigger_restore_cleanup( + name="name_value", ) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # 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 - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results + +@pytest.mark.asyncio +async def test_trigger_restore_cleanup_flattened_error_async(): + client = BackupDRAsyncClient( + 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.trigger_restore_cleanup( + restore_template_execution.TriggerRestoreCleanupRequest(), + name="name_value", ) - pages = list( - client.fetch_backup_plan_associations_for_resource_type( - request=sample_request - ).pages + +@pytest.mark.parametrize( + "request_type", + [ + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), + {}, + ], +) +def test_create_restore_verification_plan(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_restore_verification_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_restore_verification_plan_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 = BackupDRClient( + 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 = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.create_restore_verification_plan(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + ) + ) + assert args[0] == request_msg -def test_delete_backup_plan_association_rest_use_cached_wrapped_rpc(): +def test_create_restore_verification_plan_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -23049,7 +25262,7 @@ def test_delete_backup_plan_association_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_backup_plan_association + client._transport.create_restore_verification_plan in client._transport._wrapped_methods ) @@ -23059,343 +25272,373 @@ def test_delete_backup_plan_association_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_backup_plan_association + client._transport.create_restore_verification_plan ] = mock_rpc - request = {} - client.delete_backup_plan_association(request) + client.create_restore_verification_plan(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 + # 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_plan_association(request) + client.create_restore_verification_plan(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_plan_association_rest_required_fields( - request_type=backupplanassociation.DeleteBackupPlanAssociationRequest, +@pytest.mark.asyncio +async def test_create_restore_verification_plan_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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.create_restore_verification_plan + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseDeleteBackupPlanAssociation, - "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_restore_verification_plan + ] = mock_rpc + + request = {} + await client.create_restore_verification_plan(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.create_restore_verification_plan(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", + [ + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), {}, + ], +) +async def test_create_restore_verification_plan_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_restore_verification_plan(request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + assert args[0] == request - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + +def test_create_restore_verification_plan_field_headers(): client = BackupDRClient( 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 + # 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 = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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.create_restore_verification_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_verification_plan(request) - response = client.delete_backup_plan_association(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", + "parent=parent_value", + ) in kw["metadata"] -def test_delete_backup_plan_association_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_create_restore_verification_plan_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/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.create_restore_verification_plan), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.create_restore_verification_plan(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_backup_plan_association(**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_create_restore_verification_plan_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_restore_verification_plan( + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" + ), + restore_verification_plan_id="restore_verification_plan_id_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/v1/{name=projects/*/locations/*/backupPlanAssociations/*}" - % 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 + arg = args[0].restore_verification_plan + mock_val = gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" ) + assert arg == mock_val + arg = args[0].restore_verification_plan_id + mock_val = "restore_verification_plan_id_value" + assert arg == mock_val -def test_delete_backup_plan_association_rest_flattened_error(transport: str = "rest"): +def test_create_restore_verification_plan_flattened_error(): client = BackupDRClient( 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_plan_association( - backupplanassociation.DeleteBackupPlanAssociationRequest(), - name="name_value", + client.create_restore_verification_plan( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" + ), + restore_verification_plan_id="restore_verification_plan_id_value", ) -def test_trigger_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 = BackupDRClient( - 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_create_restore_verification_plan_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.trigger_backup in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # 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( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_restore_verification_plan( + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" + ), + restore_verification_plan_id="restore_verification_plan_id_value", ) - client._transport._wrapped_methods[client._transport.trigger_backup] = mock_rpc - - request = {} - client.trigger_backup(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 + arg = args[0].restore_verification_plan + mock_val = gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" + ) + assert arg == mock_val + arg = args[0].restore_verification_plan_id + mock_val = "restore_verification_plan_id_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.trigger_backup(request) +@pytest.mark.asyncio +async def test_create_restore_verification_plan_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_restore_verification_plan( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" + ), + restore_verification_plan_id="restore_verification_plan_id_value", + ) -def test_trigger_backup_rest_required_fields( - request_type=backupplanassociation.TriggerBackupRequest, +@pytest.mark.parametrize( + "request_type", + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), + {}, + ], +) +def test_create_restore_verification_plan_association( + request_type, transport: str = "grpc" ): - transport_class = transports.BackupDRRestTransport + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request_init["rule_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 + # 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 - default_values = getattr( - transport_class._BaseTriggerBackup, - "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.create_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_restore_verification_plan_association(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" - jsonified_request["ruleId"] = "rule_id_value" + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - assert "ruleId" in jsonified_request - assert jsonified_request["ruleId"] == "rule_id_value" +def test_create_restore_verification_plan_association_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - 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.trigger_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_trigger_backup_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # 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 = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", ) - # 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/backupPlanAssociations/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - rule_id="rule_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.trigger_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/v1/{name=projects/*/locations/*/backupPlanAssociations/*}:triggerBackup" - % client.transport._host, - args[1], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -def test_trigger_backup_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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.trigger_backup( - backupplanassociation.TriggerBackupRequest(), - name="name_value", - rule_id="rule_id_value", + client.create_restore_verification_plan_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest( + parent="parent_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", ) + assert args[0] == request_msg -def test_get_data_source_reference_rest_use_cached_wrapped_rpc(): +def test_create_restore_verification_plan_association_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -23404,7 +25647,7 @@ def test_get_data_source_reference_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_data_source_reference + client._transport.create_restore_verification_plan_association in client._transport._wrapped_methods ) @@ -23414,164 +25657,387 @@ def test_get_data_source_reference_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_data_source_reference + client._transport.create_restore_verification_plan_association ] = mock_rpc - request = {} - client.get_data_source_reference(request) + client.create_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_source_reference(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.create_restore_verification_plan_association(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_data_source_reference_rest_required_fields( - request_type=datasourcereference.GetDataSourceReferenceRequest, +@pytest.mark.asyncio +async def test_create_restore_verification_plan_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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.create_restore_verification_plan_association + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetDataSourceReference, - "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_restore_verification_plan_association + ] = mock_rpc + + request = {} + await client.create_restore_verification_plan_association(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.create_restore_verification_plan_association(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", + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), {}, + ], +) +async def test_create_restore_verification_plan_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_restore_verification_plan_association(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + +def test_create_restore_verification_plan_association_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = datasourcereference.DataSourceReference() - # 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 + # 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 = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() - response_value = Response() - response_value.status_code = 200 + request.parent = "parent_value" - # Convert return value to protobuf type - return_value = datasourcereference.DataSourceReference.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_verification_plan_association(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.get_data_source_reference(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_create_restore_verification_plan_association_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_get_data_source_reference_rest_flattened(): + # 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 = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_restore_verification_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_restore_verification_plan_association_flattened(): client = BackupDRClient( 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 = datasourcereference.DataSourceReference() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_restore_verification_plan_association( + parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/dataSourceReferences/sample3" - } + # 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].restore_verification_plan_association + mock_val = gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value" + ) + assert arg == mock_val + arg = args[0].restore_verification_plan_association_id + mock_val = "restore_verification_plan_association_id_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + +def test_create_restore_verification_plan_association_flattened_error(): + client = BackupDRClient( + 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_restore_verification_plan_association( + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), + parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_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 = datasourcereference.DataSourceReference.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_data_source_reference(**mock_args) +@pytest.mark.asyncio +async def test_create_restore_verification_plan_association_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_restore_verification_plan_association( + parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_id_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/v1/{name=projects/*/locations/*/dataSourceReferences/*}" - % client.transport._host, - args[1], + 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].restore_verification_plan_association + mock_val = gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value" ) + assert arg == mock_val + arg = args[0].restore_verification_plan_association_id + mock_val = "restore_verification_plan_association_id_value" + assert arg == mock_val -def test_get_data_source_reference_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_create_restore_verification_plan_association_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_source_reference( - datasourcereference.GetDataSourceReferenceRequest(), + await client.create_restore_verification_plan_association( + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), + parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), + {}, + ], +) +def test_get_restore_verification_plan_association( + request_type, transport: str = "grpc" +): + client = BackupDRClient( + 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_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_verification_plan_association.RestoreVerificationPlanAssociation( name="name_value", + description="description_value", + state=restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING, + resource_type="resource_type_value", + restore_template="restore_template_value", ) + response = client.get_restore_verification_plan_association(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + assert args[0] == request -def test_list_data_source_references_rest_use_cached_wrapped_rpc(): + # Establish that the response is the type that we expect. + assert isinstance( + response, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING + ) + assert response.resource_type == "resource_type_value" + + +def test_get_restore_verification_plan_association_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 = BackupDRClient( + 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 = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_restore_verification_plan_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_restore_verification_plan_association_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -23580,7 +26046,7 @@ def test_list_data_source_references_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_data_source_references + client._transport.get_restore_verification_plan_association in client._transport._wrapped_methods ) @@ -23590,245 +26056,361 @@ def test_list_data_source_references_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_data_source_references + client._transport.get_restore_verification_plan_association ] = mock_rpc - request = {} - client.list_data_source_references(request) + client.get_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_source_references(request) + client.get_restore_verification_plan_association(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_data_source_references_rest_required_fields( - request_type=datasourcereference.ListDataSourceReferencesRequest, +@pytest.mark.asyncio +async def test_get_restore_verification_plan_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport - - 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) - ) + # Clients should use _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 = BackupDRAsyncClient( + 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() - default_values = getattr( - transport_class._BaseListDataSourceReferences, - "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", + # Ensure method has been cached + assert ( + client._client._transport.get_restore_verification_plan_association + 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_restore_verification_plan_association + ] = mock_rpc + + request = {} + await client.get_restore_verification_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_restore_verification_plan_association(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", + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), {}, + ], +) +async def test_get_restore_verification_plan_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value", + description="description_value", + state=restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING, + resource_type="resource_type_value", + ) ) + response = await client.get_restore_verification_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING ) + assert response.resource_type == "resource_type_value" - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_get_restore_verification_plan_association_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = datasourcereference.ListDataSourceReferencesResponse() - # 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 + # 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 = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() - response_value = Response() - response_value.status_code = 200 + request.name = "name_value" - # Convert return value to protobuf type - return_value = datasourcereference.ListDataSourceReferencesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + client.get_restore_verification_plan_association(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.list_data_source_references(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_get_restore_verification_plan_association_field_headers_async(): + client = BackupDRAsyncClient( + 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 = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + + request.name = "name_value" -def test_list_data_source_references_rest_flattened(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + await client.get_restore_verification_plan_association(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_restore_verification_plan_association_flattened(): client = BackupDRClient( 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 = datasourcereference.ListDataSourceReferencesResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_restore_verification_plan_association( + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # 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 - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + +def test_get_restore_verification_plan_association_flattened_error(): + client = BackupDRClient( + 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_restore_verification_plan_association( + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), + 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 = datasourcereference.ListDataSourceReferencesResponse.pb( - return_value + +@pytest.mark.asyncio +async def test_get_restore_verification_plan_association_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() ) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_data_source_references(**mock_args) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_restore_verification_plan_association( + name="name_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/v1/{parent=projects/*/locations/*}/dataSourceReferences" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_list_data_source_references_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_get_restore_verification_plan_association_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_data_source_references( - datasourcereference.ListDataSourceReferencesRequest(), - parent="parent_value", + await client.get_restore_verification_plan_association( + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), + name="name_value", ) -def test_list_data_source_references_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), + {}, + ], +) +def test_list_restore_verification_plan_associations( + request_type, transport: str = "grpc" +): client = BackupDRClient( 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 = ( - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - datasourcereference.ListDataSourceReferencesResponse.to_json(x) - for x in response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 + response = client.list_restore_verification_plan_associations(request) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + assert args[0] == request - pager = client.list_data_source_references(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreVerificationPlanAssociationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - 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, datasourcereference.DataSourceReference) for i in results - ) +def test_list_restore_verification_plan_associations_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_data_source_references(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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_restore_verification_plan_associations), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_restore_verification_plan_associations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg -def test_fetch_data_source_references_for_resource_type_rest_use_cached_wrapped_rpc(): + +def test_list_restore_verification_plan_associations_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -23837,7 +26419,7 @@ def test_fetch_data_source_references_for_resource_type_rest_use_cached_wrapped_ # Ensure method has been cached assert ( - client._transport.fetch_data_source_references_for_resource_type + client._transport.list_restore_verification_plan_associations in client._transport._wrapped_methods ) @@ -23847,281 +26429,561 @@ def test_fetch_data_source_references_for_resource_type_rest_use_cached_wrapped_ "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_data_source_references_for_resource_type + client._transport.list_restore_verification_plan_associations ] = mock_rpc - request = {} - client.fetch_data_source_references_for_resource_type(request) + client.list_restore_verification_plan_associations(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_data_source_references_for_resource_type(request) + client.list_restore_verification_plan_associations(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_fetch_data_source_references_for_resource_type_rest_required_fields( - request_type=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, +@pytest.mark.asyncio +async def test_list_restore_verification_plan_associations_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["resource_type"] = "" - 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 - assert "resourceType" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.list_restore_verification_plan_associations + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseFetchDataSourceReferencesForResourceType, - "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_restore_verification_plan_associations + ] = mock_rpc + + request = {} + await client.list_restore_verification_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_restore_verification_plan_associations(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", + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), {}, + ], +) +async def test_list_restore_verification_plan_associations_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == request_init["resource_type"] - jsonified_request["parent"] = "parent_value" - jsonified_request["resourceType"] = "resource_type_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "resourceType", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) + response = await client.list_restore_verification_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, pagers.ListRestoreVerificationPlanAssociationsAsyncPager ) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == "resource_type_value" +def test_list_restore_verification_plan_associations_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() - ) - # 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 + # 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() - response_value = Response() - response_value.status_code = 200 + request.parent = "parent_value" - # Convert return value to protobuf type - return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + client.list_restore_verification_plan_associations(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.fetch_data_source_references_for_resource_type(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - expected_params = [ - ( - "resourceType", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_list_restore_verification_plan_associations_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_fetch_data_source_references_for_resource_type_rest_flattened(): + # 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + ) + await client.list_restore_verification_plan_associations(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_restore_verification_plan_associations_flattened(): client = BackupDRClient( 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 = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_restore_verification_plan_associations( + parent="parent_value", ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # 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 - # get truthy value for each flattened field - mock_args = dict( + +def test_list_restore_verification_plan_associations_flattened_error(): + client = BackupDRClient( + 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_restore_verification_plan_associations( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), parent="parent_value", - resource_type="resource_type_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 = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.fetch_data_source_references_for_resource_type(**mock_args) +@pytest.mark.asyncio +async def test_list_restore_verification_plan_associations_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_restore_verification_plan_associations( + 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/v1/{parent=projects/*/locations/*}/dataSourceReferences:fetchForResourceType" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_fetch_data_source_references_for_resource_type_rest_flattened_error( - transport: str = "rest", -): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_restore_verification_plan_associations_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_data_source_references_for_resource_type( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + await client.list_restore_verification_plan_associations( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), parent="parent_value", - resource_type="resource_type_value", ) -def test_fetch_data_source_references_for_resource_type_rest_pager( - transport: str = "rest", +def test_list_restore_verification_plan_associations_pager( + transport_name: str = "grpc", ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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 = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="abc", ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], next_page_token="def", ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="ghi", ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.to_json( - x - ) - for x in response + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - 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.fetch_data_source_references_for_resource_type( - request=sample_request + pager = client.list_restore_verification_plan_associations( + 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, datasourcereference.DataSourceReference) for i in results + isinstance( + i, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + for i in results ) + +def test_list_restore_verification_plan_associations_pages( + transport_name: str = "grpc", +): + client = BackupDRClient( + 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_restore_verification_plan_associations), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + next_page_token="abc", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], + next_page_token="def", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + next_page_token="ghi", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + ), + RuntimeError, + ) pages = list( - client.fetch_data_source_references_for_resource_type( - request=sample_request - ).pages + client.list_restore_verification_plan_associations(request={}).pages ) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_initialize_service_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_list_restore_verification_plan_associations_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + next_page_token="abc", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], + next_page_token="def", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + next_page_token="ghi", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_restore_verification_plan_associations( + 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, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_restore_verification_plan_associations_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + next_page_token="abc", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], + next_page_token="def", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + next_page_token="ghi", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_restore_verification_plan_associations(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", + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), + {}, + ], +) +def test_delete_restore_verification_plan_association( + request_type, transport: str = "grpc" +): + client = BackupDRClient( + 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_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_restore_verification_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_restore_verification_plan_association_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 = BackupDRClient( + 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 = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_restore_verification_plan_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_restore_verification_plan_association_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -24130,7 +26992,8 @@ def test_initialize_service_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.initialize_service in client._transport._wrapped_methods + client._transport.delete_restore_verification_plan_association + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -24138,2099 +27001,23879 @@ def test_initialize_service_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.initialize_service] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.delete_restore_verification_plan_association + ] = mock_rpc request = {} - client.initialize_service(request) + client.delete_restore_verification_plan_association(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 + # 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.initialize_service(request) + client.delete_restore_verification_plan_association(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_initialize_service_rest_required_fields( - request_type=backupdr.InitializeServiceRequest, +@pytest.mark.asyncio +async def test_delete_restore_verification_plan_association_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request_init["resource_type"] = "" - 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.delete_restore_verification_plan_association + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseInitializeService, - "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_restore_verification_plan_association + ] = mock_rpc + + request = {} + await client.delete_restore_verification_plan_association(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_restore_verification_plan_association(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", + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), {}, + ], +) +async def test_delete_restore_verification_plan_association_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" - jsonified_request["resourceType"] = "resource_type_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__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_restore_verification_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == "resource_type_value" +def test_delete_restore_verification_plan_association_field_headers(): client = BackupDRClient( 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 + # 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 = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() - 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.delete_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_verification_plan_association(request) - response = client.initialize_service(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_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BackupDRGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.asyncio +async def test_delete_restore_verification_plan_association_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - with pytest.raises(ValueError): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.BackupDRGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BackupDRClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # 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 = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) + await client.delete_restore_verification_plan_association(request) - # It is an error to provide an api_key and a transport instance. - transport = transports.BackupDRGrpcTransport( + # 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_restore_verification_plan_association_flattened(): + client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BackupDRClient( - 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 = BackupDRClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__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_restore_verification_plan_association( + name="name_value", ) - # It is an error to provide scopes and a transport instance. - transport = transports.BackupDRGrpcTransport( + # 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_restore_verification_plan_association_flattened_error(): + client = BackupDRClient( 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 = BackupDRClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client.delete_restore_verification_plan_association( + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), + name="name_value", ) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BackupDRGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.asyncio +async def test_delete_restore_verification_plan_association_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - client = BackupDRClient(transport=transport) - assert client.transport is transport + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BackupDRGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + 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_restore_verification_plan_association( + name="name_value", + ) - transport = transports.BackupDRGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), + # 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_restore_verification_plan_association_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - channel = transport.grpc_channel - assert channel + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_restore_verification_plan_association( + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), + name="name_value", + ) @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.BackupDRGrpcTransport, - transports.BackupDRGrpcAsyncIOTransport, - transports.BackupDRRestTransport, + restore_verification_plan_association.TriggerRestoreVerificationRequest(), + {}, ], ) -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 = BackupDRClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" - - -def test_initialize_client_w_grpc(): - client = BackupDRClient( - 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_management_servers_empty_call_grpc(): +def test_trigger_restore_verification(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. + # 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_management_servers), "__call__" + type(client.transport.trigger_restore_verification), "__call__" ) as call: - call.return_value = backupdr.ListManagementServersResponse() - client.list_management_servers(request=None) + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.trigger_restore_verification(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 = backupdr.ListManagementServersRequest() - assert args[0] == request_msg + request = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) + 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_management_server_empty_call_grpc(): +def test_trigger_restore_verification_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - # Mock the actual call, and fake the request. + # 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 = restore_verification_plan_association.TriggerRestoreVerificationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_management_server), "__call__" + type(client.transport.trigger_restore_verification), "__call__" ) as call: - call.return_value = backupdr.ManagementServer() - client.get_management_server(request=None) - - # Establish that the underlying stub method was called. + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.trigger_restore_verification(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupdr.GetManagementServerRequest() + request_msg = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest( + name="name_value", + ) + ) 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_management_server_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_trigger_restore_verification_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_management_server), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_management_server(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.CreateManagementServerRequest() - assert args[0] == request_msg + # Ensure method has been cached + assert ( + client._transport.trigger_restore_verification + 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.trigger_restore_verification + ] = mock_rpc + request = {} + client.trigger_restore_verification(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_management_server_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + # 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.trigger_restore_verification(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_trigger_restore_verification_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 = BackupDRAsyncClient( + 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.trigger_restore_verification + 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.trigger_restore_verification + ] = mock_rpc + + request = {} + await client.trigger_restore_verification(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.trigger_restore_verification(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", + [ + restore_verification_plan_association.TriggerRestoreVerificationRequest(), + {}, + ], +) +async def test_trigger_restore_verification_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # Mock the actual call, and fake the request. + # 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_management_server), "__call__" + type(client.transport.trigger_restore_verification), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_management_server(request=None) + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.trigger_restore_verification(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 = backupdr.DeleteManagementServerRequest() - assert args[0] == request_msg + request = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) + 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_create_backup_vault_empty_call_grpc(): + +def test_trigger_restore_verification_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. + # 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 = restore_verification_plan_association.TriggerRestoreVerificationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" + type(client.transport.trigger_restore_verification), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup_vault(request=None) + client.trigger_restore_verification(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 = backupvault.CreateBackupVaultRequest() - 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_list_backup_vaults_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_trigger_restore_verification_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # 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 = restore_verification_plan_association.TriggerRestoreVerificationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" + type(client.transport.trigger_restore_verification), "__call__" ) as call: - call.return_value = backupvault.ListBackupVaultsResponse() - client.list_backup_vaults(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.trigger_restore_verification(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 = backupvault.ListBackupVaultsRequest() - 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_fetch_usable_backup_vaults_empty_call_grpc(): +def test_trigger_restore_verification_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.trigger_restore_verification), "__call__" ) as call: - call.return_value = backupvault.FetchUsableBackupVaultsResponse() - client.fetch_usable_backup_vaults(request=None) + # 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.trigger_restore_verification( + 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 = backupvault.FetchUsableBackupVaultsRequest() - 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_backup_vault_empty_call_grpc(): +def test_trigger_restore_verification_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: - call.return_value = backupvault.BackupVault() - client.get_backup_vault(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetBackupVaultRequest() - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.trigger_restore_verification( + restore_verification_plan_association.TriggerRestoreVerificationRequest(), + 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. -def test_update_backup_vault_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_trigger_restore_verification_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_vault), "__call__" + type(client.transport.trigger_restore_verification), "__call__" ) as call: + # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup_vault(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + 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.trigger_restore_verification( + 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 = backupvault.UpdateBackupVaultRequest() - 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_backup_vault_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_vault), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup_vault(request=None) +@pytest.mark.asyncio +async def test_trigger_restore_verification_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.DeleteBackupVaultRequest() - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.trigger_restore_verification( + restore_verification_plan_association.TriggerRestoreVerificationRequest(), + 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. -def test_list_data_sources_empty_call_grpc(): +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan.GetRestoreVerificationPlanRequest(), + {}, + ], +) +def test_get_restore_verification_plan(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. + # 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_data_sources), "__call__" + type(client.transport.get_restore_verification_plan), "__call__" ) as call: - call.return_value = backupvault.ListDataSourcesResponse() - client.list_data_sources(request=None) + # Designate an appropriate return value for the call. + call.return_value = restore_verification_plan.RestoreVerificationPlan( + name="name_value", + description="description_value", + state=restore_verification_plan.RestoreVerificationPlan.State.CREATING, + schedule="schedule_value", + time_zone="time_zone_value", + ) + response = client.get_restore_verification_plan(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 = backupvault.ListDataSourcesRequest() - assert args[0] == request_msg - + request = restore_verification_plan.GetRestoreVerificationPlanRequest() + assert args[0] == 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_get_data_source_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + # Establish that the response is the type that we expect. + assert isinstance(response, restore_verification_plan.RestoreVerificationPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan.RestoreVerificationPlan.State.CREATING ) - - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: - call.return_value = backupvault.DataSource() - client.get_data_source(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetDataSourceRequest() - assert args[0] == request_msg + assert response.schedule == "schedule_value" + assert response.time_zone == "time_zone_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_update_data_source_empty_call_grpc(): +def test_get_restore_verification_plan_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - # Mock the actual call, and fake the request. + # 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 = restore_verification_plan.GetRestoreVerificationPlanRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_source), "__call__" + type(client.transport.get_restore_verification_plan), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_data_source(request=None) - - # Establish that the underlying stub method was called. + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_restore_verification_plan(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateDataSourceRequest() + request_msg = restore_verification_plan.GetRestoreVerificationPlanRequest( + name="name_value", + ) 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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_get_restore_verification_plan_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 = BackupDRClient( + 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 = backupvault.ListBackupsResponse() - client.list_backups(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListBackupsRequest() - assert args[0] == request_msg + # Ensure method has been cached + assert ( + client._transport.get_restore_verification_plan + 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_restore_verification_plan + ] = mock_rpc + request = {} + client.get_restore_verification_plan(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_fetch_backups_for_resource_type_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" - ) as call: - call.return_value = backupvault.FetchBackupsForResourceTypeResponse() - client.fetch_backups_for_resource_type(request=None) + client.get_restore_verification_plan(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.FetchBackupsForResourceTypeRequest() - assert args[0] == request_msg + # 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. -def test_get_backup_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +@pytest.mark.asyncio +async def test_get_restore_verification_plan_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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup), "__call__") as call: - call.return_value = backupvault.Backup() - client.get_backup(request=None) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetBackupRequest() - assert args[0] == request_msg + # Ensure method has been cached + assert ( + client._client._transport.get_restore_verification_plan + 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_restore_verification_plan + ] = mock_rpc -# 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_backup_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request = {} + await client.get_restore_verification_plan(request) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_backup), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup(request=None) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateBackupRequest() - assert args[0] == request_msg + await client.get_restore_verification_plan(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. -def test_delete_backup_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan.GetRestoreVerificationPlanRequest(), + {}, + ], +) +async def test_get_restore_verification_plan_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # 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) + # 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.get_restore_verification_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan.RestoreVerificationPlan( + name="name_value", + description="description_value", + state=restore_verification_plan.RestoreVerificationPlan.State.CREATING, + schedule="schedule_value", + time_zone="time_zone_value", + ) + ) + response = await client.get_restore_verification_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = backupvault.DeleteBackupRequest() - assert args[0] == request_msg + request = restore_verification_plan.GetRestoreVerificationPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, restore_verification_plan.RestoreVerificationPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan.RestoreVerificationPlan.State.CREATING + ) + assert response.schedule == "schedule_value" + assert response.time_zone == "time_zone_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_restore_backup_empty_call_grpc(): +def test_get_restore_verification_plan_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.restore_backup(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 = restore_verification_plan.GetRestoreVerificationPlanRequest() - # 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_restore_verification_plan), "__call__" + ) as call: + call.return_value = restore_verification_plan.RestoreVerificationPlan() + client.get_restore_verification_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = backupvault.RestoreBackupRequest() - 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_backup_plan_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_restore_verification_plan_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # 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 = restore_verification_plan.GetRestoreVerificationPlanRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" + type(client.transport.get_restore_verification_plan), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup_plan(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan.RestoreVerificationPlan() + ) + await client.get_restore_verification_plan(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 = backupplan.CreateBackupPlanRequest() - 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_backup_plan_empty_call_grpc(): +def test_get_restore_verification_plan_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_plan), "__call__" + type(client.transport.get_restore_verification_plan), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup_plan(request=None) + # Designate an appropriate return value for the call. + call.return_value = restore_verification_plan.RestoreVerificationPlan() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_restore_verification_plan( + 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 = backupplan.UpdateBackupPlanRequest() - 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_backup_plan_empty_call_grpc(): +def test_get_restore_verification_plan_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: - call.return_value = backupplan.BackupPlan() - client.get_backup_plan(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.GetBackupPlanRequest() - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_restore_verification_plan( + restore_verification_plan.GetRestoreVerificationPlanRequest(), + 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. -def test_list_backup_plans_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_restore_verification_plan_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" + type(client.transport.get_restore_verification_plan), "__call__" ) as call: - call.return_value = backupplan.ListBackupPlansResponse() - client.list_backup_plans(request=None) + # Designate an appropriate return value for the call. + call.return_value = restore_verification_plan.RestoreVerificationPlan() - # Establish that the underlying stub method was called. - call.assert_called() + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan.RestoreVerificationPlan() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_restore_verification_plan( + 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 = backupplan.ListBackupPlansRequest() - 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_backup_plan_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_restore_verification_plan_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup_plan(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.DeleteBackupPlanRequest() - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_restore_verification_plan( + restore_verification_plan.GetRestoreVerificationPlanRequest(), + 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. -def test_get_backup_plan_revision_empty_call_grpc(): +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan.ListRestoreVerificationPlansRequest(), + {}, + ], +) +def test_list_restore_verification_plans(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. + # 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_backup_plan_revision), "__call__" + type(client.transport.list_restore_verification_plans), "__call__" ) as call: - call.return_value = backupplan.BackupPlanRevision() - client.get_backup_plan_revision(request=None) + # Designate an appropriate return value for the call. + call.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = client.list_restore_verification_plans(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 = backupplan.GetBackupPlanRevisionRequest() - assert args[0] == request_msg + request = restore_verification_plan.ListRestoreVerificationPlansRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreVerificationPlansPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_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_backup_plan_revisions_empty_call_grpc(): + +def test_list_restore_verification_plans_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - # Mock the actual call, and fake the request. + # 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 = restore_verification_plan.ListRestoreVerificationPlansRequest( + 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_backup_plan_revisions), "__call__" + type(client.transport.list_restore_verification_plans), "__call__" ) as call: - call.return_value = backupplan.ListBackupPlanRevisionsResponse() - client.list_backup_plan_revisions(request=None) - - # Establish that the underlying stub method was called. + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_restore_verification_plans(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplan.ListBackupPlanRevisionsRequest() + request_msg = restore_verification_plan.ListRestoreVerificationPlansRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) 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_backup_plan_association_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_backup_plan_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup_plan_association(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() - assert args[0] == request_msg - +def test_list_restore_verification_plans_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) -# 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_backup_plan_association_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup_plan_association(request=None) + # Ensure method has been cached + assert ( + client._transport.list_restore_verification_plans + in client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() - assert args[0] == request_msg + # 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_restore_verification_plans + ] = mock_rpc + request = {} + client.list_restore_verification_plans(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# 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_plan_association_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + client.list_restore_verification_plans(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" - ) as call: - call.return_value = backupplanassociation.BackupPlanAssociation() - client.get_backup_plan_association(request=None) + # 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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.GetBackupPlanAssociationRequest() - assert args[0] == request_msg +@pytest.mark.asyncio +async def test_list_restore_verification_plans_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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) -# 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_plan_associations_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_associations), "__call__" - ) as call: - call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() - client.list_backup_plan_associations(request=None) + # Ensure method has been cached + assert ( + client._client._transport.list_restore_verification_plans + in client._client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() - assert args[0] == request_msg + # 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_restore_verification_plans + ] = mock_rpc + request = {} + await client.list_restore_verification_plans(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_fetch_backup_plan_associations_for_resource_type_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", - ) as call: - call.return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - ) - client.fetch_backup_plan_associations_for_resource_type(request=None) + await client.list_restore_verification_plans(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() - ) - assert args[0] == request_msg + # 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. -def test_delete_backup_plan_association_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan.ListRestoreVerificationPlansRequest(), + {}, + ], +) +async def test_list_restore_verification_plans_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # Mock the actual call, and fake the request. + # 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_plan_association), "__call__" + type(client.transport.list_restore_verification_plans), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup_plan_association(request=None) + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan.ListRestoreVerificationPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_restore_verification_plans(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 = backupplanassociation.DeleteBackupPlanAssociationRequest() - assert args[0] == request_msg + request = restore_verification_plan.ListRestoreVerificationPlansRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreVerificationPlansAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_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_trigger_backup_empty_call_grpc(): +def test_list_restore_verification_plans_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.trigger_backup(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.TriggerBackupRequest() - 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 = restore_verification_plan.ListRestoreVerificationPlansRequest() -# 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_data_source_reference_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request.parent = "parent_value" - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" + type(client.transport.list_restore_verification_plans), "__call__" ) as call: - call.return_value = datasourcereference.DataSourceReference() - client.get_data_source_reference(request=None) + call.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) + client.list_restore_verification_plans(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 = datasourcereference.GetDataSourceReferenceRequest() - 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", + "parent=parent_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_list_data_source_references_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + +@pytest.mark.asyncio +async def test_list_restore_verification_plans_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. + # 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 = restore_verification_plan.ListRestoreVerificationPlansRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" + type(client.transport.list_restore_verification_plans), "__call__" ) as call: - call.return_value = datasourcereference.ListDataSourceReferencesResponse() - client.list_data_source_references(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) + await client.list_restore_verification_plans(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 = datasourcereference.ListDataSourceReferencesRequest() - 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", + "parent=parent_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_fetch_data_source_references_for_resource_type_empty_call_grpc(): +def test_list_restore_verification_plans_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", + type(client.transport.list_restore_verification_plans), "__call__" ) as call: + # Designate an appropriate return value for the call. call.return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_restore_verification_plans( + parent="parent_value", ) - client.fetch_data_source_references_for_resource_type(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 = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() - ) - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_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_initialize_service_empty_call_grpc(): +def test_list_restore_verification_plans_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.initialize_service), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.initialize_service(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.InitializeServiceRequest() - assert args[0] == request_msg - - -def test_transport_kind_grpc_asyncio(): - transport = BackupDRAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() ) - assert transport.kind == "grpc_asyncio" - -def test_initialize_client_w_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_restore_verification_plans( + restore_verification_plan.ListRestoreVerificationPlansRequest(), + parent="parent_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_list_management_servers_empty_call_grpc_asyncio(): +async def test_list_restore_verification_plans_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_management_servers), "__call__" + type(client.transport.list_restore_verification_plans), "__call__" ) as call: # Designate an appropriate return value for the call. + call.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupdr.ListManagementServersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_restore_verification_plans( + parent="parent_value", ) - await client.list_management_servers(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) _, args, _ = call.mock_calls[0] - request_msg = backupdr.ListManagementServersRequest() - assert args[0] == request_msg + arg = args[0].parent + mock_val = "parent_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_management_server_empty_call_grpc_asyncio(): +async def test_list_restore_verification_plans_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_management_server), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupdr.ManagementServer( - name="name_value", - description="description_value", - type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, - state=backupdr.ManagementServer.InstanceState.CREATING, - etag="etag_value", - oauth2_client_id="oauth2_client_id_value", - ba_proxy_uri=["ba_proxy_uri_value"], - satisfies_pzi=True, - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_restore_verification_plans( + restore_verification_plan.ListRestoreVerificationPlansRequest(), + parent="parent_value", ) - await client.get_management_server(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.GetManagementServerRequest() - 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_management_server_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_restore_verification_plans_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_management_server), "__call__" + type(client.transport.list_restore_verification_plans), "__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 the response to a series of pages. + call.side_effect = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), + RuntimeError, ) - await client.create_management_server(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.CreateManagementServerRequest() - assert args[0] == request_msg + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_restore_verification_plans( + request={}, retry=retry, timeout=timeout + ) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout -# 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_management_server_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_management_server), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, restore_verification_plan.RestoreVerificationPlan) + for i in results ) - await client.delete_management_server(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.DeleteManagementServerRequest() - 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_backup_vault_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_restore_verification_plans_pages(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" + type(client.transport.list_restore_verification_plans), "__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 the response to a series of pages. + call.side_effect = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), + RuntimeError, ) - await client.create_backup_vault(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.CreateBackupVaultRequest() - assert args[0] == request_msg + pages = list(client.list_restore_verification_plans(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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_vaults_empty_call_grpc_asyncio(): +async def test_list_restore_verification_plans_async_pager(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" + type(client.transport.list_restore_verification_plans), + "__call__", + new_callable=mock.AsyncMock, ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListBackupVaultsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), + RuntimeError, ) - await client.list_backup_vaults(request=None) + async_pager = await client.list_restore_verification_plans( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListBackupVaultsRequest() - assert args[0] == request_msg + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all( + isinstance(i, restore_verification_plan.RestoreVerificationPlan) + for i in responses + ) -# 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_fetch_usable_backup_vaults_empty_call_grpc_asyncio(): +async def test_list_restore_verification_plans_async_pages(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_verification_plans), + "__call__", + new_callable=mock.AsyncMock, ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchUsableBackupVaultsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), + RuntimeError, ) - await client.fetch_usable_backup_vaults(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.FetchUsableBackupVaultsRequest() - assert args[0] == request_msg + pages = [] + async for page_ in ( + await client.list_restore_verification_plans(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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_vault_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), + {}, + ], +) +def test_delete_restore_verification_plan(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup_vault), "__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_restore_verification_plan), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.BackupVault( - name="name_value", - description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, - deletable=True, - etag="etag_value", - state=backupvault.BackupVault.State.CREATING, - backup_count=1278, - service_account="service_account_value", - total_stored_bytes=1946, - uid="uid_value", - access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, - ) - ) - await client.get_backup_vault(request=None) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_restore_verification_plan(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 = backupvault.GetBackupVaultRequest() - assert args[0] == request_msg + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + 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_update_backup_vault_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_delete_restore_verification_plan_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Mock the actual call, and fake the request. + # 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 = restore_verification_plan.DeleteRestoreVerificationPlanRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_vault), "__call__" + type(client.transport.delete_restore_verification_plan), "__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.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - await client.update_backup_vault(request=None) - - # Establish that the underlying stub method was called. + client.delete_restore_verification_plan(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateBackupVaultRequest() + request_msg = restore_verification_plan.DeleteRestoreVerificationPlanRequest( + name="name_value", + ) 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_vault_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) +def test_delete_restore_verification_plan_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_vault), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # 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_restore_verification_plan + in client._transport._wrapped_methods ) - await client.delete_backup_vault(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.DeleteBackupVaultRequest() - assert args[0] == request_msg + # 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_restore_verification_plan + ] = mock_rpc + request = {} + client.delete_restore_verification_plan(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# 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_data_sources_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # 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() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListDataSourcesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_data_sources(request=None) + client.delete_restore_verification_plan(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListDataSourcesRequest() - assert args[0] == request_msg + # 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_get_data_source_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) +async def test_delete_restore_verification_plan_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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.DataSource( - name="name_value", - state=backupvault.DataSource.State.CREATING, - backup_count=1278, - etag="etag_value", - total_stored_bytes=1946, - config_state=backupvault.BackupConfigState.ACTIVE, - backup_blocked_by_vault_access_restriction=True, - ) + # 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_restore_verification_plan + in client._client._transport._wrapped_methods ) - await client.get_data_source(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetDataSourceRequest() - assert args[0] == request_msg + # 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_restore_verification_plan + ] = mock_rpc + + request = {} + await client.delete_restore_verification_plan(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_restore_verification_plan(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_update_data_source_empty_call_grpc_asyncio(): +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), + {}, + ], +) +async def test_delete_restore_verification_plan_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + transport=transport, ) - # Mock the actual call, and fake the request. + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_source), "__call__" + type(client.transport.delete_restore_verification_plan), "__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_data_source(request=None) + response = await client.delete_restore_verification_plan(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 = backupvault.UpdateDataSourceRequest() - assert args[0] == request_msg + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + 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_list_backups_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_restore_verification_plan_field_headers(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # 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( - backupvault.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_backups(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 = restore_verification_plan.DeleteRestoreVerificationPlanRequest() - # 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_restore_verification_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_verification_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListBackupsRequest() - 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_fetch_backups_for_resource_type_empty_call_grpc_asyncio(): +async def test_delete_restore_verification_plan_field_headers_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. + # 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 = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.delete_restore_verification_plan), "__call__" ) as call: - # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchBackupsForResourceTypeResponse( - next_page_token="next_page_token_value", - ) + operations_pb2.Operation(name="operations/op") ) - await client.fetch_backups_for_resource_type(request=None) + await client.delete_restore_verification_plan(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 = backupvault.FetchBackupsForResourceTypeRequest() - 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_get_backup_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_restore_verification_plan_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.Backup( - name="name_value", - description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, - etag="etag_value", - state=backupvault.Backup.State.CREATING, - backup_type=backupvault.Backup.BackupType.SCHEDULED, - resource_size_bytes=2056, - satisfies_pzs=True, - satisfies_pzi=True, - kms_key_versions=["kms_key_versions_value"], - ) + 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_restore_verification_plan( + name="name_value", ) - await client.get_backup(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 = backupvault.GetBackupRequest() - 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_update_backup_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_restore_verification_plan_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_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") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_restore_verification_plan( + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), + name="name_value", ) - await client.update_backup(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateBackupRequest() - 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(): +async def test_delete_restore_verification_plan_flattened_async(): client = BackupDRAsyncClient( 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: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan), "__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_backup(request=None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_restore_verification_plan( + 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 = backupvault.DeleteBackupRequest() - 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_restore_backup_empty_call_grpc_asyncio(): +async def test_delete_restore_verification_plan_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.restore_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") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_restore_verification_plan( + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), + name="name_value", ) - await client.restore_backup(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.RestoreBackupRequest() - assert args[0] == request_msg +def test_list_management_servers_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# 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_backup_plan_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Ensure method has been cached + assert ( + client._transport.list_management_servers + in client._transport._wrapped_methods ) - await client.create_backup_plan(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.CreateBackupPlanRequest() - assert args[0] == request_msg + # 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_management_servers + ] = mock_rpc + request = {} + client.list_management_servers(request) -# 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_backup_plan_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan), "__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_backup_plan(request=None) + client.list_management_servers(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.UpdateBackupPlanRequest() - assert args[0] == request_msg + # 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_get_backup_plan_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_management_servers_rest_required_fields( + request_type=backupdr.ListManagementServersRequest, +): + transport_class = transports.BackupDRRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlan( - name="name_value", - description="description_value", - state=backupplan.BackupPlan.State.CREATING, - resource_type="resource_type_value", - etag="etag_value", - backup_vault="backup_vault_value", - backup_vault_service_account="backup_vault_service_account_value", - log_retention_days=1929, - supported_resource_types=["supported_resource_types_value"], - revision_id="revision_id_value", - revision_name="revision_name_value", - ) - ) - await client.get_backup_plan(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.GetBackupPlanRequest() - assert args[0] == request_msg + default_values = getattr( + transport_class._BaseListManagementServers, + "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -# 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_plans_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + jsonified_request["parent"] = "parent_value" - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlansResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", ) - await client.list_backup_plans(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.ListBackupPlansRequest() - assert args[0] == request_msg + ) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_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_backup_plan_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan), "__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_plan(request=None) + # Designate an appropriate value for the returned response. + return_value = backupdr.ListManagementServersResponse() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.DeleteBackupPlanRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupdr.ListManagementServersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_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_get_backup_plan_revision_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.get_backup_plan_revision), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlanRevision( - name="name_value", - revision_id="revision_id_value", - state=backupplan.BackupPlanRevision.State.CREATING, - ) - ) - await client.get_backup_plan_revision(request=None) + response = client.list_management_servers(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.GetBackupPlanRevisionRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_plan_revisions_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_management_servers_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_revisions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlanRevisionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_backup_plan_revisions(request=None) + # 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 = backupdr.ListManagementServersResponse() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.ListBackupPlanRevisionsRequest() - assert args[0] == request_msg + # 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) -# 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_backup_plan_association_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupdr.ListManagementServersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.create_backup_plan_association), "__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_backup_plan_association(request=None) + client.list_management_servers(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() - assert args[0] == request_msg + # 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/*}/managementServers" + % client.transport._host, + args[1], + ) -# 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_backup_plan_association_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_management_servers_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan_association), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_management_servers( + backupdr.ListManagementServersRequest(), + parent="parent_value", ) - await client.update_backup_plan_association(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() - 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_plan_association_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_management_servers_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.BackupPlanAssociation( - name="name_value", - resource_type="resource_type_value", - resource="resource_value", - backup_plan="backup_plan_value", - state=backupplanassociation.BackupPlanAssociation.State.CREATING, - data_source="data_source_value", - backup_plan_revision_id="backup_plan_revision_id_value", - backup_plan_revision_name="backup_plan_revision_name_value", - ) + # 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 = ( + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + next_page_token="abc", + ), + backupdr.ListManagementServersResponse( + management_servers=[], + next_page_token="def", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + ], + next_page_token="ghi", + ), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + ], + ), ) - await client.get_backup_plan_association(request=None) + # Two responses for two calls + response = response + response - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.GetBackupPlanAssociationRequest() - assert args[0] == request_msg + # Wrap the values into proper Response objs + response = tuple( + backupdr.ListManagementServersResponse.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"} -# 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_plan_associations_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + pager = client.list_management_servers(request=sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_associations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.ListBackupPlanAssociationsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_backup_plan_associations(request=None) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() - assert args[0] == request_msg + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupdr.ManagementServer) for i in results) + pages = list(client.list_management_servers(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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_fetch_backup_plan_associations_for_resource_type_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - next_page_token="next_page_token_value", - ) +def test_get_management_server_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - await client.fetch_backup_plan_associations_for_resource_type(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() - ) - assert args[0] == request_msg + # 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_management_server + in client._transport._wrapped_methods + ) -# 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_plan_association_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # 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_management_server] = ( + mock_rpc + ) + + request = {} + client.get_management_server(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_management_server(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_management_server_rest_required_fields( + request_type=backupdr.GetManagementServerRequest, +): + transport_class = transports.BackupDRRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan_association), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # verify fields with default values are dropped + + default_values = getattr( + transport_class._BaseGetManagementServer, + "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupdr.ManagementServer() + # 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 = backupdr.ManagementServer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_management_server(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_management_server_rest_flattened(): + client = BackupDRClient( + 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 = backupdr.ManagementServer() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/managementServers/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - await client.delete_backup_plan_association(request=None) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() - assert args[0] == request_msg + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupdr.ManagementServer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_management_server(**mock_args) -# 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_trigger_backup_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # 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/*/managementServers/*}" + % client.transport._host, + args[1], + ) + + +def test_get_management_server_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.trigger_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") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_management_server( + backupdr.GetManagementServerRequest(), + name="name_value", ) - await client.trigger_backup(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.TriggerBackupRequest() - assert args[0] == request_msg +def test_create_management_server_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# 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_data_source_reference_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # 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_management_server + 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_management_server + ] = mock_rpc + + request = {} + client.create_management_server(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_management_server(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_management_server_rest_required_fields( + request_type=backupdr.CreateManagementServerRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["management_server_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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.DataSourceReference( - name="name_value", - data_source="data_source_value", - data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, - data_source_backup_count=2535, - total_stored_bytes=1946, - ) + # verify fields with default values are dropped + assert "managementServerId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateManagementServer, + "_BaseCreateManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "managementServerId" in jsonified_request + assert ( + jsonified_request["managementServerId"] == request_init["management_server_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["managementServerId"] = "management_server_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "managementServerId", + "requestId", ) - await client.get_data_source_reference(request=None) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasourcereference.GetDataSourceReferenceRequest() - assert args[0] == request_msg + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "managementServerId" in jsonified_request + assert jsonified_request["managementServerId"] == "management_server_id_value" + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) -# 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_data_source_references_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # 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_management_server(request) + + expected_params = [ + ( + "managementServerId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_management_server_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.ListDataSourceReferencesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + # 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", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_id_value", ) - await client.list_data_source_references(request=None) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasourcereference.ListDataSourceReferencesRequest() - assert args[0] == request_msg + # 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_management_server(**mock_args) -# 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_fetch_data_source_references_for_resource_type_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # 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/*}/managementServers" + % client.transport._host, + args[1], + ) + + +def test_create_management_server_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - next_page_token="next_page_token_value", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_management_server( + backupdr.CreateManagementServerRequest(), + parent="parent_value", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_id_value", ) - await client.fetch_data_source_references_for_resource_type(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + +def test_delete_management_server_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert args[0] == request_msg + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# 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_initialize_service_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # Ensure method has been cached + assert ( + client._transport.delete_management_server + 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_management_server + ] = mock_rpc + + request = {} + client.delete_management_server(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_management_server(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_management_server_rest_required_fields( + request_type=backupdr.DeleteManagementServerRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteManagementServer, + "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_management_server(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_management_server_rest_flattened(): + client = BackupDRClient( + 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/managementServers/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_management_server(**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/*/managementServers/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_management_server_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_management_server( + backupdr.DeleteManagementServerRequest(), + name="name_value", + ) + + +def test_create_backup_vault_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 = BackupDRClient( + 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_backup_vault 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_backup_vault] = ( + mock_rpc + ) + + request = {} + client.create_backup_vault(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_backup_vault(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_backup_vault_rest_required_fields( + request_type=backupvault.CreateBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_vault_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 "backupVaultId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateBackupVault, + "_BaseCreateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupVaultId" in jsonified_request + assert jsonified_request["backupVaultId"] == request_init["backup_vault_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["backupVaultId"] = "backup_vault_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backupVaultId", + "requestId", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupVaultId" in jsonified_request + assert jsonified_request["backupVaultId"] == "backup_vault_id_value" + + client = BackupDRClient( + 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_backup_vault(request) + + expected_params = [ + ( + "backupVaultId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_backup_vault_rest_flattened(): + client = BackupDRClient( + 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", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_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_backup_vault(**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/*}/backupVaults" + % client.transport._host, + args[1], + ) + + +def test_create_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_vault( + backupvault.CreateBackupVaultRequest(), + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", + ) + + +def test_list_backup_vaults_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 = BackupDRClient( + 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_vaults 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_vaults] = ( + mock_rpc + ) + + request = {} + client.list_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_vaults(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_vaults_rest_required_fields( + request_type=backupvault.ListBackupVaultsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBackupVaults, + "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.ListBackupVaultsResponse() + # 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 = backupvault.ListBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_vaults(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_vaults_rest_flattened(): + client = BackupDRClient( + 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 = backupvault.ListBackupVaultsResponse() + + # 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 = backupvault.ListBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_vaults(**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/*}/backupVaults" + % client.transport._host, + args[1], + ) + + +def test_list_backup_vaults_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_vaults( + backupvault.ListBackupVaultsRequest(), + parent="parent_value", + ) + + +def test_list_backup_vaults_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.ListBackupVaultsResponse.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_vaults(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, backupvault.BackupVault) for i in results) + + pages = list(client.list_backup_vaults(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_usable_backup_vaults_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 = BackupDRClient( + 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.fetch_usable_backup_vaults + 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.fetch_usable_backup_vaults + ] = mock_rpc + + request = {} + client.fetch_usable_backup_vaults(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_usable_backup_vaults(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_fetch_usable_backup_vaults_rest_required_fields( + request_type=backupvault.FetchUsableBackupVaultsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseFetchUsableBackupVaults, + "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchUsableBackupVaultsResponse() + # 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 = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_usable_backup_vaults(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_usable_backup_vaults_rest_flattened(): + client = BackupDRClient( + 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 = backupvault.FetchUsableBackupVaultsResponse() + + # 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 = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_usable_backup_vaults(**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/*}/backupVaults:fetchUsable" + % client.transport._host, + args[1], + ) + + +def test_fetch_usable_backup_vaults_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.fetch_usable_backup_vaults( + backupvault.FetchUsableBackupVaultsRequest(), + parent="parent_value", + ) + + +def test_fetch_usable_backup_vaults_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.FetchUsableBackupVaultsResponse.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.fetch_usable_backup_vaults(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, backupvault.BackupVault) for i in results) + + pages = list(client.fetch_usable_backup_vaults(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_vault_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 = BackupDRClient( + 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_vault 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_vault] = ( + mock_rpc + ) + + request = {} + client.get_backup_vault(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_vault(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_vault_rest_required_fields( + request_type=backupvault.GetBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBackupVault, + "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.BackupVault() + # 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 = backupvault.BackupVault.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_vault(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_vault_rest_flattened(): + client = BackupDRClient( + 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 = backupvault.BackupVault() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/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 = backupvault.BackupVault.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_vault(**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/*/backupVaults/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_vault( + backupvault.GetBackupVaultRequest(), + name="name_value", + ) + + +def test_update_backup_vault_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 = BackupDRClient( + 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_backup_vault 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_backup_vault] = ( + mock_rpc + ) + + request = {} + client.update_backup_vault(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_backup_vault(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_backup_vault_rest_required_fields( + request_type=backupvault.UpdateBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateBackupVault, + "_BaseUpdateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "forceUpdateAccessRestriction", + "requestId", + "updateMask", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_backup_vault(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_backup_vault_rest_flattened(): + client = BackupDRClient( + 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 = { + "backup_vault": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup_vault=backupvault.BackupVault(name="name_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_backup_vault(**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/{backup_vault.name=projects/*/locations/*/backupVaults/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_vault( + backupvault.UpdateBackupVaultRequest(), + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_backup_vault_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 = BackupDRClient( + 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_vault 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_vault] = ( + mock_rpc + ) + + request = {} + client.delete_backup_vault(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_vault(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_vault_rest_required_fields( + request_type=backupvault.DeleteBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteBackupVault, + "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allowMissing", + "etag", + "force", + "ignoreBackupPlanReferences", + "requestId", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_vault(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_vault_rest_flattened(): + client = BackupDRClient( + 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/backupVaults/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_backup_vault(**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/*/backupVaults/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_vault( + backupvault.DeleteBackupVaultRequest(), + name="name_value", + ) + + +def test_list_data_sources_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 = BackupDRClient( + 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_data_sources 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_data_sources] = ( + mock_rpc + ) + + request = {} + client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_sources(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_data_sources_rest_required_fields( + request_type=backupvault.ListDataSourcesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListDataSources, + "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.ListDataSourcesResponse() + # 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 = backupvault.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_data_sources(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_data_sources_rest_flattened(): + client = BackupDRClient( + 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 = backupvault.ListDataSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/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 = backupvault.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_sources(**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/*/backupVaults/*}/dataSources" + % client.transport._host, + args[1], + ) + + +def test_list_data_sources_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_sources( + backupvault.ListDataSourcesRequest(), + parent="parent_value", + ) + + +def test_list_data_sources_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.ListDataSourcesResponse.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/backupVaults/sample3" + } + + pager = client.list_data_sources(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, backupvault.DataSource) for i in results) + + pages = list(client.list_data_sources(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_data_source_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 = BackupDRClient( + 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_data_source 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_data_source] = mock_rpc + + request = {} + client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source(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_data_source_rest_required_fields( + request_type=backupvault.GetDataSourceRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetDataSource, + "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.DataSource() + # 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 = backupvault.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_data_source(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_data_source_rest_flattened(): + client = BackupDRClient( + 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 = backupvault.DataSource() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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 = backupvault.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_source(**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/*/backupVaults/*/dataSources/*}" + % client.transport._host, + args[1], + ) + + +def test_get_data_source_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_source( + backupvault.GetDataSourceRequest(), + name="name_value", + ) + + +def test_update_data_source_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 = BackupDRClient( + 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_data_source 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_data_source] = ( + mock_rpc + ) + + request = {} + client.update_data_source(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_data_source(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_data_source_rest_required_fields( + request_type=backupvault.UpdateDataSourceRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateDataSource, + "_BaseUpdateDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allowMissing", + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_data_source(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_data_source_rest_flattened(): + client = BackupDRClient( + 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 = { + "data_source": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + data_source=backupvault.DataSource(name="name_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_data_source(**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/{data_source.name=projects/*/locations/*/backupVaults/*/dataSources/*}" + % client.transport._host, + args[1], + ) + + +def test_update_data_source_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_source( + backupvault.UpdateDataSourceRequest(), + data_source=backupvault.DataSource(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = BackupDRClient( + 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=backupvault.ListBackupsRequest): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBackups, + "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.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 = backupvault.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_flattened(): + client = BackupDRClient( + 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 = backupvault.ListBackupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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 = backupvault.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/v1/{parent=projects/*/locations/*/backupVaults/*/dataSources/*}/backups" + % client.transport._host, + args[1], + ) + + +def test_list_backups_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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( + backupvault.ListBackupsRequest(), + parent="parent_value", + ) + + +def test_list_backups_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(backupvault.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/backupVaults/sample3/dataSources/sample4" + } + + 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, backupvault.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_fetch_backups_for_resource_type_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 = BackupDRClient( + 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.fetch_backups_for_resource_type + 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.fetch_backups_for_resource_type + ] = mock_rpc + + request = {} + client.fetch_backups_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_backups_for_resource_type(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_fetch_backups_for_resource_type_rest_required_fields( + request_type=backupvault.FetchBackupsForResourceTypeRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["resource_type"] = "" + 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 "resourceType" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchBackupsForResourceType, + "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == request_init["resource_type"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["resourceType"] = "resource_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "resourceType", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchBackupsForResourceTypeResponse() + # 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 = backupvault.FetchBackupsForResourceTypeResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_backups_for_resource_type(request) + + expected_params = [ + ( + "resourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_backups_for_resource_type_rest_flattened(): + client = BackupDRClient( + 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 = backupvault.FetchBackupsForResourceTypeResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource_type="resource_type_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 = backupvault.FetchBackupsForResourceTypeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_backups_for_resource_type(**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/*/backupVaults/*/dataSources/*}/backups:fetchForResourceType" + % client.transport._host, + args[1], + ) + + +def test_fetch_backups_for_resource_type_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.fetch_backups_for_resource_type( + backupvault.FetchBackupsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_backups_for_resource_type_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], + next_page_token="def", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.FetchBackupsForResourceTypeResponse.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/backupVaults/sample3/dataSources/sample4" + } + + pager = client.fetch_backups_for_resource_type(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, backupvault.Backup) for i in results) + + pages = list( + client.fetch_backups_for_resource_type(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 = BackupDRClient( + 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=backupvault.GetBackupRequest): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBackup, + "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.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 = backupvault.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_flattened(): + client = BackupDRClient( + 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 = backupvault.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/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 = backupvault.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/v1/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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( + backupvault.GetBackupRequest(), + name="name_value", + ) + + +def test_update_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 = BackupDRClient( + 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_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.update_backup] = mock_rpc + + request = {} + client.update_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.update_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_update_backup_rest_required_fields( + request_type=backupvault.UpdateBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateBackup, + "_BaseUpdateBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_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_update_backup_rest_flattened(): + client = BackupDRClient( + 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 = { + "backup": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup=backupvault.Backup(name="name_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_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/v1/{backup.name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup( + backupvault.UpdateBackupRequest(), + backup=backupvault.Backup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = BackupDRClient( + 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=backupvault.DeleteBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteBackup, + "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_flattened(): + client = BackupDRClient( + 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/backupVaults/sample3/dataSources/sample4/backups/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_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/v1/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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( + backupvault.DeleteBackupRequest(), + name="name_value", + ) + + +def test_restore_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 = BackupDRClient( + 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.restore_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.restore_backup] = mock_rpc + + request = {} + client.restore_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.restore_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_restore_backup_rest_required_fields( + request_type=backupvault.RestoreBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseRestoreBackup, + "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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.restore_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_restore_backup_rest_flattened(): + client = BackupDRClient( + 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/backupVaults/sample3/dataSources/sample4/backups/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.restore_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/v1/{name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}:restore" + % client.transport._host, + args[1], + ) + + +def test_restore_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.restore_backup( + backupvault.RestoreBackupRequest(), + name="name_value", + ) + + +def test_create_backup_plan_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 = BackupDRClient( + 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_backup_plan 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_backup_plan] = ( + mock_rpc + ) + + request = {} + client.create_backup_plan(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_backup_plan(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_backup_plan_rest_required_fields( + request_type=backupplan.CreateBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_plan_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 "backupPlanId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateBackupPlan, + "_BaseCreateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupPlanId" in jsonified_request + assert jsonified_request["backupPlanId"] == request_init["backup_plan_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["backupPlanId"] = "backup_plan_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backupPlanId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupPlanId" in jsonified_request + assert jsonified_request["backupPlanId"] == "backup_plan_id_value" + + client = BackupDRClient( + 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_backup_plan(request) + + expected_params = [ + ( + "backupPlanId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_backup_plan_rest_flattened(): + client = BackupDRClient( + 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", + backup_plan=backupplan.BackupPlan(name="name_value"), + backup_plan_id="backup_plan_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_backup_plan(**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/*}/backupPlans" + % client.transport._host, + args[1], + ) + + +def test_create_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_plan( + backupplan.CreateBackupPlanRequest(), + parent="parent_value", + backup_plan=backupplan.BackupPlan(name="name_value"), + backup_plan_id="backup_plan_id_value", + ) + + +def test_update_backup_plan_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 = BackupDRClient( + 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_backup_plan 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_backup_plan] = ( + mock_rpc + ) + + request = {} + client.update_backup_plan(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_backup_plan(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_backup_plan_rest_required_fields( + request_type=backupplan.UpdateBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateBackupPlan, + "_BaseUpdateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_backup_plan(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_backup_plan_rest_flattened(): + client = BackupDRClient( + 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 = { + "backup_plan": { + "name": "projects/sample1/locations/sample2/backupPlans/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup_plan=backupplan.BackupPlan(name="name_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_backup_plan(**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/{backup_plan.name=projects/*/locations/*/backupPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_plan( + backupplan.UpdateBackupPlanRequest(), + backup_plan=backupplan.BackupPlan(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_backup_plan_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 = BackupDRClient( + 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_plan 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_plan] = mock_rpc + + request = {} + client.get_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan(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_plan_rest_required_fields( + request_type=backupplan.GetBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBackupPlan, + "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlan() + # 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 = backupplan.BackupPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan(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_plan_rest_flattened(): + client = BackupDRClient( + 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 = backupplan.BackupPlan() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlans/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 = backupplan.BackupPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan(**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/*/backupPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan( + backupplan.GetBackupPlanRequest(), + name="name_value", + ) + + +def test_list_backup_plans_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 = BackupDRClient( + 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_plans 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_plans] = ( + mock_rpc + ) + + request = {} + client.list_backup_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plans(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_plans_rest_required_fields( + request_type=backupplan.ListBackupPlansRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBackupPlans, + "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlansResponse() + # 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 = backupplan.ListBackupPlansResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plans(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_plans_rest_flattened(): + client = BackupDRClient( + 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 = backupplan.ListBackupPlansResponse() + + # 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 = backupplan.ListBackupPlansResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plans(**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/*}/backupPlans" + % client.transport._host, + args[1], + ) + + +def test_list_backup_plans_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plans( + backupplan.ListBackupPlansRequest(), + parent="parent_value", + ) + + +def test_list_backup_plans_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[], + next_page_token="def", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplan.ListBackupPlansResponse.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_plans(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, backupplan.BackupPlan) for i in results) + + pages = list(client.list_backup_plans(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_backup_plan_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 = BackupDRClient( + 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_plan 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_plan] = ( + mock_rpc + ) + + request = {} + client.delete_backup_plan(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_plan(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_plan_rest_required_fields( + request_type=backupplan.DeleteBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteBackupPlan, + "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_plan(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_plan_rest_flattened(): + client = BackupDRClient( + 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/backupPlans/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_backup_plan(**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/*/backupPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan( + backupplan.DeleteBackupPlanRequest(), + name="name_value", + ) + + +def test_get_backup_plan_revision_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 = BackupDRClient( + 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_plan_revision + 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_plan_revision + ] = mock_rpc + + request = {} + client.get_backup_plan_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan_revision(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_plan_revision_rest_required_fields( + request_type=backupplan.GetBackupPlanRevisionRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBackupPlanRevision, + "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlanRevision() + # 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 = backupplan.BackupPlanRevision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan_revision(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_plan_revision_rest_flattened(): + client = BackupDRClient( + 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 = backupplan.BackupPlanRevision() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/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 = backupplan.BackupPlanRevision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan_revision(**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/*/backupPlans/*/revisions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_plan_revision_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_revision( + backupplan.GetBackupPlanRevisionRequest(), + name="name_value", + ) + + +def test_list_backup_plan_revisions_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 = BackupDRClient( + 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_plan_revisions + 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_plan_revisions + ] = mock_rpc + + request = {} + client.list_backup_plan_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plan_revisions(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_plan_revisions_rest_required_fields( + request_type=backupplan.ListBackupPlanRevisionsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBackupPlanRevisions, + "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlanRevisionsResponse() + # 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 = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan_revisions(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_plan_revisions_rest_flattened(): + client = BackupDRClient( + 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 = backupplan.ListBackupPlanRevisionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupPlans/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 = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan_revisions(**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/*/backupPlans/*}/revisions" + % client.transport._host, + args[1], + ) + + +def test_list_backup_plan_revisions_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_revisions( + backupplan.ListBackupPlanRevisionsRequest(), + parent="parent_value", + ) + + +def test_list_backup_plan_revisions_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplan.ListBackupPlanRevisionsResponse.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/backupPlans/sample3" + } + + pager = client.list_backup_plan_revisions(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, backupplan.BackupPlanRevision) for i in results) + + pages = list(client.list_backup_plan_revisions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_backup_plan_association_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 = BackupDRClient( + 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_backup_plan_association + 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_backup_plan_association + ] = mock_rpc + + request = {} + client.create_backup_plan_association(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_backup_plan_association(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_backup_plan_association_rest_required_fields( + request_type=backupplanassociation.CreateBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_plan_association_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 "backupPlanAssociationId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateBackupPlanAssociation, + "_BaseCreateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupPlanAssociationId" in jsonified_request + assert ( + jsonified_request["backupPlanAssociationId"] + == request_init["backup_plan_association_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["backupPlanAssociationId"] = "backup_plan_association_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backupPlanAssociationId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupPlanAssociationId" in jsonified_request + assert ( + jsonified_request["backupPlanAssociationId"] + == "backup_plan_association_id_value" + ) + + client = BackupDRClient( + 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_backup_plan_association(request) + + expected_params = [ + ( + "backupPlanAssociationId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_backup_plan_association_rest_flattened(): + client = BackupDRClient( + 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", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + name="name_value" + ), + backup_plan_association_id="backup_plan_association_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_backup_plan_association(**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/*}/backupPlanAssociations" + % client.transport._host, + args[1], + ) + + +def test_create_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_plan_association( + backupplanassociation.CreateBackupPlanAssociationRequest(), + parent="parent_value", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + name="name_value" + ), + backup_plan_association_id="backup_plan_association_id_value", + ) + + +def test_update_backup_plan_association_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 = BackupDRClient( + 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_backup_plan_association + 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_backup_plan_association + ] = mock_rpc + + request = {} + client.update_backup_plan_association(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_backup_plan_association(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_backup_plan_association_rest_required_fields( + request_type=backupplanassociation.UpdateBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateBackupPlanAssociation, + "_BaseUpdateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_backup_plan_association(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_backup_plan_association_rest_flattened(): + client = BackupDRClient( + 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 = { + "backup_plan_association": { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup_plan_association=backupplanassociation.BackupPlanAssociation( + name="name_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_backup_plan_association(**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/{backup_plan_association.name=projects/*/locations/*/backupPlanAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_plan_association( + backupplanassociation.UpdateBackupPlanAssociationRequest(), + backup_plan_association=backupplanassociation.BackupPlanAssociation( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_backup_plan_association_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 = BackupDRClient( + 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_plan_association + 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_plan_association + ] = mock_rpc + + request = {} + client.get_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan_association(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_plan_association_rest_required_fields( + request_type=backupplanassociation.GetBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBackupPlanAssociation, + "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.BackupPlanAssociation() + # 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 = backupplanassociation.BackupPlanAssociation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan_association(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_plan_association_rest_flattened(): + client = BackupDRClient( + 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 = backupplanassociation.BackupPlanAssociation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/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 = backupplanassociation.BackupPlanAssociation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan_association(**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/*/backupPlanAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_association( + backupplanassociation.GetBackupPlanAssociationRequest(), + name="name_value", + ) + + +def test_list_backup_plan_associations_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 = BackupDRClient( + 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_plan_associations + 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_plan_associations + ] = mock_rpc + + request = {} + client.list_backup_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plan_associations(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_plan_associations_rest_required_fields( + request_type=backupplanassociation.ListBackupPlanAssociationsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBackupPlanAssociations, + "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + # 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 = backupplanassociation.ListBackupPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan_associations(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_plan_associations_rest_flattened(): + client = BackupDRClient( + 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 = backupplanassociation.ListBackupPlanAssociationsResponse() + + # 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 = backupplanassociation.ListBackupPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan_associations(**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/*}/backupPlanAssociations" + % client.transport._host, + args[1], + ) + + +def test_list_backup_plan_associations_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_associations( + backupplanassociation.ListBackupPlanAssociationsRequest(), + parent="parent_value", + ) + + +def test_list_backup_plan_associations_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplanassociation.ListBackupPlanAssociationsResponse.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_plan_associations(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, backupplanassociation.BackupPlanAssociation) for i in results + ) + + pages = list(client.list_backup_plan_associations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_backup_plan_associations_for_resource_type_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 = BackupDRClient( + 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.fetch_backup_plan_associations_for_resource_type + 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.fetch_backup_plan_associations_for_resource_type + ] = mock_rpc + + request = {} + client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_backup_plan_associations_for_resource_type(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_fetch_backup_plan_associations_for_resource_type_rest_required_fields( + request_type=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["resource_type"] = "" + 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 "resourceType" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchBackupPlanAssociationsForResourceType, + "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == request_init["resource_type"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["resourceType"] = "resource_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "resourceType", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + # 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 = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_backup_plan_associations_for_resource_type(request) + + expected_params = [ + ( + "resourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_backup_plan_associations_for_resource_type_rest_flattened(): + client = BackupDRClient( + 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 = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + + # 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", + resource_type="resource_type_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 = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_backup_plan_associations_for_resource_type(**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/*}/backupPlanAssociations:fetchForResourceType" + % client.transport._host, + args[1], + ) + + +def test_fetch_backup_plan_associations_for_resource_type_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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.fetch_backup_plan_associations_for_resource_type( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_backup_plan_associations_for_resource_type_rest_pager( + transport: str = "rest", +): + client = BackupDRClient( + 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 = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.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.fetch_backup_plan_associations_for_resource_type( + 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, backupplanassociation.BackupPlanAssociation) for i in results + ) + + pages = list( + client.fetch_backup_plan_associations_for_resource_type( + request=sample_request + ).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_backup_plan_association_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 = BackupDRClient( + 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_plan_association + 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_plan_association + ] = mock_rpc + + request = {} + client.delete_backup_plan_association(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_plan_association(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_plan_association_rest_required_fields( + request_type=backupplanassociation.DeleteBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteBackupPlanAssociation, + "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "autoProtectionPolicyBinding", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_plan_association(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_plan_association_rest_flattened(): + client = BackupDRClient( + 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/backupPlanAssociations/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_backup_plan_association(**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/*/backupPlanAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_association( + backupplanassociation.DeleteBackupPlanAssociationRequest(), + name="name_value", + ) + + +def test_trigger_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 = BackupDRClient( + 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.trigger_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.trigger_backup] = mock_rpc + + request = {} + client.trigger_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.trigger_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_trigger_backup_rest_required_fields( + request_type=backupplanassociation.TriggerBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request_init["rule_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 + + default_values = getattr( + transport_class._BaseTriggerBackup, + "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["ruleId"] = "rule_id_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "ruleId" in jsonified_request + assert jsonified_request["ruleId"] == "rule_id_value" + + client = BackupDRClient( + 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.trigger_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_trigger_backup_rest_flattened(): + client = BackupDRClient( + 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/backupPlanAssociations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + rule_id="rule_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.trigger_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/v1/{name=projects/*/locations/*/backupPlanAssociations/*}:triggerBackup" + % client.transport._host, + args[1], + ) + + +def test_trigger_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.trigger_backup( + backupplanassociation.TriggerBackupRequest(), + name="name_value", + rule_id="rule_id_value", + ) + + +def test_get_data_source_reference_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 = BackupDRClient( + 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_data_source_reference + 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_data_source_reference + ] = mock_rpc + + request = {} + client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source_reference(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_data_source_reference_rest_required_fields( + request_type=datasourcereference.GetDataSourceReferenceRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetDataSourceReference, + "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasourcereference.DataSourceReference() + # 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 = datasourcereference.DataSourceReference.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_data_source_reference(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_data_source_reference_rest_flattened(): + client = BackupDRClient( + 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 = datasourcereference.DataSourceReference() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/dataSourceReferences/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 = datasourcereference.DataSourceReference.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_source_reference(**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/*/dataSourceReferences/*}" + % client.transport._host, + args[1], + ) + + +def test_get_data_source_reference_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_source_reference( + datasourcereference.GetDataSourceReferenceRequest(), + name="name_value", + ) + + +def test_list_data_source_references_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 = BackupDRClient( + 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_data_source_references + 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_data_source_references + ] = mock_rpc + + request = {} + client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_source_references(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_data_source_references_rest_required_fields( + request_type=datasourcereference.ListDataSourceReferencesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListDataSourceReferences, + "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasourcereference.ListDataSourceReferencesResponse() + # 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 = datasourcereference.ListDataSourceReferencesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_data_source_references(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_data_source_references_rest_flattened(): + client = BackupDRClient( + 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 = datasourcereference.ListDataSourceReferencesResponse() + + # 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 = datasourcereference.ListDataSourceReferencesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_source_references(**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/*}/dataSourceReferences" + % client.transport._host, + args[1], + ) + + +def test_list_data_source_references_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_source_references( + datasourcereference.ListDataSourceReferencesRequest(), + parent="parent_value", + ) + + +def test_list_data_source_references_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + datasourcereference.ListDataSourceReferencesResponse.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_data_source_references(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, datasourcereference.DataSourceReference) for i in results + ) + + pages = list(client.list_data_source_references(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_data_source_references_for_resource_type_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 = BackupDRClient( + 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.fetch_data_source_references_for_resource_type + 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.fetch_data_source_references_for_resource_type + ] = mock_rpc + + request = {} + client.fetch_data_source_references_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_data_source_references_for_resource_type(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_fetch_data_source_references_for_resource_type_rest_required_fields( + request_type=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["resource_type"] = "" + 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 "resourceType" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchDataSourceReferencesForResourceType, + "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == request_init["resource_type"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["resourceType"] = "resource_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "resourceType", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + # 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 = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_data_source_references_for_resource_type(request) + + expected_params = [ + ( + "resourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_data_source_references_for_resource_type_rest_flattened(): + client = BackupDRClient( + 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 = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + + # 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", + resource_type="resource_type_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 = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_data_source_references_for_resource_type(**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/*}/dataSourceReferences:fetchForResourceType" + % client.transport._host, + args[1], + ) + + +def test_fetch_data_source_references_for_resource_type_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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.fetch_data_source_references_for_resource_type( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_data_source_references_for_resource_type_rest_pager( + transport: str = "rest", +): + client = BackupDRClient( + 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 = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.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.fetch_data_source_references_for_resource_type( + 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, datasourcereference.DataSourceReference) for i in results + ) + + pages = list( + client.fetch_data_source_references_for_resource_type( + request=sample_request + ).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_initialize_service_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 = BackupDRClient( + 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.initialize_service 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.initialize_service] = ( + mock_rpc + ) + + request = {} + client.initialize_service(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.initialize_service(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_initialize_service_rest_required_fields( + request_type=backupdr.InitializeServiceRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request_init["resource_type"] = "" + 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 + + default_values = getattr( + transport_class._BaseInitializeService, + "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["resourceType"] = "resource_type_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + 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.initialize_service(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_auto_protection_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 = BackupDRClient( + 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_auto_protection_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.create_auto_protection_policy + ] = mock_rpc + + request = {} + client.create_auto_protection_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.create_auto_protection_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_create_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.CreateAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["auto_protection_policy_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 "autoProtectionPolicyId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateAutoProtectionPolicy, + "_BaseCreateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "autoProtectionPolicyId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyId"] + == request_init["auto_protection_policy_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["autoProtectionPolicyId"] = "auto_protection_policy_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "autoProtectionPolicyId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "autoProtectionPolicyId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyId"] == "auto_protection_policy_id_value" + ) + + client = BackupDRClient( + 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_auto_protection_policy(request) + + expected_params = [ + ( + "autoProtectionPolicyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + 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", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_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_auto_protection_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/v1/{parent=projects/*/locations/*}/autoProtectionPolicies" + % client.transport._host, + args[1], + ) + + +def test_create_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + +def test_list_auto_protection_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: + client = BackupDRClient( + 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_auto_protection_policies + 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_auto_protection_policies + ] = mock_rpc + + request = {} + client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auto_protection_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_list_auto_protection_policies_rest_required_fields( + request_type=autoprotectionpolicy.ListAutoProtectionPoliciesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListAutoProtectionPolicies, + "_BaseListAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_auto_protection_policies(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_auto_protection_policies_rest_flattened(): + client = BackupDRClient( + 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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_auto_protection_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/v1/{parent=projects/*/locations/*}/autoProtectionPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_auto_protection_policies_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policies( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_auto_protection_policies_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse.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_auto_protection_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, autoprotectionpolicy.AutoProtectionPolicy) for i in results + ) + + pages = list(client.list_auto_protection_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_auto_protection_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 = BackupDRClient( + 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_auto_protection_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_auto_protection_policy + ] = mock_rpc + + request = {} + client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auto_protection_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_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.GetAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetAutoProtectionPolicy, + "_BaseGetAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.AutoProtectionPolicy() + # 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 = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_auto_protection_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_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + 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 = autoprotectionpolicy.AutoProtectionPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/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 = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_auto_protection_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/v1/{name=projects/*/locations/*/autoProtectionPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_get_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + name="name_value", + ) + + +def test_update_auto_protection_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 = BackupDRClient( + 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_auto_protection_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_auto_protection_policy + ] = mock_rpc + + request = {} + client.update_auto_protection_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_auto_protection_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_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateAutoProtectionPolicy, + "_BaseUpdateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_auto_protection_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_update_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + 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 = { + "auto_protection_policy": { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_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_auto_protection_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/v1/{auto_protection_policy.name=projects/*/locations/*/autoProtectionPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_update_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_auto_protection_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 = BackupDRClient( + 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_auto_protection_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.delete_auto_protection_policy + ] = mock_rpc + + request = {} + client.delete_auto_protection_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.delete_auto_protection_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_delete_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteAutoProtectionPolicy, + "_BaseDeleteAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_auto_protection_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_delete_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + 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/autoProtectionPolicies/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_auto_protection_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/v1/{name=projects/*/locations/*/autoProtectionPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + name="name_value", + ) + + +def test_create_auto_protection_policy_binding_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 = BackupDRClient( + 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_auto_protection_policy_binding + 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_auto_protection_policy_binding + ] = mock_rpc + + request = {} + client.create_auto_protection_policy_binding(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_auto_protection_policy_binding(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_auto_protection_policy_binding_rest_required_fields( + request_type=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["auto_protection_policy_binding_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 "autoProtectionPolicyBindingId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateAutoProtectionPolicyBinding, + "_BaseCreateAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "autoProtectionPolicyBindingId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyBindingId"] + == request_init["auto_protection_policy_binding_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["autoProtectionPolicyBindingId"] = ( + "auto_protection_policy_binding_id_value" + ) + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "autoProtectionPolicyBindingId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "autoProtectionPolicyBindingId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyBindingId"] + == "auto_protection_policy_binding_id_value" + ) + + client = BackupDRClient( + 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_auto_protection_policy_binding(request) + + expected_params = [ + ( + "autoProtectionPolicyBindingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_auto_protection_policy_binding_rest_flattened(): + client = BackupDRClient( + 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/autoProtectionPolicies/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_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_auto_protection_policy_binding(**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/*/autoProtectionPolicies/*}/bindings" + % client.transport._host, + args[1], + ) + + +def test_create_auto_protection_policy_binding_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_auto_protection_policy_binding( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + +def test_get_auto_protection_policy_binding_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 = BackupDRClient( + 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_auto_protection_policy_binding + 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_auto_protection_policy_binding + ] = mock_rpc + + request = {} + client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auto_protection_policy_binding(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_auto_protection_policy_binding_rest_required_fields( + request_type=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetAutoProtectionPolicyBinding, + "_BaseGetAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + # 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 = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_auto_protection_policy_binding(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_auto_protection_policy_binding_rest_flattened(): + client = BackupDRClient( + 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 = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/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 = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_auto_protection_policy_binding(**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/*/autoProtectionPolicies/*/bindings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_auto_protection_policy_binding_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_auto_protection_policy_binding( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +def test_list_auto_protection_policy_bindings_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 = BackupDRClient( + 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_auto_protection_policy_bindings + 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_auto_protection_policy_bindings + ] = mock_rpc + + request = {} + client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auto_protection_policy_bindings(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_auto_protection_policy_bindings_rest_required_fields( + request_type=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListAutoProtectionPolicyBindings, + "_BaseListAutoProtectionPolicyBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + # 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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_auto_protection_policy_bindings(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_auto_protection_policy_bindings_rest_flattened(): + client = BackupDRClient( + 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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_auto_protection_policy_bindings(**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/*/autoProtectionPolicies/*}/bindings" + % client.transport._host, + args[1], + ) + + +def test_list_auto_protection_policy_bindings_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_auto_protection_policy_bindings( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + parent="parent_value", + ) + + +def test_list_auto_protection_policy_bindings_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.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/autoProtectionPolicies/sample3" + } + + pager = client.list_auto_protection_policy_bindings(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, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + for i in results + ) + + pages = list( + client.list_auto_protection_policy_bindings(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_applied_auto_protection_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: + client = BackupDRClient( + 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_applied_auto_protection_policies + 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_applied_auto_protection_policies + ] = mock_rpc + + request = {} + client.list_applied_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_applied_auto_protection_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_list_applied_auto_protection_policies_rest_required_fields( + request_type=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListAppliedAutoProtectionPolicies, + "_BaseListAppliedAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + # 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_applied_auto_protection_policies(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_applied_auto_protection_policies_rest_flattened(): + client = BackupDRClient( + 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + + # 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_applied_auto_protection_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/v1/{parent=projects/*/locations/*}/appliedAutoProtectionPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_applied_auto_protection_policies_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_applied_auto_protection_policies( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_applied_auto_protection_policies_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.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_applied_auto_protection_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, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + for i in results + ) + + pages = list( + client.list_applied_auto_protection_policies(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_initiate_delete_auto_protection_policy_binding_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 = BackupDRClient( + 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.initiate_delete_auto_protection_policy_binding + 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.initiate_delete_auto_protection_policy_binding + ] = mock_rpc + + request = {} + client.initiate_delete_auto_protection_policy_binding(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.initiate_delete_auto_protection_policy_binding(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_initiate_delete_auto_protection_policy_binding_rest_required_fields( + request_type=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseInitiateDeleteAutoProtectionPolicyBinding, + "_BaseInitiateDeleteAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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.initiate_delete_auto_protection_policy_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_initiate_delete_auto_protection_policy_binding_rest_flattened(): + client = BackupDRClient( + 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/autoProtectionPolicies/sample3/bindings/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.initiate_delete_auto_protection_policy_binding(**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/*/autoProtectionPolicies/*/bindings/*}:initiateDelete" + % client.transport._host, + args[1], + ) + + +def test_initiate_delete_auto_protection_policy_binding_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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.initiate_delete_auto_protection_policy_binding( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +def test_list_binding_matching_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: + client = BackupDRClient( + 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_binding_matching_resources + 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_binding_matching_resources + ] = mock_rpc + + request = {} + client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_binding_matching_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_binding_matching_resources_rest_required_fields( + request_type=bindingmatchingresource.ListBindingMatchingResourcesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBindingMatchingResources, + "_BaseListBindingMatchingResources__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bindingmatchingresource.ListBindingMatchingResourcesResponse() + # 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 = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_binding_matching_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_binding_matching_resources_rest_flattened(): + client = BackupDRClient( + 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 = bindingmatchingresource.ListBindingMatchingResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/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 = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_binding_matching_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/*/autoProtectionPolicies/*/bindings/*}/matchingResources" + % client.transport._host, + args[1], + ) + + +def test_list_binding_matching_resources_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_binding_matching_resources( + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + parent="parent_value", + ) + + +def test_list_binding_matching_resources_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + bindingmatchingresource.ListBindingMatchingResourcesResponse.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/autoProtectionPolicies/sample3/bindings/sample4" + } + + pager = client.list_binding_matching_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, bindingmatchingresource.BindingMatchingResource) + for i in results + ) + + pages = list( + client.list_binding_matching_resources(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_restore_template_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 = BackupDRClient( + 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_restore_template + 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_restore_template + ] = mock_rpc + + request = {} + client.create_restore_template(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_restore_template(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_restore_template_rest_required_fields( + request_type=gcb_restore_template.CreateRestoreTemplateRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["restore_template_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 "restoreTemplateId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateRestoreTemplate, + "_BaseCreateRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "restoreTemplateId" in jsonified_request + assert jsonified_request["restoreTemplateId"] == request_init["restore_template_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["restoreTemplateId"] = "restore_template_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "restoreTemplateId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "restoreTemplateId" in jsonified_request + assert jsonified_request["restoreTemplateId"] == "restore_template_id_value" + + client = BackupDRClient( + 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_restore_template(request) + + expected_params = [ + ( + "restoreTemplateId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_restore_template_rest_flattened(): + client = BackupDRClient( + 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", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_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_restore_template(**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/*}/restoreTemplates" + % client.transport._host, + args[1], + ) + + +def test_create_restore_template_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_template( + gcb_restore_template.CreateRestoreTemplateRequest(), + parent="parent_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", + ) + + +def test_get_restore_template_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 = BackupDRClient( + 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_restore_template 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_restore_template] = ( + mock_rpc + ) + + request = {} + client.get_restore_template(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_restore_template(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_restore_template_rest_required_fields( + request_type=restore_template.GetRestoreTemplateRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetRestoreTemplate, + "_BaseGetRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = restore_template.RestoreTemplate() + # 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 = restore_template.RestoreTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_restore_template(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_restore_template_rest_flattened(): + client = BackupDRClient( + 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 = restore_template.RestoreTemplate() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/restoreTemplates/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 = restore_template.RestoreTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_restore_template(**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/*/restoreTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_get_restore_template_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_template( + restore_template.GetRestoreTemplateRequest(), + name="name_value", + ) + + +def test_list_restore_templates_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 = BackupDRClient( + 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_restore_templates + 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_restore_templates] = ( + mock_rpc + ) + + request = {} + client.list_restore_templates(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_restore_templates(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_restore_templates_rest_required_fields( + request_type=restore_template.ListRestoreTemplatesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListRestoreTemplates, + "_BaseListRestoreTemplates__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = restore_template.ListRestoreTemplatesResponse() + # 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 = restore_template.ListRestoreTemplatesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_restore_templates(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_restore_templates_rest_flattened(): + client = BackupDRClient( + 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 = restore_template.ListRestoreTemplatesResponse() + + # 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 = restore_template.ListRestoreTemplatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_restore_templates(**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/*}/restoreTemplates" + % client.transport._host, + args[1], + ) + + +def test_list_restore_templates_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_templates( + restore_template.ListRestoreTemplatesRequest(), + parent="parent_value", + ) + + +def test_list_restore_templates_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + next_page_token="abc", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], + next_page_token="def", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + ], + next_page_token="ghi", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + restore_template.ListRestoreTemplatesResponse.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_restore_templates(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, restore_template.RestoreTemplate) for i in results) + + pages = list(client.list_restore_templates(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_restore_template_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 = BackupDRClient( + 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_restore_template + 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_restore_template + ] = mock_rpc + + request = {} + client.update_restore_template(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_restore_template(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_restore_template_rest_required_fields( + request_type=gcb_restore_template.UpdateRestoreTemplateRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateRestoreTemplate, + "_BaseUpdateRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_restore_template(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_restore_template_rest_flattened(): + client = BackupDRClient( + 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 = { + "restore_template": { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + restore_template=gcb_restore_template.RestoreTemplate(name="name_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_restore_template(**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/{restore_template.name=projects/*/locations/*/restoreTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_update_restore_template_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_template( + gcb_restore_template.UpdateRestoreTemplateRequest(), + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_restore_template_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 = BackupDRClient( + 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_restore_template + 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_restore_template + ] = mock_rpc + + request = {} + client.delete_restore_template(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_restore_template(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_restore_template_rest_required_fields( + request_type=restore_template.DeleteRestoreTemplateRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteRestoreTemplate, + "_BaseDeleteRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_restore_template(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_restore_template_rest_flattened(): + client = BackupDRClient( + 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/restoreTemplates/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_restore_template(**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/*/restoreTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_restore_template_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_template( + restore_template.DeleteRestoreTemplateRequest(), + name="name_value", + ) + + +def test_run_restore_template_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 = BackupDRClient( + 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.run_restore_template 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.run_restore_template] = ( + mock_rpc + ) + + request = {} + client.run_restore_template(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.run_restore_template(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_run_restore_template_rest_required_fields( + request_type=restore_template.RunRestoreTemplateRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseRunRestoreTemplate, + "_BaseRunRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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.run_restore_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_run_restore_template_rest_flattened(): + client = BackupDRClient( + 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/restoreTemplates/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.run_restore_template(**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/*/restoreTemplates/*}:run" + % client.transport._host, + args[1], + ) + + +def test_run_restore_template_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.run_restore_template( + restore_template.RunRestoreTemplateRequest(), + name="name_value", + ) + + +def test_get_restore_template_execution_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 = BackupDRClient( + 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_restore_template_execution + 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_restore_template_execution + ] = mock_rpc + + request = {} + client.get_restore_template_execution(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_restore_template_execution(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_restore_template_execution_rest_required_fields( + request_type=restore_template_execution.GetRestoreTemplateExecutionRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetRestoreTemplateExecution, + "_BaseGetRestoreTemplateExecution__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = restore_template_execution.RestoreTemplateExecution() + # 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 = restore_template_execution.RestoreTemplateExecution.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_restore_template_execution(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_restore_template_execution_rest_flattened(): + client = BackupDRClient( + 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 = restore_template_execution.RestoreTemplateExecution() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/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 = restore_template_execution.RestoreTemplateExecution.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_restore_template_execution(**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/*/restoreTemplates/*/executions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_restore_template_execution_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_template_execution( + restore_template_execution.GetRestoreTemplateExecutionRequest(), + name="name_value", + ) + + +def test_list_restore_template_executions_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 = BackupDRClient( + 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_restore_template_executions + 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_restore_template_executions + ] = mock_rpc + + request = {} + client.list_restore_template_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_restore_template_executions(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_restore_template_executions_rest_required_fields( + request_type=restore_template_execution.ListRestoreTemplateExecutionsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListRestoreTemplateExecutions, + "_BaseListRestoreTemplateExecutions__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = restore_template_execution.ListRestoreTemplateExecutionsResponse() + # 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 = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_restore_template_executions(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_restore_template_executions_rest_flattened(): + client = BackupDRClient( + 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 = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/restoreTemplates/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 = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_restore_template_executions(**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/*/restoreTemplates/*}/executions" + % client.transport._host, + args[1], + ) + + +def test_list_restore_template_executions_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_template_executions( + restore_template_execution.ListRestoreTemplateExecutionsRequest(), + parent="parent_value", + ) + + +def test_list_restore_template_executions_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="abc", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], + next_page_token="def", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="ghi", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + restore_template_execution.ListRestoreTemplateExecutionsResponse.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/restoreTemplates/sample3" + } + + pager = client.list_restore_template_executions(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, restore_template_execution.RestoreTemplateExecution) + for i in results + ) + + pages = list( + client.list_restore_template_executions(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_trigger_restore_cleanup_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 = BackupDRClient( + 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.trigger_restore_cleanup + 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.trigger_restore_cleanup + ] = mock_rpc + + request = {} + client.trigger_restore_cleanup(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.trigger_restore_cleanup(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_trigger_restore_cleanup_rest_required_fields( + request_type=restore_template_execution.TriggerRestoreCleanupRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseTriggerRestoreCleanup, + "_BaseTriggerRestoreCleanup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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.trigger_restore_cleanup(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_trigger_restore_cleanup_rest_flattened(): + client = BackupDRClient( + 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/restoreTemplates/sample3/executions/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.trigger_restore_cleanup(**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/*/restoreTemplates/*/executions/*}:triggerRestoreCleanup" + % client.transport._host, + args[1], + ) + + +def test_trigger_restore_cleanup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.trigger_restore_cleanup( + restore_template_execution.TriggerRestoreCleanupRequest(), + name="name_value", + ) + + +def test_create_restore_verification_plan_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 = BackupDRClient( + 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_restore_verification_plan + 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_restore_verification_plan + ] = mock_rpc + + request = {} + client.create_restore_verification_plan(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_restore_verification_plan(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_restore_verification_plan_rest_required_fields( + request_type=gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["restore_verification_plan_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 "restoreVerificationPlanId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateRestoreVerificationPlan, + "_BaseCreateRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "restoreVerificationPlanId" in jsonified_request + assert ( + jsonified_request["restoreVerificationPlanId"] + == request_init["restore_verification_plan_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["restoreVerificationPlanId"] = ( + "restore_verification_plan_id_value" + ) + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "restoreVerificationPlanId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "restoreVerificationPlanId" in jsonified_request + assert ( + jsonified_request["restoreVerificationPlanId"] + == "restore_verification_plan_id_value" + ) + + client = BackupDRClient( + 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_restore_verification_plan(request) + + expected_params = [ + ( + "restoreVerificationPlanId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_restore_verification_plan_rest_flattened(): + client = BackupDRClient( + 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", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" + ), + restore_verification_plan_id="restore_verification_plan_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_restore_verification_plan(**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/*}/restoreVerificationPlans" + % client.transport._host, + args[1], + ) + + +def test_create_restore_verification_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_verification_plan( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" + ), + restore_verification_plan_id="restore_verification_plan_id_value", + ) + + +def test_create_restore_verification_plan_association_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 = BackupDRClient( + 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_restore_verification_plan_association + 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_restore_verification_plan_association + ] = mock_rpc + + request = {} + client.create_restore_verification_plan_association(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_restore_verification_plan_association(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_restore_verification_plan_association_rest_required_fields( + request_type=gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["restore_verification_plan_association_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 "restoreVerificationPlanAssociationId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateRestoreVerificationPlanAssociation, + "_BaseCreateRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "restoreVerificationPlanAssociationId" in jsonified_request + assert ( + jsonified_request["restoreVerificationPlanAssociationId"] + == request_init["restore_verification_plan_association_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["restoreVerificationPlanAssociationId"] = ( + "restore_verification_plan_association_id_value" + ) + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "restoreVerificationPlanAssociationId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "restoreVerificationPlanAssociationId" in jsonified_request + assert ( + jsonified_request["restoreVerificationPlanAssociationId"] + == "restore_verification_plan_association_id_value" + ) + + client = BackupDRClient( + 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_restore_verification_plan_association(request) + + expected_params = [ + ( + "restoreVerificationPlanAssociationId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_restore_verification_plan_association_rest_flattened(): + client = BackupDRClient( + 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/restoreVerificationPlans/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_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_restore_verification_plan_association(**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/*/restoreVerificationPlans/*}/associations" + % client.transport._host, + args[1], + ) + + +def test_create_restore_verification_plan_association_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_restore_verification_plan_association( + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), + parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_id_value", + ) + + +def test_get_restore_verification_plan_association_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 = BackupDRClient( + 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_restore_verification_plan_association + 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_restore_verification_plan_association + ] = mock_rpc + + request = {} + client.get_restore_verification_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_restore_verification_plan_association(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_restore_verification_plan_association_rest_required_fields( + request_type=restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetRestoreVerificationPlanAssociation, + "_BaseGetRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + # 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 = restore_verification_plan_association.RestoreVerificationPlanAssociation.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_restore_verification_plan_association(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_restore_verification_plan_association_rest_flattened(): + client = BackupDRClient( + 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 = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/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 = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_restore_verification_plan_association(**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/*/restoreVerificationPlans/*/associations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_restore_verification_plan_association_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_restore_verification_plan_association( + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), + name="name_value", + ) + + +def test_list_restore_verification_plan_associations_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 = BackupDRClient( + 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_restore_verification_plan_associations + 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_restore_verification_plan_associations + ] = mock_rpc + + request = {} + client.list_restore_verification_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_restore_verification_plan_associations(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_restore_verification_plan_associations_rest_required_fields( + request_type=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListRestoreVerificationPlanAssociations, + "_BaseListRestoreVerificationPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + # 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_restore_verification_plan_associations(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_restore_verification_plan_associations_rest_flattened(): + client = BackupDRClient( + 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_restore_verification_plan_associations(**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/*/restoreVerificationPlans/*}/associations" + % client.transport._host, + args[1], + ) + + +def test_list_restore_verification_plan_associations_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_restore_verification_plan_associations( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), + parent="parent_value", + ) + + +def test_list_restore_verification_plan_associations_rest_pager( + transport: str = "rest", +): + client = BackupDRClient( + 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 = ( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + next_page_token="abc", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], + next_page_token="def", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + next_page_token="ghi", + ), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.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/restoreVerificationPlans/sample3" + } + + pager = client.list_restore_verification_plan_associations( + 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, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + for i in results + ) + + pages = list( + client.list_restore_verification_plan_associations( + request=sample_request + ).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_restore_verification_plan_association_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 = BackupDRClient( + 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_restore_verification_plan_association + 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_restore_verification_plan_association + ] = mock_rpc + + request = {} + client.delete_restore_verification_plan_association(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_restore_verification_plan_association(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_restore_verification_plan_association_rest_required_fields( + request_type=restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteRestoreVerificationPlanAssociation, + "_BaseDeleteRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_restore_verification_plan_association(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_restore_verification_plan_association_rest_flattened(): + client = BackupDRClient( + 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/restoreVerificationPlans/sample3/associations/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_restore_verification_plan_association(**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/*/restoreVerificationPlans/*/associations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_restore_verification_plan_association_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_restore_verification_plan_association( + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), + name="name_value", + ) + + +def test_trigger_restore_verification_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 = BackupDRClient( + 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.trigger_restore_verification + 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.trigger_restore_verification + ] = mock_rpc + + request = {} + client.trigger_restore_verification(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.trigger_restore_verification(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_trigger_restore_verification_rest_required_fields( + request_type=restore_verification_plan_association.TriggerRestoreVerificationRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseTriggerRestoreVerification, + "_BaseTriggerRestoreVerification__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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.trigger_restore_verification(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_trigger_restore_verification_rest_flattened(): + client = BackupDRClient( + 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/restoreVerificationPlans/sample3/associations/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.trigger_restore_verification(**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/*/restoreVerificationPlans/*/associations/*}:triggerRestoreVerification" + % client.transport._host, + args[1], + ) + + +def test_trigger_restore_verification_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.trigger_restore_verification( + restore_verification_plan_association.TriggerRestoreVerificationRequest(), + name="name_value", + ) + + +def test_get_restore_verification_plan_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 = BackupDRClient( + 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_restore_verification_plan + 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_restore_verification_plan + ] = mock_rpc + + request = {} + client.get_restore_verification_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_restore_verification_plan(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_restore_verification_plan_rest_required_fields( + request_type=restore_verification_plan.GetRestoreVerificationPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetRestoreVerificationPlan, + "_BaseGetRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = restore_verification_plan.RestoreVerificationPlan() + # 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 = restore_verification_plan.RestoreVerificationPlan.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_restore_verification_plan(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_restore_verification_plan_rest_flattened(): + client = BackupDRClient( + 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 = restore_verification_plan.RestoreVerificationPlan() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/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 = restore_verification_plan.RestoreVerificationPlan.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_restore_verification_plan(**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/*/restoreVerificationPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_get_restore_verification_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_verification_plan( + restore_verification_plan.GetRestoreVerificationPlanRequest(), + name="name_value", + ) + + +def test_list_restore_verification_plans_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 = BackupDRClient( + 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_restore_verification_plans + 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_restore_verification_plans + ] = mock_rpc + + request = {} + client.list_restore_verification_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_restore_verification_plans(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_restore_verification_plans_rest_required_fields( + request_type=restore_verification_plan.ListRestoreVerificationPlansRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListRestoreVerificationPlans, + "_BaseListRestoreVerificationPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = restore_verification_plan.ListRestoreVerificationPlansResponse() + # 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 = ( + restore_verification_plan.ListRestoreVerificationPlansResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_restore_verification_plans(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_restore_verification_plans_rest_flattened(): + client = BackupDRClient( + 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 = restore_verification_plan.ListRestoreVerificationPlansResponse() + + # 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 = ( + restore_verification_plan.ListRestoreVerificationPlansResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_restore_verification_plans(**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/*}/restoreVerificationPlans" + % client.transport._host, + args[1], + ) + + +def test_list_restore_verification_plans_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_verification_plans( + restore_verification_plan.ListRestoreVerificationPlansRequest(), + parent="parent_value", + ) + + +def test_list_restore_verification_plans_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + restore_verification_plan.ListRestoreVerificationPlansResponse.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_restore_verification_plans(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, restore_verification_plan.RestoreVerificationPlan) + for i in results + ) + + pages = list( + client.list_restore_verification_plans(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_restore_verification_plan_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 = BackupDRClient( + 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_restore_verification_plan + 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_restore_verification_plan + ] = mock_rpc + + request = {} + client.delete_restore_verification_plan(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_restore_verification_plan(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_restore_verification_plan_rest_required_fields( + request_type=restore_verification_plan.DeleteRestoreVerificationPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteRestoreVerificationPlan, + "_BaseDeleteRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_restore_verification_plan(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_restore_verification_plan_rest_flattened(): + client = BackupDRClient( + 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/restoreVerificationPlans/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_restore_verification_plan(**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/*/restoreVerificationPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_restore_verification_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_verification_plan( + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDRClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BackupDRClient( + 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 = BackupDRClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDRClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BackupDRClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BackupDRGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDRGrpcTransport, + transports.BackupDRGrpcAsyncIOTransport, + transports.BackupDRRestTransport, + ], +) +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 = BackupDRClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BackupDRClient( + 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_management_servers_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + call.return_value = backupdr.ListManagementServersResponse() + client.list_management_servers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.ListManagementServersRequest() + 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_management_server_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + call.return_value = backupdr.ManagementServer() + client.get_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.GetManagementServerRequest() + 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_management_server_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.CreateManagementServerRequest() + 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_management_server_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.DeleteManagementServerRequest() + 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_backup_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.CreateBackupVaultRequest() + 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_vaults_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + call.return_value = backupvault.ListBackupVaultsResponse() + client.list_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupVaultsRequest() + 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_fetch_usable_backup_vaults_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + call.return_value = backupvault.FetchUsableBackupVaultsResponse() + client.fetch_usable_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchUsableBackupVaultsRequest() + 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_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + call.return_value = backupvault.BackupVault() + client.get_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupVaultRequest() + 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_backup_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupVaultRequest() + 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_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupVaultRequest() + 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_data_sources_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + call.return_value = backupvault.ListDataSourcesResponse() + client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListDataSourcesRequest() + 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_data_source_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + call.return_value = backupvault.DataSource() + client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetDataSourceRequest() + 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_data_source_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateDataSourceRequest() + 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 = BackupDRClient( + 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 = backupvault.ListBackupsResponse() + client.list_backups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.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_fetch_backups_for_resource_type_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + call.return_value = backupvault.FetchBackupsForResourceTypeResponse() + client.fetch_backups_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchBackupsForResourceTypeRequest() + 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 = BackupDRClient( + 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 = backupvault.Backup() + client.get_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.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_update_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupRequest() + 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 = BackupDRClient( + 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 = backupvault.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_restore_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.restore_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.RestoreBackupRequest() + 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_backup_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.CreateBackupPlanRequest() + 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_backup_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.UpdateBackupPlanRequest() + 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_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + call.return_value = backupplan.BackupPlan() + client.get_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRequest() + 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_plans_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + call.return_value = backupplan.ListBackupPlansResponse() + client.list_backup_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlansRequest() + 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_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.DeleteBackupPlanRequest() + 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_plan_revision_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + call.return_value = backupplan.BackupPlanRevision() + client.get_backup_plan_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRevisionRequest() + 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_plan_revisions_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + call.return_value = backupplan.ListBackupPlanRevisionsResponse() + client.list_backup_plan_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlanRevisionsRequest() + 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_backup_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() + 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_backup_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() + 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_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + call.return_value = backupplanassociation.BackupPlanAssociation() + client.get_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.GetBackupPlanAssociationRequest() + 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_plan_associations_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + client.list_backup_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() + 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_fetch_backup_plan_associations_for_resource_type_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + client.fetch_backup_plan_associations_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + 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_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() + 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_trigger_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.TriggerBackupRequest() + 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_data_source_reference_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + call.return_value = datasourcereference.DataSourceReference() + client.get_data_source_reference(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.GetDataSourceReferenceRequest() + 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_data_source_references_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + call.return_value = datasourcereference.ListDataSourceReferencesResponse() + client.list_data_source_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.ListDataSourceReferencesRequest() + 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_fetch_data_source_references_for_resource_type_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + client.fetch_data_source_references_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + ) + 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_initialize_service_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + 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_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + 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_auto_protection_policies_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + client.list_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + 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_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + client.get_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + 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_auto_protection_policy_binding_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_binding_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + client.get_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_bindings_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + client.list_auto_protection_policy_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + 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_applied_auto_protection_policies_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + client.list_applied_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + ) + 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_initiate_delete_auto_protection_policy_binding_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initiate_delete_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + 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_binding_matching_resources_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + client.list_binding_matching_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() + 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_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.CreateRestoreTemplateRequest() + 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_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template), "__call__" + ) as call: + call.return_value = restore_template.RestoreTemplate() + client.get_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.GetRestoreTemplateRequest() + 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_restore_templates_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + call.return_value = restore_template.ListRestoreTemplatesResponse() + client.list_restore_templates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.ListRestoreTemplatesRequest() + 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_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.UpdateRestoreTemplateRequest() + 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_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.DeleteRestoreTemplateRequest() + 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_run_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.run_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.RunRestoreTemplateRequest() + 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_restore_template_execution_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + call.return_value = restore_template_execution.RestoreTemplateExecution() + client.get_restore_template_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.GetRestoreTemplateExecutionRequest() + 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_restore_template_executions_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + client.list_restore_template_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.ListRestoreTemplateExecutionsRequest() + 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_trigger_restore_cleanup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_restore_cleanup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.TriggerRestoreCleanupRequest() + 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_restore_verification_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + ) + 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_restore_verification_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + client.get_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_associations_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + client.list_restore_verification_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + 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_restore_verification_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + 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_trigger_restore_verification_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_restore_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) + 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_restore_verification_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: + call.return_value = restore_verification_plan.RestoreVerificationPlan() + client.get_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.GetRestoreVerificationPlanRequest() + 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_restore_verification_plans_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: + call.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) + client.list_restore_verification_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.ListRestoreVerificationPlansRequest() + 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_restore_verification_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BackupDRAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BackupDRAsyncClient( + 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_management_servers_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ListManagementServersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_management_servers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.ListManagementServersRequest() + 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_management_server_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ManagementServer( + name="name_value", + description="description_value", + type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, + state=backupdr.ManagementServer.InstanceState.CREATING, + etag="etag_value", + oauth2_client_id="oauth2_client_id_value", + ba_proxy_uri=["ba_proxy_uri_value"], + satisfies_pzi=True, + ) + ) + await client.get_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.GetManagementServerRequest() + 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_management_server_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__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_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.CreateManagementServerRequest() + 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_management_server_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__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_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.DeleteManagementServerRequest() + 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_backup_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__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_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.CreateBackupVaultRequest() + 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_vaults_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupVaultsRequest() + 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_fetch_usable_backup_vaults_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchUsableBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.fetch_usable_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchUsableBackupVaultsRequest() + 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_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.BackupVault( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + deletable=True, + etag="etag_value", + state=backupvault.BackupVault.State.CREATING, + backup_count=1278, + service_account="service_account_value", + total_stored_bytes=1946, + uid="uid_value", + access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + ) + ) + await client.get_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupVaultRequest() + 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_backup_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__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_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupVaultRequest() + 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_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__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_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupVaultRequest() + 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_data_sources_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListDataSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListDataSourcesRequest() + 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_data_source_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.DataSource( + name="name_value", + state=backupvault.DataSource.State.CREATING, + backup_count=1278, + etag="etag_value", + total_stored_bytes=1946, + config_state=backupvault.BackupConfigState.ACTIVE, + backup_blocked_by_vault_access_restriction=True, + ) + ) + await client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetDataSourceRequest() + 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_data_source_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__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_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateDataSourceRequest() + 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 = BackupDRAsyncClient( + 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( + backupvault.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 = backupvault.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_fetch_backups_for_resource_type_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchBackupsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_backups_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchBackupsForResourceTypeRequest() + 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 = BackupDRAsyncClient( + 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( + backupvault.Backup( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + etag="etag_value", + state=backupvault.Backup.State.CREATING, + backup_type=backupvault.Backup.BackupType.SCHEDULED, + resource_size_bytes=2056, + satisfies_pzs=True, + satisfies_pzi=True, + kms_key_versions=["kms_key_versions_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 = backupvault.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_update_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_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.update_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupRequest() + 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 = BackupDRAsyncClient( + 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 = backupvault.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_restore_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.restore_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.restore_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.RestoreBackupRequest() + 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_backup_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__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_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.CreateBackupPlanRequest() + 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_backup_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__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_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.UpdateBackupPlanRequest() + 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_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlan( + name="name_value", + description="description_value", + state=backupplan.BackupPlan.State.CREATING, + resource_type="resource_type_value", + etag="etag_value", + backup_vault="backup_vault_value", + backup_vault_service_account="backup_vault_service_account_value", + log_retention_days=1929, + supported_resource_types=["supported_resource_types_value"], + revision_id="revision_id_value", + revision_name="revision_name_value", + ) + ) + await client.get_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRequest() + 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_plans_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlansRequest() + 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_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__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_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.DeleteBackupPlanRequest() + 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_plan_revision_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlanRevision( + name="name_value", + revision_id="revision_id_value", + state=backupplan.BackupPlanRevision.State.CREATING, + ) + ) + await client.get_backup_plan_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRevisionRequest() + 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_plan_revisions_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlanRevisionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_plan_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlanRevisionsRequest() + 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_backup_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__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_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() + 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_backup_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__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_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() + 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_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.BackupPlanAssociation( + name="name_value", + resource_type="resource_type_value", + resource="resource_value", + backup_plan="backup_plan_value", + state=backupplanassociation.BackupPlanAssociation.State.CREATING, + data_source="data_source_value", + backup_plan_revision_id="backup_plan_revision_id_value", + backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + ) + await client.get_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.GetBackupPlanAssociationRequest() + 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_plan_associations_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.ListBackupPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() + 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_fetch_backup_plan_associations_for_resource_type_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_backup_plan_associations_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + 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_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__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_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() + 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_trigger_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.trigger_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.trigger_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.TriggerBackupRequest() + 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_data_source_reference_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.DataSourceReference( + name="name_value", + data_source="data_source_value", + data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, + data_source_backup_count=2535, + total_stored_bytes=1946, + ) + ) + await client.get_data_source_reference(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.GetDataSourceReferenceRequest() + 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_data_source_references_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.ListDataSourceReferencesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_data_source_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.ListDataSourceReferencesRequest() + 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_fetch_data_source_references_for_resource_type_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_data_source_references_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + ) + 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_initialize_service_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__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.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + 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_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__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_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + 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_auto_protection_policies_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + 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_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy( + name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_value", + ) + ) + await client.get_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__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_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__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_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + 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_auto_protection_policy_binding_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__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_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_binding_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_value", + ) + ) + await client.get_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_bindings_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_auto_protection_policy_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + 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_applied_auto_protection_policies_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_applied_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + ) + 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_initiate_delete_auto_protection_policy_binding_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__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.initiate_delete_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + 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_binding_matching_resources_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_binding_matching_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() + 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_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__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_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.CreateRestoreTemplateRequest() + 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_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template.RestoreTemplate( + name="name_value", + description="description_value", + resource_type="resource_type_value", + state=restore_template.RestoreTemplate.State.CREATING, + etag="etag_value", + ) + ) + await client.get_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.GetRestoreTemplateRequest() + 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_restore_templates_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template.ListRestoreTemplatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_restore_templates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.ListRestoreTemplatesRequest() + 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_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__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_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.UpdateRestoreTemplateRequest() + 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_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__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_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.DeleteRestoreTemplateRequest() + 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_run_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__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.run_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.RunRestoreTemplateRequest() + 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_restore_template_execution_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.RestoreTemplateExecution( + name="name_value", + resource_type="resource_type_value", + type_=restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED, + phase=restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING, + state=restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING, + ) + ) + await client.get_restore_template_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.GetRestoreTemplateExecutionRequest() + 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_restore_template_executions_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_restore_template_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.ListRestoreTemplateExecutionsRequest() + 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_trigger_restore_cleanup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__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.trigger_restore_cleanup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.TriggerRestoreCleanupRequest() + 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_restore_verification_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__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_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + ) + 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_restore_verification_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__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_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value", + description="description_value", + state=restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING, + resource_type="resource_type_value", + ) + ) + await client.get_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_associations_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_restore_verification_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + 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_restore_verification_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__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_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + 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_trigger_restore_verification_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__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.trigger_restore_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) + 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_restore_verification_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan.RestoreVerificationPlan( + name="name_value", + description="description_value", + state=restore_verification_plan.RestoreVerificationPlan.State.CREATING, + schedule="schedule_value", + time_zone="time_zone_value", + ) + ) + await client.get_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.GetRestoreVerificationPlanRequest() + 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_restore_verification_plans_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan.ListRestoreVerificationPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_restore_verification_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.ListRestoreVerificationPlansRequest() + 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_restore_verification_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan), "__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_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BackupDRClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_management_servers_rest_bad_request( + request_type=backupdr.ListManagementServersRequest, +): + client = BackupDRClient( + 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_management_servers(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.ListManagementServersRequest, + dict, + ], +) +def test_list_management_servers_rest_call_success(request_type): + client = BackupDRClient( + 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 = backupdr.ListManagementServersResponse( + 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 = backupdr.ListManagementServersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_management_servers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListManagementServersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_management_servers_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_management_servers" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_management_servers_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_management_servers" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.ListManagementServersRequest.pb( + backupdr.ListManagementServersRequest() + ) + 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 = backupdr.ListManagementServersResponse.to_json( + backupdr.ListManagementServersResponse() + ) + req.return_value.content = return_value + + request = backupdr.ListManagementServersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupdr.ListManagementServersResponse() + post_with_metadata.return_value = ( + backupdr.ListManagementServersResponse(), + metadata, + ) + + client.list_management_servers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_management_server_rest_bad_request( + request_type=backupdr.GetManagementServerRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/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_management_server(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.GetManagementServerRequest, + dict, + ], +) +def test_get_management_server_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/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 = backupdr.ManagementServer( + name="name_value", + description="description_value", + type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, + state=backupdr.ManagementServer.InstanceState.CREATING, + etag="etag_value", + oauth2_client_id="oauth2_client_id_value", + ba_proxy_uri=["ba_proxy_uri_value"], + satisfies_pzi=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 = backupdr.ManagementServer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_management_server(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupdr.ManagementServer) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.type_ == backupdr.ManagementServer.InstanceType.BACKUP_RESTORE + assert response.state == backupdr.ManagementServer.InstanceState.CREATING + assert response.etag == "etag_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.ba_proxy_uri == ["ba_proxy_uri_value"] + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_management_server_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_management_server" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_management_server_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_management_server" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.GetManagementServerRequest.pb( + backupdr.GetManagementServerRequest() + ) + 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 = backupdr.ManagementServer.to_json(backupdr.ManagementServer()) + req.return_value.content = return_value + + request = backupdr.GetManagementServerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupdr.ManagementServer() + post_with_metadata.return_value = backupdr.ManagementServer(), metadata + + client.get_management_server( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_management_server_rest_bad_request( + request_type=backupdr.CreateManagementServerRequest, +): + client = BackupDRClient( + 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_management_server(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.CreateManagementServerRequest, + dict, + ], +) +def test_create_management_server_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["management_server"] = { + "name": "name_value", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "type_": 1, + "management_uri": {"web_ui": "web_ui_value", "api": "api_value"}, + "workforce_identity_based_management_uri": { + "first_party_management_uri": "first_party_management_uri_value", + "third_party_management_uri": "third_party_management_uri_value", + }, + "state": 1, + "networks": [{"network": "network_value", "peering_mode": 1}], + "etag": "etag_value", + "oauth2_client_id": "oauth2_client_id_value", + "workforce_identity_based_oauth2_client_id": { + "first_party_oauth2_client_id": "first_party_oauth2_client_id_value", + "third_party_oauth2_client_id": "third_party_oauth2_client_id_value", + }, + "ba_proxy_uri": ["ba_proxy_uri_value1", "ba_proxy_uri_value2"], + "satisfies_pzs": {"value": True}, + "satisfies_pzi": 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 = backupdr.CreateManagementServerRequest.meta.fields["management_server"] + + 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["management_server"].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["management_server"][field])): + del request_init["management_server"][field][i][subfield] + else: + del request_init["management_server"][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_management_server(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_management_server_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_create_management_server" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_management_server_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_management_server" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.CreateManagementServerRequest.pb( + backupdr.CreateManagementServerRequest() + ) + 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 = backupdr.CreateManagementServerRequest() + 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_management_server( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_management_server_rest_bad_request( + request_type=backupdr.DeleteManagementServerRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/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_management_server(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.DeleteManagementServerRequest, + dict, + ], +) +def test_delete_management_server_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/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_management_server(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_management_server_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_delete_management_server" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_delete_management_server_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_management_server" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.DeleteManagementServerRequest.pb( + backupdr.DeleteManagementServerRequest() + ) + 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 = backupdr.DeleteManagementServerRequest() + 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_management_server( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_backup_vault_rest_bad_request( + request_type=backupvault.CreateBackupVaultRequest, +): + client = BackupDRClient( + 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_backup_vault(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.CreateBackupVaultRequest, + dict, + ], +) +def test_create_backup_vault_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup_vault"] = { + "name": "name_value", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "backup_minimum_enforced_retention_duration": {"seconds": 751, "nanos": 543}, + "backup_retention_inheritance": 1, + "deletable": True, + "etag": "etag_value", + "state": 1, + "effective_time": {}, + "backup_count": 1278, + "service_account": "service_account_value", + "total_stored_bytes": 1946, + "uid": "uid_value", + "annotations": {}, + "access_restriction": 1, + "encryption_config": {"kms_key_name": "kms_key_name_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 = backupvault.CreateBackupVaultRequest.meta.fields["backup_vault"] + + 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["backup_vault"].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["backup_vault"][field])): + del request_init["backup_vault"][field][i][subfield] + else: + del request_init["backup_vault"][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_backup_vault(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_backup_vault_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_create_backup_vault" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_create_backup_vault_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_backup_vault" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.CreateBackupVaultRequest.pb( + backupvault.CreateBackupVaultRequest() + ) + 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 = backupvault.CreateBackupVaultRequest() + 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_backup_vault( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backup_vaults_rest_bad_request( + request_type=backupvault.ListBackupVaultsRequest, +): + client = BackupDRClient( + 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_vaults(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListBackupVaultsRequest, + dict, + ], +) +def test_list_backup_vaults_rest_call_success(request_type): + client = BackupDRClient( + 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 = backupvault.ListBackupVaultsResponse( + 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 = backupvault.ListBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_vaults(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupVaultsPager) + 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_vaults_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_backup_vaults" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backup_vaults_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_backup_vaults" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.ListBackupVaultsRequest.pb( + backupvault.ListBackupVaultsRequest() + ) + 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 = backupvault.ListBackupVaultsResponse.to_json( + backupvault.ListBackupVaultsResponse() + ) + req.return_value.content = return_value + + request = backupvault.ListBackupVaultsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.ListBackupVaultsResponse() + post_with_metadata.return_value = ( + backupvault.ListBackupVaultsResponse(), + metadata, + ) + + client.list_backup_vaults( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_fetch_usable_backup_vaults_rest_bad_request( + request_type=backupvault.FetchUsableBackupVaultsRequest, +): + client = BackupDRClient( + 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.fetch_usable_backup_vaults(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.FetchUsableBackupVaultsRequest, + dict, + ], +) +def test_fetch_usable_backup_vaults_rest_call_success(request_type): + client = BackupDRClient( + 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 = backupvault.FetchUsableBackupVaultsResponse( + 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 = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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.fetch_usable_backup_vaults(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchUsableBackupVaultsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_usable_backup_vaults_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_fetch_usable_backup_vaults" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_fetch_usable_backup_vaults_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_fetch_usable_backup_vaults" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.FetchUsableBackupVaultsRequest.pb( + backupvault.FetchUsableBackupVaultsRequest() + ) + 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 = backupvault.FetchUsableBackupVaultsResponse.to_json( + backupvault.FetchUsableBackupVaultsResponse() + ) + req.return_value.content = return_value + + request = backupvault.FetchUsableBackupVaultsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.FetchUsableBackupVaultsResponse() + post_with_metadata.return_value = ( + backupvault.FetchUsableBackupVaultsResponse(), + metadata, + ) + + client.fetch_usable_backup_vaults( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_vault_rest_bad_request( + request_type=backupvault.GetBackupVaultRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupVaults/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_vault(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetBackupVaultRequest, + dict, + ], +) +def test_get_backup_vault_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupVaults/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 = backupvault.BackupVault( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + deletable=True, + etag="etag_value", + state=backupvault.BackupVault.State.CREATING, + backup_count=1278, + service_account="service_account_value", + total_stored_bytes=1946, + uid="uid_value", + access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + ) + + # 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 = backupvault.BackupVault.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_vault(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.BackupVault) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.deletable is True + assert response.etag == "etag_value" + assert response.state == backupvault.BackupVault.State.CREATING + assert response.backup_count == 1278 + assert response.service_account == "service_account_value" + assert response.total_stored_bytes == 1946 + assert response.uid == "uid_value" + assert ( + response.access_restriction + == backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_vault_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_backup_vault" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_vault_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_backup_vault" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.GetBackupVaultRequest.pb( + backupvault.GetBackupVaultRequest() + ) + 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 = backupvault.BackupVault.to_json(backupvault.BackupVault()) + req.return_value.content = return_value + + request = backupvault.GetBackupVaultRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.BackupVault() + post_with_metadata.return_value = backupvault.BackupVault(), metadata + + client.get_backup_vault( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_backup_vault_rest_bad_request( + request_type=backupvault.UpdateBackupVaultRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "backup_vault": { + "name": "projects/sample1/locations/sample2/backupVaults/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_backup_vault(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateBackupVaultRequest, + dict, + ], +) +def test_update_backup_vault_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "backup_vault": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3" + } + } + request_init["backup_vault"] = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "backup_minimum_enforced_retention_duration": {"seconds": 751, "nanos": 543}, + "backup_retention_inheritance": 1, + "deletable": True, + "etag": "etag_value", + "state": 1, + "effective_time": {}, + "backup_count": 1278, + "service_account": "service_account_value", + "total_stored_bytes": 1946, + "uid": "uid_value", + "annotations": {}, + "access_restriction": 1, + "encryption_config": {"kms_key_name": "kms_key_name_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 = backupvault.UpdateBackupVaultRequest.meta.fields["backup_vault"] + + 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["backup_vault"].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["backup_vault"][field])): + del request_init["backup_vault"][field][i][subfield] + else: + del request_init["backup_vault"][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_backup_vault(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_backup_vault_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_update_backup_vault" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup_vault_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_backup_vault" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.UpdateBackupVaultRequest.pb( + backupvault.UpdateBackupVaultRequest() + ) + 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 = backupvault.UpdateBackupVaultRequest() + 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_backup_vault( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_backup_vault_rest_bad_request( + request_type=backupvault.DeleteBackupVaultRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupVaults/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_backup_vault(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.DeleteBackupVaultRequest, + dict, + ], +) +def test_delete_backup_vault_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupVaults/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_backup_vault(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_vault_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_delete_backup_vault" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup_vault_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_backup_vault" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.DeleteBackupVaultRequest.pb( + backupvault.DeleteBackupVaultRequest() + ) + 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 = backupvault.DeleteBackupVaultRequest() + 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_vault( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_data_sources_rest_bad_request( + request_type=backupvault.ListDataSourcesRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/backupVaults/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_data_sources(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListDataSourcesRequest, + dict, + ], +) +def test_list_data_sources_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/backupVaults/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 = backupvault.ListDataSourcesResponse( + 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 = backupvault.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_data_sources(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_data_sources_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_data_sources" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_data_sources_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_data_sources" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.ListDataSourcesRequest.pb( + backupvault.ListDataSourcesRequest() + ) + 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 = backupvault.ListDataSourcesResponse.to_json( + backupvault.ListDataSourcesResponse() + ) + req.return_value.content = return_value + + request = backupvault.ListDataSourcesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.ListDataSourcesResponse() + post_with_metadata.return_value = ( + backupvault.ListDataSourcesResponse(), + metadata, + ) + + client.list_data_sources( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_data_source_rest_bad_request( + request_type=backupvault.GetDataSourceRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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_data_source(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetDataSourceRequest, + dict, + ], +) +def test_get_data_source_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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 = backupvault.DataSource( + name="name_value", + state=backupvault.DataSource.State.CREATING, + backup_count=1278, + etag="etag_value", + total_stored_bytes=1946, + config_state=backupvault.BackupConfigState.ACTIVE, + backup_blocked_by_vault_access_restriction=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 = backupvault.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_data_source(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupvault.DataSource) + assert response.name == "name_value" + assert response.state == backupvault.DataSource.State.CREATING + assert response.backup_count == 1278 + assert response.etag == "etag_value" + assert response.total_stored_bytes == 1946 + assert response.config_state == backupvault.BackupConfigState.ACTIVE + assert response.backup_blocked_by_vault_access_restriction is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_data_source_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_data_source" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_data_source_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_data_source" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.GetDataSourceRequest.pb( + backupvault.GetDataSourceRequest() + ) + 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 = backupvault.DataSource.to_json(backupvault.DataSource()) + req.return_value.content = return_value + + request = backupvault.GetDataSourceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.DataSource() + post_with_metadata.return_value = backupvault.DataSource(), metadata + + client.get_data_source( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_data_source_rest_bad_request( + request_type=backupvault.UpdateDataSourceRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "data_source": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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.update_data_source(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateDataSourceRequest, + dict, + ], +) +def test_update_data_source_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "data_source": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + } + request_init["data_source"] = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4", + "state": 1, + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "backup_count": 1278, + "etag": "etag_value", + "total_stored_bytes": 1946, + "config_state": 1, + "backup_config_info": { + "last_backup_state": 1, + "last_successful_backup_consistency_time": {}, + "last_backup_error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "gcp_backup_config": { + "backup_plan": "backup_plan_value", + "backup_plan_description": "backup_plan_description_value", + "backup_plan_association": "backup_plan_association_value", + "backup_plan_rules": [ + "backup_plan_rules_value1", + "backup_plan_rules_value2", + ], + "backup_plan_revision_name": "backup_plan_revision_name_value", + "backup_plan_revision_id": "backup_plan_revision_id_value", + "auto_protection_policy_binding": "auto_protection_policy_binding_value", + }, + "backup_appliance_backup_config": { + "backup_appliance_name": "backup_appliance_name_value", + "backup_appliance_id": 1966, + "sla_id": 620, + "application_name": "application_name_value", + "host_name": "host_name_value", + "slt_name": "slt_name_value", + "slp_name": "slp_name_value", + }, + }, + "data_source_gcp_resource": { + "gcp_resourcename": "gcp_resourcename_value", + "location": "location_value", + "type_": "type__value", + "compute_instance_datasource_properties": { + "name": "name_value", + "description": "description_value", + "machine_type": "machine_type_value", + "total_disk_count": 1718, + "total_disk_size_gb": 1904, + }, + "cloud_sql_instance_datasource_properties": { + "name": "name_value", + "database_installed_version": "database_installed_version_value", + "instance_create_time": {}, + "instance_tier": "instance_tier_value", + }, + "alloy_db_cluster_datasource_properties": {"name": "name_value"}, + "disk_datasource_properties": { + "name": "name_value", + "description": "description_value", + "type_": "type__value", + "size_gb": 739, + }, + }, + "data_source_backup_appliance_application": { + "application_name": "application_name_value", + "backup_appliance": "backup_appliance_value", + "appliance_id": 1241, + "type_": "type__value", + "application_id": 1472, + "hostname": "hostname_value", + "host_id": 746, + }, + "backup_blocked_by_vault_access_restriction": 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 = backupvault.UpdateDataSourceRequest.meta.fields["data_source"] + + 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["data_source"].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["data_source"][field])): + del request_init["data_source"][field][i][subfield] + else: + del request_init["data_source"][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_data_source(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_data_source_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_update_data_source" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_data_source_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_data_source" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.UpdateDataSourceRequest.pb( + backupvault.UpdateDataSourceRequest() + ) + 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 = backupvault.UpdateDataSourceRequest() + 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_data_source( + 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=backupvault.ListBackupsRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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.list_backups(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.ListBackupsRequest, + dict, + ], +) +def test_list_backups_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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 = backupvault.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 = backupvault.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.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_backups" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backups_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_backups" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.ListBackupsRequest.pb(backupvault.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 = backupvault.ListBackupsResponse.to_json( + backupvault.ListBackupsResponse() + ) + req.return_value.content = return_value + + request = backupvault.ListBackupsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.ListBackupsResponse() + post_with_metadata.return_value = backupvault.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_fetch_backups_for_resource_type_rest_bad_request( + request_type=backupvault.FetchBackupsForResourceTypeRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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.fetch_backups_for_resource_type(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.FetchBackupsForResourceTypeRequest, + dict, + ], +) +def test_fetch_backups_for_resource_type_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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 = backupvault.FetchBackupsForResourceTypeResponse( + next_page_token="next_page_token_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 = backupvault.FetchBackupsForResourceTypeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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.fetch_backups_for_resource_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchBackupsForResourceTypePager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_backups_for_resource_type_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_fetch_backups_for_resource_type" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_fetch_backups_for_resource_type_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_fetch_backups_for_resource_type" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.FetchBackupsForResourceTypeRequest.pb( + backupvault.FetchBackupsForResourceTypeRequest() + ) + 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 = backupvault.FetchBackupsForResourceTypeResponse.to_json( + backupvault.FetchBackupsForResourceTypeResponse() + ) + req.return_value.content = return_value + + request = backupvault.FetchBackupsForResourceTypeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.FetchBackupsForResourceTypeResponse() + post_with_metadata.return_value = ( + backupvault.FetchBackupsForResourceTypeResponse(), + metadata, + ) + + client.fetch_backups_for_resource_type( + 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=backupvault.GetBackupRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/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.get_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.GetBackupRequest, + dict, + ], +) +def test_get_backup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/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 = backupvault.Backup( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + etag="etag_value", + state=backupvault.Backup.State.CREATING, + backup_type=backupvault.Backup.BackupType.SCHEDULED, + resource_size_bytes=2056, + satisfies_pzs=True, + satisfies_pzi=True, + kms_key_versions=["kms_key_versions_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 = backupvault.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, backupvault.Backup) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.etag == "etag_value" + assert response.state == backupvault.Backup.State.CREATING + assert response.backup_type == backupvault.Backup.BackupType.SCHEDULED + assert response.resource_size_bytes == 2056 + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.kms_key_versions == ["kms_key_versions_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_backup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.BackupDRRestInterceptor, "pre_get_backup") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.GetBackupRequest.pb(backupvault.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 = backupvault.Backup.to_json(backupvault.Backup()) + req.return_value.content = return_value + + request = backupvault.GetBackupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupvault.Backup() + post_with_metadata.return_value = backupvault.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_update_backup_rest_bad_request(request_type=backupvault.UpdateBackupRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "backup": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/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.update_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.UpdateBackupRequest, + dict, + ], +) +def test_update_backup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "backup": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + } + request_init["backup"] = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "enforced_retention_end_time": {}, + "backup_retention_inheritance": 1, + "expire_time": {}, + "consistency_time": {}, + "etag": "etag_value", + "state": 1, + "service_locks": [ + { + "lock_until_time": {}, + "backup_appliance_lock_info": { + "backup_appliance_id": 1966, + "backup_appliance_name": "backup_appliance_name_value", + "lock_reason": "lock_reason_value", + "job_name": "job_name_value", + "backup_image": "backup_image_value", + "sla_id": 620, + }, + "service_lock_info": {"operation": "operation_value"}, + } + ], + "backup_appliance_locks": {}, + "compute_instance_backup_properties": { + "description": "description_value", + "tags": {"items": ["items_value1", "items_value2"]}, + "machine_type": "machine_type_value", + "can_ip_forward": True, + "network_interface": [ + { + "network": "network_value", + "subnetwork": "subnetwork_value", + "ip_address": "ip_address_value", + "ipv6_address": "ipv6_address_value", + "internal_ipv6_prefix_length": 2831, + "name": "name_value", + "access_configs": [ + { + "type_": 1, + "name": "name_value", + "external_ip": "external_ip_value", + "external_ipv6": "external_ipv6_value", + "external_ipv6_prefix_length": 2837, + "set_public_ptr": True, + "public_ptr_domain_name": "public_ptr_domain_name_value", + "network_tier": 1, + } + ], + "ipv6_access_configs": {}, + "alias_ip_ranges": [ + { + "ip_cidr_range": "ip_cidr_range_value", + "subnetwork_range_name": "subnetwork_range_name_value", + } + ], + "stack_type": 1, + "ipv6_access_type": 1, + "queue_count": 1197, + "nic_type": 1, + "network_attachment": "network_attachment_value", + } + ], + "disk": [ + { + "initialize_params": { + "disk_name": "disk_name_value", + "replica_zones": [ + "replica_zones_value1", + "replica_zones_value2", + ], + }, + "device_name": "device_name_value", + "kind": "kind_value", + "disk_type_deprecated": 1, + "mode": 1, + "source": "source_value", + "index": 536, + "boot": True, + "auto_delete": True, + "license_": ["license__value1", "license__value2"], + "disk_interface": 1, + "guest_os_feature": [{"type_": 1}], + "disk_encryption_key": { + "raw_key": "raw_key_value", + "rsa_encrypted_key": "rsa_encrypted_key_value", + "kms_key_name": "kms_key_name_value", + "kms_key_service_account": "kms_key_service_account_value", + }, + "disk_size_gb": 1261, + "saved_state": 1, + "disk_type": "disk_type_value", + "type_": 1, + } + ], + "metadata": {"items": [{"key": "key_value", "value": "value_value"}]}, + "service_account": [ + {"email": "email_value", "scopes": ["scopes_value1", "scopes_value2"]} + ], + "scheduling": { + "on_host_maintenance": 1, + "automatic_restart": True, + "preemptible": True, + "node_affinities": [ + { + "key": "key_value", + "operator": 1, + "values": ["values_value1", "values_value2"], + } + ], + "min_node_cpus": 1379, + "provisioning_model": 1, + "instance_termination_action": 1, + "local_ssd_recovery_timeout": {"seconds": 751, "nanos": 543}, + }, + "guest_accelerator": [ + { + "accelerator_type": "accelerator_type_value", + "accelerator_count": 1805, + } + ], + "min_cpu_platform": "min_cpu_platform_value", + "key_revocation_action_type": 1, + "source_instance": "source_instance_value", + "labels": {}, + }, + "cloud_sql_instance_backup_properties": { + "database_installed_version": "database_installed_version_value", + "final_backup": True, + "source_instance": "source_instance_value", + "instance_create_time": {}, + "instance_tier": "instance_tier_value", + "instance_delete_time": {}, + }, + "backup_appliance_backup_properties": { + "generation_id": 1368, + "finalize_time": {}, + "recovery_range_start_time": {}, + "recovery_range_end_time": {}, + }, + "alloy_db_backup_properties": { + "description": "description_value", + "stored_bytes": 1303, + "chain_id": "chain_id_value", + "database_version": "database_version_value", + }, + "disk_backup_properties": { + "description": "description_value", + "licenses": ["licenses_value1", "licenses_value2"], + "guest_os_feature": {}, + "architecture": 1, + "type_": "type__value", + "size_gb": 739, + "region": "region_value", + "zone": "zone_value", + "replica_zones": ["replica_zones_value1", "replica_zones_value2"], + "source_disk": "source_disk_value", + }, + "backup_type": 1, + "gcp_backup_plan_info": { + "backup_plan": "backup_plan_value", + "backup_plan_rule_id": "backup_plan_rule_id_value", + "backup_plan_revision_name": "backup_plan_revision_name_value", + "backup_plan_revision_id": "backup_plan_revision_id_value", + }, + "resource_size_bytes": 2056, + "satisfies_pzs": True, + "satisfies_pzi": True, + "gcp_resource": { + "gcp_resourcename": "gcp_resourcename_value", + "location": "location_value", + "type_": "type__value", + }, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + "verification_summary": { + "last_verification_time": {}, + "last_verification_state": 1, + "last_verification_execution": "last_verification_execution_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 = backupvault.UpdateBackupRequest.meta.fields["backup"] + + 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["backup"].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["backup"][field])): + del request_init["backup"][field][i][subfield] + else: + del request_init["backup"][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_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_update_backup_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_update_backup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.UpdateBackupRequest.pb( + backupvault.UpdateBackupRequest() + ) + 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 = backupvault.UpdateBackupRequest() + 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_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=backupvault.DeleteBackupRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/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_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.DeleteBackupRequest, + dict, + ], +) +def test_delete_backup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/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_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.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_delete_backup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.DeleteBackupRequest.pb( + backupvault.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 = backupvault.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_restore_backup_rest_bad_request(request_type=backupvault.RestoreBackupRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/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.restore_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupvault.RestoreBackupRequest, + dict, + ], +) +def test_restore_backup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/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.restore_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_restore_backup_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_restore_backup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_restore_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_restore_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupvault.RestoreBackupRequest.pb( + backupvault.RestoreBackupRequest() + ) + 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 = backupvault.RestoreBackupRequest() + 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.restore_backup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_backup_plan_rest_bad_request( + request_type=backupplan.CreateBackupPlanRequest, +): + client = BackupDRClient( + 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_backup_plan(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.CreateBackupPlanRequest, + dict, + ], +) +def test_create_backup_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup_plan"] = { + "name": "name_value", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "backup_rules": [ + { + "rule_id": "rule_id_value", + "backup_retention_days": 2237, + "standard_schedule": { + "recurrence_type": 1, + "hourly_frequency": 1748, + "days_of_week": [1], + "days_of_month": [1387, 1388], + "week_day_of_month": {"week_of_month": 1, "day_of_week": 1}, + "months": [1], + "backup_window": { + "start_hour_of_day": 1820, + "end_hour_of_day": 1573, + }, + "time_zone": "time_zone_value", + }, + } + ], + "state": 1, + "resource_type": "resource_type_value", + "etag": "etag_value", + "backup_vault": "backup_vault_value", + "backup_vault_service_account": "backup_vault_service_account_value", + "log_retention_days": 1929, + "supported_resource_types": [ + "supported_resource_types_value1", + "supported_resource_types_value2", + ], + "revision_id": "revision_id_value", + "revision_name": "revision_name_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 = backupplan.CreateBackupPlanRequest.meta.fields["backup_plan"] + + 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["backup_plan"].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["backup_plan"][field])): + del request_init["backup_plan"][field][i][subfield] + else: + del request_init["backup_plan"][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_backup_plan(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_backup_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_create_backup_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_create_backup_plan_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_backup_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.CreateBackupPlanRequest.pb( + backupplan.CreateBackupPlanRequest() + ) + 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 = backupplan.CreateBackupPlanRequest() + 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_backup_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_backup_plan_rest_bad_request( + request_type=backupplan.UpdateBackupPlanRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "backup_plan": { + "name": "projects/sample1/locations/sample2/backupPlans/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_backup_plan(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.UpdateBackupPlanRequest, + dict, + ], +) +def test_update_backup_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "backup_plan": { + "name": "projects/sample1/locations/sample2/backupPlans/sample3" + } + } + request_init["backup_plan"] = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "backup_rules": [ + { + "rule_id": "rule_id_value", + "backup_retention_days": 2237, + "standard_schedule": { + "recurrence_type": 1, + "hourly_frequency": 1748, + "days_of_week": [1], + "days_of_month": [1387, 1388], + "week_day_of_month": {"week_of_month": 1, "day_of_week": 1}, + "months": [1], + "backup_window": { + "start_hour_of_day": 1820, + "end_hour_of_day": 1573, + }, + "time_zone": "time_zone_value", + }, + } + ], + "state": 1, + "resource_type": "resource_type_value", + "etag": "etag_value", + "backup_vault": "backup_vault_value", + "backup_vault_service_account": "backup_vault_service_account_value", + "log_retention_days": 1929, + "supported_resource_types": [ + "supported_resource_types_value1", + "supported_resource_types_value2", + ], + "revision_id": "revision_id_value", + "revision_name": "revision_name_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 = backupplan.UpdateBackupPlanRequest.meta.fields["backup_plan"] + + 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["backup_plan"].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["backup_plan"][field])): + del request_init["backup_plan"][field][i][subfield] + else: + del request_init["backup_plan"][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_backup_plan(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_backup_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_update_backup_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_update_backup_plan_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_backup_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.UpdateBackupPlanRequest.pb( + backupplan.UpdateBackupPlanRequest() + ) + 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 = backupplan.UpdateBackupPlanRequest() + 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_backup_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_plan_rest_bad_request(request_type=backupplan.GetBackupPlanRequest): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupPlans/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_plan(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.GetBackupPlanRequest, + dict, + ], +) +def test_get_backup_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupPlans/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 = backupplan.BackupPlan( + name="name_value", + description="description_value", + state=backupplan.BackupPlan.State.CREATING, + resource_type="resource_type_value", + etag="etag_value", + backup_vault="backup_vault_value", + backup_vault_service_account="backup_vault_service_account_value", + log_retention_days=1929, + supported_resource_types=["supported_resource_types_value"], + revision_id="revision_id_value", + revision_name="revision_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 = backupplan.BackupPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_plan(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplan.BackupPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == backupplan.BackupPlan.State.CREATING + assert response.resource_type == "resource_type_value" + assert response.etag == "etag_value" + assert response.backup_vault == "backup_vault_value" + assert response.backup_vault_service_account == "backup_vault_service_account_value" + assert response.log_retention_days == 1929 + assert response.supported_resource_types == ["supported_resource_types_value"] + assert response.revision_id == "revision_id_value" + assert response.revision_name == "revision_name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_backup_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_backup_plan_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_backup_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.GetBackupPlanRequest.pb( + backupplan.GetBackupPlanRequest() + ) + 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 = backupplan.BackupPlan.to_json(backupplan.BackupPlan()) + req.return_value.content = return_value + + request = backupplan.GetBackupPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplan.BackupPlan() + post_with_metadata.return_value = backupplan.BackupPlan(), metadata + + client.get_backup_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backup_plans_rest_bad_request( + request_type=backupplan.ListBackupPlansRequest, +): + client = BackupDRClient( + 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_plans(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.ListBackupPlansRequest, + dict, + ], +) +def test_list_backup_plans_rest_call_success(request_type): + client = BackupDRClient( + 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 = backupplan.ListBackupPlansResponse( + 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 = backupplan.ListBackupPlansResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_plans(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlansPager) + 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_plans_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_backup_plans" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_list_backup_plans_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_backup_plans" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.ListBackupPlansRequest.pb( + backupplan.ListBackupPlansRequest() + ) + 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 = backupplan.ListBackupPlansResponse.to_json( + backupplan.ListBackupPlansResponse() + ) + req.return_value.content = return_value + + request = backupplan.ListBackupPlansRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplan.ListBackupPlansResponse() + post_with_metadata.return_value = backupplan.ListBackupPlansResponse(), metadata + + client.list_backup_plans( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_backup_plan_rest_bad_request( + request_type=backupplan.DeleteBackupPlanRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupPlans/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_backup_plan(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.DeleteBackupPlanRequest, + dict, + ], +) +def test_delete_backup_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/backupPlans/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_backup_plan(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_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_delete_backup_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_delete_backup_plan_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_backup_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.DeleteBackupPlanRequest.pb( + backupplan.DeleteBackupPlanRequest() + ) + 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 = backupplan.DeleteBackupPlanRequest() + 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_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_plan_revision_rest_bad_request( + request_type=backupplan.GetBackupPlanRevisionRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/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_plan_revision(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.GetBackupPlanRevisionRequest, + dict, + ], +) +def test_get_backup_plan_revision_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/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 = backupplan.BackupPlanRevision( + name="name_value", + revision_id="revision_id_value", + state=backupplan.BackupPlanRevision.State.CREATING, + ) + + # 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 = backupplan.BackupPlanRevision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_plan_revision(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupplan.BackupPlanRevision) + assert response.name == "name_value" + assert response.revision_id == "revision_id_value" + assert response.state == backupplan.BackupPlanRevision.State.CREATING + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_plan_revision_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_backup_plan_revision" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_backup_plan_revision_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_backup_plan_revision" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.GetBackupPlanRevisionRequest.pb( + backupplan.GetBackupPlanRevisionRequest() + ) + 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 = backupplan.BackupPlanRevision.to_json( + backupplan.BackupPlanRevision() + ) + req.return_value.content = return_value + + request = backupplan.GetBackupPlanRevisionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplan.BackupPlanRevision() + post_with_metadata.return_value = backupplan.BackupPlanRevision(), metadata + + client.get_backup_plan_revision( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backup_plan_revisions_rest_bad_request( + request_type=backupplan.ListBackupPlanRevisionsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/backupPlans/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_backup_plan_revisions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplan.ListBackupPlanRevisionsRequest, + dict, + ], +) +def test_list_backup_plan_revisions_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/backupPlans/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 = backupplan.ListBackupPlanRevisionsResponse( + 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 = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_plan_revisions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupPlanRevisionsPager) + 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_plan_revisions_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_backup_plan_revisions" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_backup_plan_revisions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_backup_plan_revisions" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplan.ListBackupPlanRevisionsRequest.pb( + backupplan.ListBackupPlanRevisionsRequest() + ) + 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 = backupplan.ListBackupPlanRevisionsResponse.to_json( + backupplan.ListBackupPlanRevisionsResponse() + ) + req.return_value.content = return_value + + request = backupplan.ListBackupPlanRevisionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupplan.ListBackupPlanRevisionsResponse() + post_with_metadata.return_value = ( + backupplan.ListBackupPlanRevisionsResponse(), + metadata, + ) + + client.list_backup_plan_revisions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_backup_plan_association_rest_bad_request( + request_type=backupplanassociation.CreateBackupPlanAssociationRequest, +): + client = BackupDRClient( + 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_backup_plan_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.CreateBackupPlanAssociationRequest, + dict, + ], +) +def test_create_backup_plan_association_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup_plan_association"] = { + "name": "name_value", + "resource_type": "resource_type_value", + "resource": "resource_value", + "backup_plan": "backup_plan_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "state": 1, + "rules_config_info": [ + { + "rule_id": "rule_id_value", + "last_backup_state": 1, + "last_backup_error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "last_successful_backup_consistency_time": {}, + } + ], + "data_source": "data_source_value", + "cloud_sql_instance_backup_plan_association_properties": { + "instance_create_time": {} + }, + "alloydb_cluster_backup_plan_association_properties": { + "cluster_uid": "cluster_uid_value" + }, + "backup_plan_revision_id": "backup_plan_revision_id_value", + "backup_plan_revision_name": "backup_plan_revision_name_value", + "auto_protection_policy_binding": "auto_protection_policy_binding_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 = backupplanassociation.CreateBackupPlanAssociationRequest.meta.fields[ + "backup_plan_association" + ] + + 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[ + "backup_plan_association" + ].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["backup_plan_association"][field])): + del request_init["backup_plan_association"][field][i][subfield] + else: + del request_init["backup_plan_association"][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_backup_plan_association(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_backup_plan_association_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_create_backup_plan_association" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_backup_plan_association_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_backup_plan_association" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplanassociation.CreateBackupPlanAssociationRequest.pb( + backupplanassociation.CreateBackupPlanAssociationRequest() + ) + 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 = backupplanassociation.CreateBackupPlanAssociationRequest() + 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_backup_plan_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_backup_plan_association_rest_bad_request( + request_type=backupplanassociation.UpdateBackupPlanAssociationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "backup_plan_association": { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/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_backup_plan_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupplanassociation.UpdateBackupPlanAssociationRequest, + dict, + ], +) +def test_update_backup_plan_association_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "backup_plan_association": { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + } + request_init["backup_plan_association"] = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3", + "resource_type": "resource_type_value", + "resource": "resource_value", + "backup_plan": "backup_plan_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "state": 1, + "rules_config_info": [ + { + "rule_id": "rule_id_value", + "last_backup_state": 1, + "last_backup_error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "last_successful_backup_consistency_time": {}, + } + ], + "data_source": "data_source_value", + "cloud_sql_instance_backup_plan_association_properties": { + "instance_create_time": {} + }, + "alloydb_cluster_backup_plan_association_properties": { + "cluster_uid": "cluster_uid_value" + }, + "backup_plan_revision_id": "backup_plan_revision_id_value", + "backup_plan_revision_name": "backup_plan_revision_name_value", + "auto_protection_policy_binding": "auto_protection_policy_binding_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 = backupplanassociation.UpdateBackupPlanAssociationRequest.meta.fields[ + "backup_plan_association" + ] + + 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[ + "backup_plan_association" + ].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["backup_plan_association"][field])): + del request_init["backup_plan_association"][field][i][subfield] + else: + del request_init["backup_plan_association"][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_backup_plan_association(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_backup_plan_association_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), ) + client = BackupDRClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.initialize_service), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + 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.BackupDRRestInterceptor, "post_update_backup_plan_association" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_update_backup_plan_association_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_backup_plan_association" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupplanassociation.UpdateBackupPlanAssociationRequest.pb( + backupplanassociation.UpdateBackupPlanAssociationRequest() ) - await client.initialize_service(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.InitializeServiceRequest() - assert args[0] == request_msg + 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 = backupplanassociation.UpdateBackupPlanAssociationRequest() + 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 -def test_transport_kind_rest(): - transport = BackupDRClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + client.update_backup_plan_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_management_servers_rest_bad_request( - request_type=backupdr.ListManagementServersRequest, + +def test_get_backup_plan_association_rest_bad_request( + request_type=backupplanassociation.GetBackupPlanAssociationRequest, ): client = BackupDRClient( 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/backupPlanAssociations/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -26246,31 +50889,40 @@ def test_list_management_servers_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_management_servers(request) + client.get_backup_plan_association(request) @pytest.mark.parametrize( "request_type", [ - backupdr.ListManagementServersRequest, + backupplanassociation.GetBackupPlanAssociationRequest, dict, ], ) -def test_list_management_servers_rest_call_success(request_type): +def test_get_backup_plan_association_rest_call_success(request_type): client = BackupDRClient( 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/backupPlanAssociations/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 = backupdr.ListManagementServersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = backupplanassociation.BackupPlanAssociation( + name="name_value", + resource_type="resource_type_value", + resource="resource_value", + backup_plan="backup_plan_value", + state=backupplanassociation.BackupPlanAssociation.State.CREATING, + data_source="data_source_value", + backup_plan_revision_id="backup_plan_revision_id_value", + backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", ) # Wrap the value into a proper Response obj @@ -26278,21 +50930,31 @@ def test_list_management_servers_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupdr.ListManagementServersResponse.pb(return_value) + return_value = backupplanassociation.BackupPlanAssociation.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_management_servers(request) + response = client.get_backup_plan_association(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListManagementServersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, backupplanassociation.BackupPlanAssociation) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert response.resource == "resource_value" + assert response.backup_plan == "backup_plan_value" + assert response.state == backupplanassociation.BackupPlanAssociation.State.CREATING + assert response.data_source == "data_source_value" + assert response.backup_plan_revision_id == "backup_plan_revision_id_value" + assert response.backup_plan_revision_name == "backup_plan_revision_name_value" + assert ( + response.auto_protection_policy_binding + == "auto_protection_policy_binding_value" + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_management_servers_rest_interceptors(null_interceptor): +def test_get_backup_plan_association_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -26303,21 +50965,21 @@ def test_list_management_servers_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.BackupDRRestInterceptor, "post_list_management_servers" + transports.BackupDRRestInterceptor, "post_get_backup_plan_association" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_list_management_servers_with_metadata", + "post_get_backup_plan_association_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_list_management_servers" + transports.BackupDRRestInterceptor, "pre_get_backup_plan_association" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupdr.ListManagementServersRequest.pb( - backupdr.ListManagementServersRequest() + pb_message = backupplanassociation.GetBackupPlanAssociationRequest.pb( + backupplanassociation.GetBackupPlanAssociationRequest() ) transcode.return_value = { "method": "post", @@ -26329,24 +50991,24 @@ def test_list_management_servers_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 = backupdr.ListManagementServersResponse.to_json( - backupdr.ListManagementServersResponse() + return_value = backupplanassociation.BackupPlanAssociation.to_json( + backupplanassociation.BackupPlanAssociation() ) req.return_value.content = return_value - request = backupdr.ListManagementServersRequest() + request = backupplanassociation.GetBackupPlanAssociationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupdr.ListManagementServersResponse() + post.return_value = backupplanassociation.BackupPlanAssociation() post_with_metadata.return_value = ( - backupdr.ListManagementServersResponse(), + backupplanassociation.BackupPlanAssociation(), metadata, ) - client.list_management_servers( + client.get_backup_plan_association( request, metadata=[ ("key", "val"), @@ -26359,16 +51021,14 @@ def test_list_management_servers_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_management_server_rest_bad_request( - request_type=backupdr.GetManagementServerRequest, +def test_list_backup_plan_associations_rest_bad_request( + request_type=backupplanassociation.ListBackupPlanAssociationsRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/managementServers/sample3" - } + 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. @@ -26384,39 +51044,31 @@ def test_get_management_server_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_management_server(request) + client.list_backup_plan_associations(request) @pytest.mark.parametrize( "request_type", [ - backupdr.GetManagementServerRequest, + backupplanassociation.ListBackupPlanAssociationsRequest, dict, ], ) -def test_get_management_server_rest_call_success(request_type): +def test_list_backup_plan_associations_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/managementServers/sample3" - } + 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 = backupdr.ManagementServer( - name="name_value", - description="description_value", - type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, - state=backupdr.ManagementServer.InstanceState.CREATING, - etag="etag_value", - oauth2_client_id="oauth2_client_id_value", - ba_proxy_uri=["ba_proxy_uri_value"], - satisfies_pzi=True, + return_value = backupplanassociation.ListBackupPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) # Wrap the value into a proper Response obj @@ -26424,27 +51076,23 @@ def test_get_management_server_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupdr.ManagementServer.pb(return_value) + return_value = backupplanassociation.ListBackupPlanAssociationsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_management_server(request) + response = client.list_backup_plan_associations(request) # Establish that the response is the type that we expect. - assert isinstance(response, backupdr.ManagementServer) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.type_ == backupdr.ManagementServer.InstanceType.BACKUP_RESTORE - assert response.state == backupdr.ManagementServer.InstanceState.CREATING - assert response.etag == "etag_value" - assert response.oauth2_client_id == "oauth2_client_id_value" - assert response.ba_proxy_uri == ["ba_proxy_uri_value"] - assert response.satisfies_pzi is True + assert isinstance(response, pagers.ListBackupPlanAssociationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_management_server_rest_interceptors(null_interceptor): +def test_list_backup_plan_associations_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -26455,21 +51103,21 @@ def test_get_management_server_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.BackupDRRestInterceptor, "post_get_management_server" + transports.BackupDRRestInterceptor, "post_list_backup_plan_associations" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_get_management_server_with_metadata", + "post_list_backup_plan_associations_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_get_management_server" + transports.BackupDRRestInterceptor, "pre_list_backup_plan_associations" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupdr.GetManagementServerRequest.pb( - backupdr.GetManagementServerRequest() + pb_message = backupplanassociation.ListBackupPlanAssociationsRequest.pb( + backupplanassociation.ListBackupPlanAssociationsRequest() ) transcode.return_value = { "method": "post", @@ -26481,19 +51129,24 @@ def test_get_management_server_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 = backupdr.ManagementServer.to_json(backupdr.ManagementServer()) + return_value = backupplanassociation.ListBackupPlanAssociationsResponse.to_json( + backupplanassociation.ListBackupPlanAssociationsResponse() + ) req.return_value.content = return_value - request = backupdr.GetManagementServerRequest() + request = backupplanassociation.ListBackupPlanAssociationsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupdr.ManagementServer() - post_with_metadata.return_value = backupdr.ManagementServer(), metadata + post.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + post_with_metadata.return_value = ( + backupplanassociation.ListBackupPlanAssociationsResponse(), + metadata, + ) - client.get_management_server( + client.list_backup_plan_associations( request, metadata=[ ("key", "val"), @@ -26506,8 +51159,8 @@ def test_get_management_server_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_management_server_rest_bad_request( - request_type=backupdr.CreateManagementServerRequest, +def test_fetch_backup_plan_associations_for_resource_type_rest_bad_request( + request_type=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -26529,136 +51182,61 @@ def test_create_management_server_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_management_server(request) + client.fetch_backup_plan_associations_for_resource_type(request) @pytest.mark.parametrize( "request_type", [ - backupdr.CreateManagementServerRequest, + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, dict, ], ) -def test_create_management_server_rest_call_success(request_type): +def test_fetch_backup_plan_associations_for_resource_type_rest_call_success( + request_type, +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["management_server"] = { - "name": "name_value", - "description": "description_value", - "labels": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "type_": 1, - "management_uri": {"web_ui": "web_ui_value", "api": "api_value"}, - "workforce_identity_based_management_uri": { - "first_party_management_uri": "first_party_management_uri_value", - "third_party_management_uri": "third_party_management_uri_value", - }, - "state": 1, - "networks": [{"network": "network_value", "peering_mode": 1}], - "etag": "etag_value", - "oauth2_client_id": "oauth2_client_id_value", - "workforce_identity_based_oauth2_client_id": { - "first_party_oauth2_client_id": "first_party_oauth2_client_id_value", - "third_party_oauth2_client_id": "third_party_oauth2_client_id_value", - }, - "ba_proxy_uri": ["ba_proxy_uri_value1", "ba_proxy_uri_value2"], - "satisfies_pzs": {"value": True}, - "satisfies_pzi": 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 = backupdr.CreateManagementServerRequest.meta.fields["management_server"] - - 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["management_server"].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["management_server"][field])): - del request_init["management_server"][field][i][subfield] - else: - del request_init["management_server"][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") + return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + next_page_token="next_page_token_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 = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_management_server(request) + response = client.fetch_backup_plan_associations_for_resource_type(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.FetchBackupPlanAssociationsForResourceTypePager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_management_server_rest_interceptors(null_interceptor): +def test_fetch_backup_plan_associations_for_resource_type_rest_interceptors( + null_interceptor, +): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -26668,23 +51246,24 @@ def test_create_management_server_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.BackupDRRestInterceptor, "post_create_management_server" + transports.BackupDRRestInterceptor, + "post_fetch_backup_plan_associations_for_resource_type", ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_create_management_server_with_metadata", + "post_fetch_backup_plan_associations_for_resource_type_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_create_management_server" + transports.BackupDRRestInterceptor, + "pre_fetch_backup_plan_associations_for_resource_type", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupdr.CreateManagementServerRequest.pb( - backupdr.CreateManagementServerRequest() + pb_message = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest.pb( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() ) transcode.return_value = { "method": "post", @@ -26696,19 +51275,28 @@ def test_create_management_server_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 = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) req.return_value.content = return_value - request = backupdr.CreateManagementServerRequest() + request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) 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 = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + post_with_metadata.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse(), + metadata, + ) - client.create_management_server( + client.fetch_backup_plan_associations_for_resource_type( request, metadata=[ ("key", "val"), @@ -26721,15 +51309,15 @@ def test_create_management_server_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_management_server_rest_bad_request( - request_type=backupdr.DeleteManagementServerRequest, +def test_delete_backup_plan_association_rest_bad_request( + request_type=backupplanassociation.DeleteBackupPlanAssociationRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/managementServers/sample3" + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" } request = request_type(**request_init) @@ -26746,24 +51334,24 @@ def test_delete_management_server_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_management_server(request) + client.delete_backup_plan_association(request) @pytest.mark.parametrize( "request_type", [ - backupdr.DeleteManagementServerRequest, + backupplanassociation.DeleteBackupPlanAssociationRequest, dict, ], ) -def test_delete_management_server_rest_call_success(request_type): +def test_delete_backup_plan_association_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/managementServers/sample3" + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" } request = request_type(**request_init) @@ -26779,14 +51367,14 @@ def test_delete_management_server_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_management_server(request) + response = client.delete_backup_plan_association(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_management_server_rest_interceptors(null_interceptor): +def test_delete_backup_plan_association_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -26798,21 +51386,21 @@ def test_delete_management_server_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.BackupDRRestInterceptor, "post_delete_management_server" + transports.BackupDRRestInterceptor, "post_delete_backup_plan_association" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_delete_management_server_with_metadata", + "post_delete_backup_plan_association_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_delete_management_server" + transports.BackupDRRestInterceptor, "pre_delete_backup_plan_association" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupdr.DeleteManagementServerRequest.pb( - backupdr.DeleteManagementServerRequest() + pb_message = backupplanassociation.DeleteBackupPlanAssociationRequest.pb( + backupplanassociation.DeleteBackupPlanAssociationRequest() ) transcode.return_value = { "method": "post", @@ -26827,7 +51415,7 @@ def test_delete_management_server_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupdr.DeleteManagementServerRequest() + request = backupplanassociation.DeleteBackupPlanAssociationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -26836,7 +51424,7 @@ def test_delete_management_server_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_management_server( + client.delete_backup_plan_association( request, metadata=[ ("key", "val"), @@ -26849,14 +51437,16 @@ def test_delete_management_server_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_backup_vault_rest_bad_request( - request_type=backupvault.CreateBackupVaultRequest, +def test_trigger_backup_rest_bad_request( + request_type=backupplanassociation.TriggerBackupRequest, ): client = BackupDRClient( 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/backupPlanAssociations/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -26872,110 +51462,25 @@ def test_create_backup_vault_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_backup_vault(request) + client.trigger_backup(request) @pytest.mark.parametrize( "request_type", [ - backupvault.CreateBackupVaultRequest, + backupplanassociation.TriggerBackupRequest, dict, ], ) -def test_create_backup_vault_rest_call_success(request_type): +def test_trigger_backup_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["backup_vault"] = { - "name": "name_value", - "description": "description_value", - "labels": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "backup_minimum_enforced_retention_duration": {"seconds": 751, "nanos": 543}, - "backup_retention_inheritance": 1, - "deletable": True, - "etag": "etag_value", - "state": 1, - "effective_time": {}, - "backup_count": 1278, - "service_account": "service_account_value", - "total_stored_bytes": 1946, - "uid": "uid_value", - "annotations": {}, - "access_restriction": 1, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, + request_init = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" } - # 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 = backupvault.CreateBackupVaultRequest.meta.fields["backup_vault"] - - 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["backup_vault"].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["backup_vault"][field])): - del request_init["backup_vault"][field][i][subfield] - else: - del request_init["backup_vault"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -26990,14 +51495,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_backup_vault(request) + response = client.trigger_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_create_backup_vault_rest_interceptors(null_interceptor): +def test_trigger_backup_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -27009,20 +51514,20 @@ def test_create_backup_vault_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.BackupDRRestInterceptor, "post_create_backup_vault" + transports.BackupDRRestInterceptor, "post_trigger_backup" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_create_backup_vault_with_metadata" + transports.BackupDRRestInterceptor, "post_trigger_backup_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_create_backup_vault" + transports.BackupDRRestInterceptor, "pre_trigger_backup" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.CreateBackupVaultRequest.pb( - backupvault.CreateBackupVaultRequest() + pb_message = backupplanassociation.TriggerBackupRequest.pb( + backupplanassociation.TriggerBackupRequest() ) transcode.return_value = { "method": "post", @@ -27037,7 +51542,7 @@ def test_create_backup_vault_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupvault.CreateBackupVaultRequest() + request = backupplanassociation.TriggerBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -27046,7 +51551,7 @@ def test_create_backup_vault_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_backup_vault( + client.trigger_backup( request, metadata=[ ("key", "val"), @@ -27059,14 +51564,16 @@ def test_create_backup_vault_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_backup_vaults_rest_bad_request( - request_type=backupvault.ListBackupVaultsRequest, +def test_get_data_source_reference_rest_bad_request( + request_type=datasourcereference.GetDataSourceReferenceRequest, ): client = BackupDRClient( 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/dataSourceReferences/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -27082,31 +51589,36 @@ def test_list_backup_vaults_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_backup_vaults(request) + client.get_data_source_reference(request) @pytest.mark.parametrize( "request_type", [ - backupvault.ListBackupVaultsRequest, + datasourcereference.GetDataSourceReferenceRequest, dict, ], ) -def test_list_backup_vaults_rest_call_success(request_type): +def test_get_data_source_reference_rest_call_success(request_type): client = BackupDRClient( 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/dataSourceReferences/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 = backupvault.ListBackupVaultsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = datasourcereference.DataSourceReference( + name="name_value", + data_source="data_source_value", + data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, + data_source_backup_count=2535, + total_stored_bytes=1946, ) # Wrap the value into a proper Response obj @@ -27114,21 +51626,26 @@ def test_list_backup_vaults_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupvault.ListBackupVaultsResponse.pb(return_value) + return_value = datasourcereference.DataSourceReference.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_vaults(request) + response = client.get_data_source_reference(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupVaultsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, datasourcereference.DataSourceReference) + assert response.name == "name_value" + assert response.data_source == "data_source_value" + assert ( + response.data_source_backup_config_state == backupvault.BackupConfigState.ACTIVE + ) + assert response.data_source_backup_count == 2535 + assert response.total_stored_bytes == 1946 @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_backup_vaults_rest_interceptors(null_interceptor): +def test_get_data_source_reference_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -27139,20 +51656,21 @@ def test_list_backup_vaults_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.BackupDRRestInterceptor, "post_list_backup_vaults" + transports.BackupDRRestInterceptor, "post_get_data_source_reference" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_list_backup_vaults_with_metadata" + transports.BackupDRRestInterceptor, + "post_get_data_source_reference_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_list_backup_vaults" + transports.BackupDRRestInterceptor, "pre_get_data_source_reference" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.ListBackupVaultsRequest.pb( - backupvault.ListBackupVaultsRequest() + pb_message = datasourcereference.GetDataSourceReferenceRequest.pb( + datasourcereference.GetDataSourceReferenceRequest() ) transcode.return_value = { "method": "post", @@ -27164,24 +51682,24 @@ def test_list_backup_vaults_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 = backupvault.ListBackupVaultsResponse.to_json( - backupvault.ListBackupVaultsResponse() + return_value = datasourcereference.DataSourceReference.to_json( + datasourcereference.DataSourceReference() ) req.return_value.content = return_value - request = backupvault.ListBackupVaultsRequest() + request = datasourcereference.GetDataSourceReferenceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupvault.ListBackupVaultsResponse() + post.return_value = datasourcereference.DataSourceReference() post_with_metadata.return_value = ( - backupvault.ListBackupVaultsResponse(), + datasourcereference.DataSourceReference(), metadata, ) - client.list_backup_vaults( + client.get_data_source_reference( request, metadata=[ ("key", "val"), @@ -27194,8 +51712,8 @@ def test_list_backup_vaults_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_usable_backup_vaults_rest_bad_request( - request_type=backupvault.FetchUsableBackupVaultsRequest, +def test_list_data_source_references_rest_bad_request( + request_type=datasourcereference.ListDataSourceReferencesRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -27217,17 +51735,17 @@ def test_fetch_usable_backup_vaults_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.fetch_usable_backup_vaults(request) + client.list_data_source_references(request) @pytest.mark.parametrize( "request_type", [ - backupvault.FetchUsableBackupVaultsRequest, + datasourcereference.ListDataSourceReferencesRequest, dict, ], ) -def test_fetch_usable_backup_vaults_rest_call_success(request_type): +def test_list_data_source_references_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -27239,7 +51757,7 @@ def test_fetch_usable_backup_vaults_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 = backupvault.FetchUsableBackupVaultsResponse( + return_value = datasourcereference.ListDataSourceReferencesResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -27249,21 +51767,23 @@ def test_fetch_usable_backup_vaults_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) + return_value = datasourcereference.ListDataSourceReferencesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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.fetch_usable_backup_vaults(request) + response = client.list_data_source_references(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchUsableBackupVaultsPager) + assert isinstance(response, pagers.ListDataSourceReferencesPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_usable_backup_vaults_rest_interceptors(null_interceptor): +def test_list_data_source_references_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -27274,21 +51794,21 @@ def test_fetch_usable_backup_vaults_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.BackupDRRestInterceptor, "post_fetch_usable_backup_vaults" + transports.BackupDRRestInterceptor, "post_list_data_source_references" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_fetch_usable_backup_vaults_with_metadata", + "post_list_data_source_references_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_fetch_usable_backup_vaults" + transports.BackupDRRestInterceptor, "pre_list_data_source_references" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.FetchUsableBackupVaultsRequest.pb( - backupvault.FetchUsableBackupVaultsRequest() + pb_message = datasourcereference.ListDataSourceReferencesRequest.pb( + datasourcereference.ListDataSourceReferencesRequest() ) transcode.return_value = { "method": "post", @@ -27300,24 +51820,24 @@ def test_fetch_usable_backup_vaults_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 = backupvault.FetchUsableBackupVaultsResponse.to_json( - backupvault.FetchUsableBackupVaultsResponse() + return_value = datasourcereference.ListDataSourceReferencesResponse.to_json( + datasourcereference.ListDataSourceReferencesResponse() ) req.return_value.content = return_value - request = backupvault.FetchUsableBackupVaultsRequest() + request = datasourcereference.ListDataSourceReferencesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupvault.FetchUsableBackupVaultsResponse() + post.return_value = datasourcereference.ListDataSourceReferencesResponse() post_with_metadata.return_value = ( - backupvault.FetchUsableBackupVaultsResponse(), + datasourcereference.ListDataSourceReferencesResponse(), metadata, ) - client.fetch_usable_backup_vaults( + client.list_data_source_references( request, metadata=[ ("key", "val"), @@ -27330,14 +51850,14 @@ def test_fetch_usable_backup_vaults_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_backup_vault_rest_bad_request( - request_type=backupvault.GetBackupVaultRequest, +def test_fetch_data_source_references_for_resource_type_rest_bad_request( + request_type=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backupVaults/sample3"} + 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. @@ -27353,40 +51873,32 @@ def test_get_backup_vault_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_backup_vault(request) + client.fetch_data_source_references_for_resource_type(request) @pytest.mark.parametrize( "request_type", [ - backupvault.GetBackupVaultRequest, + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, dict, ], ) -def test_get_backup_vault_rest_call_success(request_type): +def test_fetch_data_source_references_for_resource_type_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backupVaults/sample3"} + 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 = backupvault.BackupVault( - name="name_value", - description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, - deletable=True, - etag="etag_value", - state=backupvault.BackupVault.State.CREATING, - backup_count=1278, - service_account="service_account_value", - total_stored_bytes=1946, - uid="uid_value", - access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + next_page_token="next_page_token_value", + ) ) # Wrap the value into a proper Response obj @@ -27394,36 +51906,26 @@ def test_get_backup_vault_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupvault.BackupVault.pb(return_value) + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_vault(request) + response = client.fetch_data_source_references_for_resource_type(request) # Establish that the response is the type that we expect. - assert isinstance(response, backupvault.BackupVault) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( - response.backup_retention_inheritance - == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION - ) - assert response.deletable is True - assert response.etag == "etag_value" - assert response.state == backupvault.BackupVault.State.CREATING - assert response.backup_count == 1278 - assert response.service_account == "service_account_value" - assert response.total_stored_bytes == 1946 - assert response.uid == "uid_value" - assert ( - response.access_restriction - == backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT - ) + assert isinstance(response, pagers.FetchDataSourceReferencesForResourceTypePager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_vault_rest_interceptors(null_interceptor): +def test_fetch_data_source_references_for_resource_type_rest_interceptors( + null_interceptor, +): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -27434,20 +51936,25 @@ def test_get_backup_vault_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.BackupDRRestInterceptor, "post_get_backup_vault" + transports.BackupDRRestInterceptor, + "post_fetch_data_source_references_for_resource_type", ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_get_backup_vault_with_metadata" + transports.BackupDRRestInterceptor, + "post_fetch_data_source_references_for_resource_type_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_get_backup_vault" + transports.BackupDRRestInterceptor, + "pre_fetch_data_source_references_for_resource_type", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.GetBackupVaultRequest.pb( - backupvault.GetBackupVaultRequest() + pb_message = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest.pb( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + ) ) transcode.return_value = { "method": "post", @@ -27459,19 +51966,26 @@ def test_get_backup_vault_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 = backupvault.BackupVault.to_json(backupvault.BackupVault()) + return_value = datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.to_json( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) req.return_value.content = return_value - request = backupvault.GetBackupVaultRequest() + request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupvault.BackupVault() - post_with_metadata.return_value = backupvault.BackupVault(), metadata + post.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + post_with_metadata.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse(), + metadata, + ) - client.get_backup_vault( + client.fetch_data_source_references_for_resource_type( request, metadata=[ ("key", "val"), @@ -27484,18 +51998,14 @@ def test_get_backup_vault_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_backup_vault_rest_bad_request( - request_type=backupvault.UpdateBackupVaultRequest, +def test_initialize_service_rest_bad_request( + request_type=backupdr.InitializeServiceRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "backup_vault": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3" - } - } + request_init = {"name": "projects/sample1/locations/sample2/serviceConfig"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -27511,114 +52021,23 @@ def test_update_backup_vault_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_backup_vault(request) + client.initialize_service(request) @pytest.mark.parametrize( "request_type", [ - backupvault.UpdateBackupVaultRequest, + backupdr.InitializeServiceRequest, dict, ], ) -def test_update_backup_vault_rest_call_success(request_type): +def test_initialize_service_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "backup_vault": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3" - } - } - request_init["backup_vault"] = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3", - "description": "description_value", - "labels": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "backup_minimum_enforced_retention_duration": {"seconds": 751, "nanos": 543}, - "backup_retention_inheritance": 1, - "deletable": True, - "etag": "etag_value", - "state": 1, - "effective_time": {}, - "backup_count": 1278, - "service_account": "service_account_value", - "total_stored_bytes": 1946, - "uid": "uid_value", - "annotations": {}, - "access_restriction": 1, - "encryption_config": {"kms_key_name": "kms_key_name_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 = backupvault.UpdateBackupVaultRequest.meta.fields["backup_vault"] - - 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["backup_vault"].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["backup_vault"][field])): - del request_init["backup_vault"][field][i][subfield] - else: - del request_init["backup_vault"][field][subfield] + request_init = {"name": "projects/sample1/locations/sample2/serviceConfig"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -27633,14 +52052,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_backup_vault(request) + response = client.initialize_service(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_backup_vault_rest_interceptors(null_interceptor): +def test_initialize_service_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -27652,20 +52071,20 @@ def test_update_backup_vault_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.BackupDRRestInterceptor, "post_update_backup_vault" + transports.BackupDRRestInterceptor, "post_initialize_service" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_update_backup_vault_with_metadata" + transports.BackupDRRestInterceptor, "post_initialize_service_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_update_backup_vault" + transports.BackupDRRestInterceptor, "pre_initialize_service" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.UpdateBackupVaultRequest.pb( - backupvault.UpdateBackupVaultRequest() + pb_message = backupdr.InitializeServiceRequest.pb( + backupdr.InitializeServiceRequest() ) transcode.return_value = { "method": "post", @@ -27680,7 +52099,7 @@ def test_update_backup_vault_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupvault.UpdateBackupVaultRequest() + request = backupdr.InitializeServiceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -27689,7 +52108,7 @@ def test_update_backup_vault_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_backup_vault( + client.initialize_service( request, metadata=[ ("key", "val"), @@ -27702,14 +52121,14 @@ def test_update_backup_vault_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_backup_vault_rest_bad_request( - request_type=backupvault.DeleteBackupVaultRequest, +def test_create_auto_protection_policy_rest_bad_request( + request_type=autoprotectionpolicy.CreateAutoProtectionPolicyRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backupVaults/sample3"} + 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. @@ -27725,23 +52144,121 @@ def test_delete_backup_vault_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_backup_vault(request) + client.create_auto_protection_policy(request) @pytest.mark.parametrize( "request_type", [ - backupvault.DeleteBackupVaultRequest, + autoprotectionpolicy.CreateAutoProtectionPolicyRequest, dict, ], ) -def test_delete_backup_vault_rest_call_success(request_type): +def test_create_auto_protection_policy_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backupVaults/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["auto_protection_policy"] = { + "name": "name_value", + "description": "description_value", + "backup_plan_details": [ + {"resource_type": "resource_type_value", "backup_plan": "backup_plan_value"} + ], + "criteria": { + "matching_conditions": [ + { + "label_condition": { + "key": "key_value", + "values": ["values_value1", "values_value2"], + } + } + ] + }, + "state": 1, + "etag": "etag_value", + "binding_summary": {"project_count": 1407}, + "policy_evaluation_summary": { + "matching_resource_count": 2458, + "protected_resource_count": 2585, + "failed_resource_count": 2228, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + } + # 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest.meta.fields[ + "auto_protection_policy" + ] + + 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[ + "auto_protection_policy" + ].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["auto_protection_policy"][field])): + del request_init["auto_protection_policy"][field][i][subfield] + else: + del request_init["auto_protection_policy"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -27756,14 +52273,14 @@ def test_delete_backup_vault_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_backup_vault(request) + response = client.create_auto_protection_policy(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_vault_rest_interceptors(null_interceptor): +def test_create_auto_protection_policy_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -27775,20 +52292,21 @@ def test_delete_backup_vault_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.BackupDRRestInterceptor, "post_delete_backup_vault" + transports.BackupDRRestInterceptor, "post_create_auto_protection_policy" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_delete_backup_vault_with_metadata" + transports.BackupDRRestInterceptor, + "post_create_auto_protection_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_delete_backup_vault" + transports.BackupDRRestInterceptor, "pre_create_auto_protection_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.DeleteBackupVaultRequest.pb( - backupvault.DeleteBackupVaultRequest() + pb_message = autoprotectionpolicy.CreateAutoProtectionPolicyRequest.pb( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest() ) transcode.return_value = { "method": "post", @@ -27803,7 +52321,7 @@ def test_delete_backup_vault_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupvault.DeleteBackupVaultRequest() + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -27812,7 +52330,7 @@ def test_delete_backup_vault_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_backup_vault( + client.create_auto_protection_policy( request, metadata=[ ("key", "val"), @@ -27825,14 +52343,14 @@ def test_delete_backup_vault_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_data_sources_rest_bad_request( - request_type=backupvault.ListDataSourcesRequest, +def test_list_auto_protection_policies_rest_bad_request( + request_type=autoprotectionpolicy.ListAutoProtectionPoliciesRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/backupVaults/sample3"} + 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. @@ -27848,29 +52366,29 @@ def test_list_data_sources_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_data_sources(request) + client.list_auto_protection_policies(request) @pytest.mark.parametrize( "request_type", [ - backupvault.ListDataSourcesRequest, + autoprotectionpolicy.ListAutoProtectionPoliciesRequest, dict, ], ) -def test_list_data_sources_rest_call_success(request_type): +def test_list_auto_protection_policies_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/backupVaults/sample3"} + 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 = backupvault.ListDataSourcesResponse( + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -27880,21 +52398,23 @@ def test_list_data_sources_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupvault.ListDataSourcesResponse.pb(return_value) + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_data_sources(request) + response = client.list_auto_protection_policies(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourcesPager) + assert isinstance(response, pagers.ListAutoProtectionPoliciesPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_data_sources_rest_interceptors(null_interceptor): +def test_list_auto_protection_policies_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -27905,20 +52425,21 @@ def test_list_data_sources_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.BackupDRRestInterceptor, "post_list_data_sources" + transports.BackupDRRestInterceptor, "post_list_auto_protection_policies" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_list_data_sources_with_metadata" + transports.BackupDRRestInterceptor, + "post_list_auto_protection_policies_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_list_data_sources" + transports.BackupDRRestInterceptor, "pre_list_auto_protection_policies" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.ListDataSourcesRequest.pb( - backupvault.ListDataSourcesRequest() + pb_message = autoprotectionpolicy.ListAutoProtectionPoliciesRequest.pb( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest() ) transcode.return_value = { "method": "post", @@ -27930,24 +52451,24 @@ def test_list_data_sources_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 = backupvault.ListDataSourcesResponse.to_json( - backupvault.ListDataSourcesResponse() + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.to_json( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse() ) req.return_value.content = return_value - request = backupvault.ListDataSourcesRequest() + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupvault.ListDataSourcesResponse() + post.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() post_with_metadata.return_value = ( - backupvault.ListDataSourcesResponse(), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse(), metadata, ) - client.list_data_sources( + client.list_auto_protection_policies( request, metadata=[ ("key", "val"), @@ -27960,15 +52481,15 @@ def test_list_data_sources_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_data_source_rest_bad_request( - request_type=backupvault.GetDataSourceRequest, +def test_get_auto_protection_policy_rest_bad_request( + request_type=autoprotectionpolicy.GetAutoProtectionPolicyRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" } request = request_type(**request_init) @@ -27985,38 +52506,35 @@ def test_get_data_source_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_data_source(request) + client.get_auto_protection_policy(request) @pytest.mark.parametrize( "request_type", [ - backupvault.GetDataSourceRequest, + autoprotectionpolicy.GetAutoProtectionPolicyRequest, dict, ], ) -def test_get_data_source_rest_call_success(request_type): +def test_get_auto_protection_policy_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/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 = backupvault.DataSource( + return_value = autoprotectionpolicy.AutoProtectionPolicy( name="name_value", - state=backupvault.DataSource.State.CREATING, - backup_count=1278, + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, etag="etag_value", - total_stored_bytes=1946, - config_state=backupvault.BackupConfigState.ACTIVE, - backup_blocked_by_vault_access_restriction=True, ) # Wrap the value into a proper Response obj @@ -28024,26 +52542,23 @@ def test_get_data_source_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupvault.DataSource.pb(return_value) + return_value = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_data_source(request) + response = client.get_auto_protection_policy(request) # Establish that the response is the type that we expect. - assert isinstance(response, backupvault.DataSource) + assert isinstance(response, autoprotectionpolicy.AutoProtectionPolicy) assert response.name == "name_value" - assert response.state == backupvault.DataSource.State.CREATING - assert response.backup_count == 1278 + assert response.description == "description_value" + assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING assert response.etag == "etag_value" - assert response.total_stored_bytes == 1946 - assert response.config_state == backupvault.BackupConfigState.ACTIVE - assert response.backup_blocked_by_vault_access_restriction is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_data_source_rest_interceptors(null_interceptor): +def test_get_auto_protection_policy_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -28054,20 +52569,21 @@ def test_get_data_source_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.BackupDRRestInterceptor, "post_get_data_source" + transports.BackupDRRestInterceptor, "post_get_auto_protection_policy" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_get_data_source_with_metadata" + transports.BackupDRRestInterceptor, + "post_get_auto_protection_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_get_data_source" + transports.BackupDRRestInterceptor, "pre_get_auto_protection_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.GetDataSourceRequest.pb( - backupvault.GetDataSourceRequest() + pb_message = autoprotectionpolicy.GetAutoProtectionPolicyRequest.pb( + autoprotectionpolicy.GetAutoProtectionPolicyRequest() ) transcode.return_value = { "method": "post", @@ -28079,19 +52595,24 @@ def test_get_data_source_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 = backupvault.DataSource.to_json(backupvault.DataSource()) + return_value = autoprotectionpolicy.AutoProtectionPolicy.to_json( + autoprotectionpolicy.AutoProtectionPolicy() + ) req.return_value.content = return_value - request = backupvault.GetDataSourceRequest() + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupvault.DataSource() - post_with_metadata.return_value = backupvault.DataSource(), metadata + post.return_value = autoprotectionpolicy.AutoProtectionPolicy() + post_with_metadata.return_value = ( + autoprotectionpolicy.AutoProtectionPolicy(), + metadata, + ) - client.get_data_source( + client.get_auto_protection_policy( request, metadata=[ ("key", "val"), @@ -28104,16 +52625,16 @@ def test_get_data_source_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_data_source_rest_bad_request( - request_type=backupvault.UpdateDataSourceRequest, +def test_update_auto_protection_policy_rest_bad_request( + request_type=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "data_source": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + "auto_protection_policy": { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" } } request = request_type(**request_init) @@ -28131,113 +52652,62 @@ def test_update_data_source_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_data_source(request) + client.update_auto_protection_policy(request) @pytest.mark.parametrize( "request_type", [ - backupvault.UpdateDataSourceRequest, + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, dict, ], ) -def test_update_data_source_rest_call_success(request_type): +def test_update_auto_protection_policy_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "data_source": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + "auto_protection_policy": { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" } } - request_init["data_source"] = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4", - "state": 1, - "labels": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "backup_count": 1278, - "etag": "etag_value", - "total_stored_bytes": 1946, - "config_state": 1, - "backup_config_info": { - "last_backup_state": 1, - "last_successful_backup_consistency_time": {}, - "last_backup_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", + request_init["auto_protection_policy"] = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3", + "description": "description_value", + "backup_plan_details": [ + {"resource_type": "resource_type_value", "backup_plan": "backup_plan_value"} + ], + "criteria": { + "matching_conditions": [ + { + "label_condition": { + "key": "key_value", + "values": ["values_value1", "values_value2"], } - ], - }, - "gcp_backup_config": { - "backup_plan": "backup_plan_value", - "backup_plan_description": "backup_plan_description_value", - "backup_plan_association": "backup_plan_association_value", - "backup_plan_rules": [ - "backup_plan_rules_value1", - "backup_plan_rules_value2", - ], - "backup_plan_revision_name": "backup_plan_revision_name_value", - "backup_plan_revision_id": "backup_plan_revision_id_value", - }, - "backup_appliance_backup_config": { - "backup_appliance_name": "backup_appliance_name_value", - "backup_appliance_id": 1966, - "sla_id": 620, - "application_name": "application_name_value", - "host_name": "host_name_value", - "slt_name": "slt_name_value", - "slp_name": "slp_name_value", - }, - }, - "data_source_gcp_resource": { - "gcp_resourcename": "gcp_resourcename_value", - "location": "location_value", - "type_": "type__value", - "compute_instance_datasource_properties": { - "name": "name_value", - "description": "description_value", - "machine_type": "machine_type_value", - "total_disk_count": 1718, - "total_disk_size_gb": 1904, - }, - "cloud_sql_instance_datasource_properties": { - "name": "name_value", - "database_installed_version": "database_installed_version_value", - "instance_create_time": {}, - "instance_tier": "instance_tier_value", - }, - "alloy_db_cluster_datasource_properties": {"name": "name_value"}, - "disk_datasource_properties": { - "name": "name_value", - "description": "description_value", - "type_": "type__value", - "size_gb": 739, - }, + } + ] }, - "data_source_backup_appliance_application": { - "application_name": "application_name_value", - "backup_appliance": "backup_appliance_value", - "appliance_id": 1241, - "type_": "type__value", - "application_id": 1472, - "hostname": "hostname_value", - "host_id": 746, + "state": 1, + "etag": "etag_value", + "binding_summary": {"project_count": 1407}, + "policy_evaluation_summary": { + "matching_resource_count": 2458, + "protected_resource_count": 2585, + "failed_resource_count": 2228, }, - "backup_blocked_by_vault_access_restriction": True, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, } # 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 = backupvault.UpdateDataSourceRequest.meta.fields["data_source"] + test_field = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest.meta.fields[ + "auto_protection_policy" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -28265,7 +52735,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["data_source"].items(): # pragma: NO COVER + for field, value in request_init[ + "auto_protection_policy" + ].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -28295,10 +52767,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["data_source"][field])): - del request_init["data_source"][field][i][subfield] + for i in range(0, len(request_init["auto_protection_policy"][field])): + del request_init["auto_protection_policy"][field][i][subfield] else: - del request_init["data_source"][field][subfield] + del request_init["auto_protection_policy"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -28313,14 +52785,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_data_source(request) + response = client.update_auto_protection_policy(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_data_source_rest_interceptors(null_interceptor): +def test_update_auto_protection_policy_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -28332,20 +52804,21 @@ def test_update_data_source_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.BackupDRRestInterceptor, "post_update_data_source" + transports.BackupDRRestInterceptor, "post_update_auto_protection_policy" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_update_data_source_with_metadata" + transports.BackupDRRestInterceptor, + "post_update_auto_protection_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_update_data_source" + transports.BackupDRRestInterceptor, "pre_update_auto_protection_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.UpdateDataSourceRequest.pb( - backupvault.UpdateDataSourceRequest() + pb_message = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest.pb( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() ) transcode.return_value = { "method": "post", @@ -28360,7 +52833,7 @@ def test_update_data_source_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupvault.UpdateDataSourceRequest() + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -28369,7 +52842,7 @@ def test_update_data_source_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_data_source( + client.update_auto_protection_policy( request, metadata=[ ("key", "val"), @@ -28382,13 +52855,15 @@ def test_update_data_source_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_backups_rest_bad_request(request_type=backupvault.ListBackupsRequest): +def test_delete_auto_protection_policy_rest_bad_request( + request_type=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" } request = request_type(**request_init) @@ -28405,55 +52880,47 @@ def test_list_backups_rest_bad_request(request_type=backupvault.ListBackupsReque 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) + client.delete_auto_protection_policy(request) @pytest.mark.parametrize( "request_type", [ - backupvault.ListBackupsRequest, + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, dict, ], ) -def test_list_backups_rest_call_success(request_type): +def test_delete_auto_protection_policy_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/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 = backupvault.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_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 = backupvault.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) + response = client.delete_auto_protection_policy(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"] + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_backups_rest_interceptors(null_interceptor): +def test_delete_auto_protection_policy_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -28463,20 +52930,24 @@ def test_list_backups_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.BackupDRRestInterceptor, "post_list_backups" + transports.BackupDRRestInterceptor, "post_delete_auto_protection_policy" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_list_backups_with_metadata" + transports.BackupDRRestInterceptor, + "post_delete_auto_protection_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_list_backups" + transports.BackupDRRestInterceptor, "pre_delete_auto_protection_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.ListBackupsRequest.pb(backupvault.ListBackupsRequest()) + pb_message = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest.pb( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -28487,21 +52958,19 @@ def test_list_backups_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 = backupvault.ListBackupsResponse.to_json( - backupvault.ListBackupsResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupvault.ListBackupsRequest() + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupvault.ListBackupsResponse() - post_with_metadata.return_value = backupvault.ListBackupsResponse(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.list_backups( + client.delete_auto_protection_policy( request, metadata=[ ("key", "val"), @@ -28514,15 +52983,15 @@ def test_list_backups_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_backups_for_resource_type_rest_bad_request( - request_type=backupvault.FetchBackupsForResourceTypeRequest, +def test_create_auto_protection_policy_binding_rest_bad_request( + request_type=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" } request = request_type(**request_init) @@ -28539,53 +53008,136 @@ def test_fetch_backups_for_resource_type_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.fetch_backups_for_resource_type(request) + client.create_auto_protection_policy_binding(request) @pytest.mark.parametrize( "request_type", [ - backupvault.FetchBackupsForResourceTypeRequest, + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, dict, ], ) -def test_fetch_backups_for_resource_type_rest_call_success(request_type): +def test_create_auto_protection_policy_binding_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + request_init["auto_protection_policy_binding"] = { + "name": "name_value", + "description": "description_value", + "state": 1, + "scope": "scope_value", + "binding_evaluation_summary": { + "matching_resource_count": 2458, + "protected_resource_count": 2585, + "failed_resource_count": 2228, + }, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "etag": "etag_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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest.meta.fields[ + "auto_protection_policy_binding" + ] + + 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[ + "auto_protection_policy_binding" + ].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["auto_protection_policy_binding"][field]) + ): + del request_init["auto_protection_policy_binding"][field][i][ + subfield + ] + else: + del request_init["auto_protection_policy_binding"][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 = backupvault.FetchBackupsForResourceTypeResponse( - next_page_token="next_page_token_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 = backupvault.FetchBackupsForResourceTypeResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.fetch_backups_for_resource_type(request) + response = client.create_auto_protection_policy_binding(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchBackupsForResourceTypePager) - assert response.next_page_token == "next_page_token_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_backups_for_resource_type_rest_interceptors(null_interceptor): +def test_create_auto_protection_policy_binding_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -28595,22 +53147,27 @@ def test_fetch_backups_for_resource_type_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.BackupDRRestInterceptor, "post_fetch_backups_for_resource_type" + transports.BackupDRRestInterceptor, + "post_create_auto_protection_policy_binding", ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_fetch_backups_for_resource_type_with_metadata", + "post_create_auto_protection_policy_binding_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_fetch_backups_for_resource_type" + transports.BackupDRRestInterceptor, + "pre_create_auto_protection_policy_binding", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.FetchBackupsForResourceTypeRequest.pb( - backupvault.FetchBackupsForResourceTypeRequest() + pb_message = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest.pb( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) ) transcode.return_value = { "method": "post", @@ -28622,24 +53179,19 @@ def test_fetch_backups_for_resource_type_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 = backupvault.FetchBackupsForResourceTypeResponse.to_json( - backupvault.FetchBackupsForResourceTypeResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupvault.FetchBackupsForResourceTypeRequest() + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupvault.FetchBackupsForResourceTypeResponse() - post_with_metadata.return_value = ( - backupvault.FetchBackupsForResourceTypeResponse(), - metadata, - ) + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.fetch_backups_for_resource_type( + client.create_auto_protection_policy_binding( request, metadata=[ ("key", "val"), @@ -28652,13 +53204,15 @@ def test_fetch_backups_for_resource_type_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_backup_rest_bad_request(request_type=backupvault.GetBackupRequest): +def test_get_auto_protection_policy_binding_rest_bad_request( + request_type=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" } request = request_type(**request_init) @@ -28675,41 +53229,36 @@ def test_get_backup_rest_bad_request(request_type=backupvault.GetBackupRequest): 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) + client.get_auto_protection_policy_binding(request) @pytest.mark.parametrize( "request_type", [ - backupvault.GetBackupRequest, + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, dict, ], ) -def test_get_backup_rest_call_success(request_type): +def test_get_auto_protection_policy_binding_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/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 = backupvault.Backup( + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding( name="name_value", description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", etag="etag_value", - state=backupvault.Backup.State.CREATING, - backup_type=backupvault.Backup.BackupType.SCHEDULED, - resource_size_bytes=2056, - satisfies_pzs=True, - satisfies_pzi=True, - kms_key_versions=["kms_key_versions_value"], ) # Wrap the value into a proper Response obj @@ -28717,32 +53266,29 @@ def test_get_backup_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupvault.Backup.pb(return_value) + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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) + response = client.get_auto_protection_policy_binding(request) # Establish that the response is the type that we expect. - assert isinstance(response, backupvault.Backup) + assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) assert response.name == "name_value" assert response.description == "description_value" assert ( - response.backup_retention_inheritance - == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + response.state + == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING ) + assert response.scope == "scope_value" assert response.etag == "etag_value" - assert response.state == backupvault.Backup.State.CREATING - assert response.backup_type == backupvault.Backup.BackupType.SCHEDULED - assert response.resource_size_bytes == 2056 - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - assert response.kms_key_versions == ["kms_key_versions_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_rest_interceptors(null_interceptor): +def test_get_auto_protection_policy_binding_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -28753,17 +53299,25 @@ def test_get_backup_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.BackupDRRestInterceptor, "post_get_backup" + transports.BackupDRRestInterceptor, + "post_get_auto_protection_policy_binding", ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_get_backup_with_metadata" + transports.BackupDRRestInterceptor, + "post_get_auto_protection_policy_binding_with_metadata", ) as post_with_metadata, - mock.patch.object(transports.BackupDRRestInterceptor, "pre_get_backup") as pre, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_auto_protection_policy_binding" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.GetBackupRequest.pb(backupvault.GetBackupRequest()) + pb_message = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest.pb( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -28774,19 +53328,24 @@ def test_get_backup_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 = backupvault.Backup.to_json(backupvault.Backup()) + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding.to_json( + autoprotectionpolicybinding.AutoProtectionPolicyBinding() + ) req.return_value.content = return_value - request = backupvault.GetBackupRequest() + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupvault.Backup() - post_with_metadata.return_value = backupvault.Backup(), metadata + post.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + post_with_metadata.return_value = ( + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + metadata, + ) - client.get_backup( + client.get_auto_protection_policy_binding( request, metadata=[ ("key", "val"), @@ -28799,15 +53358,15 @@ def test_get_backup_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_backup_rest_bad_request(request_type=backupvault.UpdateBackupRequest): +def test_list_auto_protection_policy_bindings_rest_bad_request( + request_type=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "backup": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" - } + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" } request = request_type(**request_init) @@ -28824,294 +53383,209 @@ def test_update_backup_rest_bad_request(request_type=backupvault.UpdateBackupReq response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_backup(request) + client.list_auto_protection_policy_bindings(request) @pytest.mark.parametrize( "request_type", [ - backupvault.UpdateBackupRequest, + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, dict, ], ) -def test_update_backup_rest_call_success(request_type): +def test_list_auto_protection_policy_bindings_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = { - "backup": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" - } - } - request_init["backup"] = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5", - "description": "description_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "enforced_retention_end_time": {}, - "backup_retention_inheritance": 1, - "expire_time": {}, - "consistency_time": {}, - "etag": "etag_value", - "state": 1, - "service_locks": [ - { - "lock_until_time": {}, - "backup_appliance_lock_info": { - "backup_appliance_id": 1966, - "backup_appliance_name": "backup_appliance_name_value", - "lock_reason": "lock_reason_value", - "job_name": "job_name_value", - "backup_image": "backup_image_value", - "sla_id": 620, - }, - "service_lock_info": {"operation": "operation_value"}, - } - ], - "backup_appliance_locks": {}, - "compute_instance_backup_properties": { - "description": "description_value", - "tags": {"items": ["items_value1", "items_value2"]}, - "machine_type": "machine_type_value", - "can_ip_forward": True, - "network_interface": [ - { - "network": "network_value", - "subnetwork": "subnetwork_value", - "ip_address": "ip_address_value", - "ipv6_address": "ipv6_address_value", - "internal_ipv6_prefix_length": 2831, - "name": "name_value", - "access_configs": [ - { - "type_": 1, - "name": "name_value", - "external_ip": "external_ip_value", - "external_ipv6": "external_ipv6_value", - "external_ipv6_prefix_length": 2837, - "set_public_ptr": True, - "public_ptr_domain_name": "public_ptr_domain_name_value", - "network_tier": 1, - } - ], - "ipv6_access_configs": {}, - "alias_ip_ranges": [ - { - "ip_cidr_range": "ip_cidr_range_value", - "subnetwork_range_name": "subnetwork_range_name_value", - } - ], - "stack_type": 1, - "ipv6_access_type": 1, - "queue_count": 1197, - "nic_type": 1, - "network_attachment": "network_attachment_value", - } - ], - "disk": [ - { - "initialize_params": { - "disk_name": "disk_name_value", - "replica_zones": [ - "replica_zones_value1", - "replica_zones_value2", - ], - }, - "device_name": "device_name_value", - "kind": "kind_value", - "disk_type_deprecated": 1, - "mode": 1, - "source": "source_value", - "index": 536, - "boot": True, - "auto_delete": True, - "license_": ["license__value1", "license__value2"], - "disk_interface": 1, - "guest_os_feature": [{"type_": 1}], - "disk_encryption_key": { - "raw_key": "raw_key_value", - "rsa_encrypted_key": "rsa_encrypted_key_value", - "kms_key_name": "kms_key_name_value", - "kms_key_service_account": "kms_key_service_account_value", - }, - "disk_size_gb": 1261, - "saved_state": 1, - "disk_type": "disk_type_value", - "type_": 1, - } - ], - "metadata": {"items": [{"key": "key_value", "value": "value_value"}]}, - "service_account": [ - {"email": "email_value", "scopes": ["scopes_value1", "scopes_value2"]} - ], - "scheduling": { - "on_host_maintenance": 1, - "automatic_restart": True, - "preemptible": True, - "node_affinities": [ - { - "key": "key_value", - "operator": 1, - "values": ["values_value1", "values_value2"], - } - ], - "min_node_cpus": 1379, - "provisioning_model": 1, - "instance_termination_action": 1, - "local_ssd_recovery_timeout": {"seconds": 751, "nanos": 543}, - }, - "guest_accelerator": [ - { - "accelerator_type": "accelerator_type_value", - "accelerator_count": 1805, - } - ], - "min_cpu_platform": "min_cpu_platform_value", - "key_revocation_action_type": 1, - "source_instance": "source_instance_value", - "labels": {}, - }, - "cloud_sql_instance_backup_properties": { - "database_installed_version": "database_installed_version_value", - "final_backup": True, - "source_instance": "source_instance_value", - "instance_create_time": {}, - "instance_tier": "instance_tier_value", - "instance_delete_time": {}, - }, - "backup_appliance_backup_properties": { - "generation_id": 1368, - "finalize_time": {}, - "recovery_range_start_time": {}, - "recovery_range_end_time": {}, - }, - "alloy_db_backup_properties": { - "description": "description_value", - "stored_bytes": 1303, - "chain_id": "chain_id_value", - "database_version": "database_version_value", - }, - "disk_backup_properties": { - "description": "description_value", - "licenses": ["licenses_value1", "licenses_value2"], - "guest_os_feature": {}, - "architecture": 1, - "type_": "type__value", - "size_gb": 739, - "region": "region_value", - "zone": "zone_value", - "replica_zones": ["replica_zones_value1", "replica_zones_value2"], - "source_disk": "source_disk_value", - }, - "backup_type": 1, - "gcp_backup_plan_info": { - "backup_plan": "backup_plan_value", - "backup_plan_rule_id": "backup_plan_rule_id_value", - "backup_plan_revision_name": "backup_plan_revision_name_value", - "backup_plan_revision_id": "backup_plan_revision_id_value", - }, - "resource_size_bytes": 2056, - "satisfies_pzs": True, - "satisfies_pzi": True, - "gcp_resource": { - "gcp_resourcename": "gcp_resourcename_value", - "location": "location_value", - "type_": "type__value", - }, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" } - # 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 = backupvault.UpdateBackupRequest.meta.fields["backup"] + # 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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) - 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 - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Convert return value to protobuf type + return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_auto_protection_policy_bindings(request) - 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 + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_auto_protection_policy_bindings_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) - # 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["backup"].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 + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_auto_protection_policy_bindings", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_auto_protection_policy_bindings_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_list_auto_protection_policy_bindings", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest.pb( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - 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, - } - ) + 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.to_json( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + req.return_value.content = return_value - # 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["backup"][field])): - del request_init["backup"][field][i][subfield] - else: - del request_init["backup"][field][subfield] + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + post_with_metadata.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse(), + metadata, + ) + + client.list_auto_protection_policy_bindings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_applied_auto_protection_policies_rest_bad_request( + request_type=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, +): + client = BackupDRClient( + 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_applied_auto_protection_policies(request) + + +@pytest.mark.parametrize( + "request_type", + [ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, + dict, + ], +) +def test_list_applied_auto_protection_policies_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_backup(request) + response = client.list_applied_auto_protection_policies(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.ListAppliedAutoProtectionPoliciesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_backup_rest_interceptors(null_interceptor): +def test_list_applied_auto_protection_policies_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -29121,22 +53595,26 @@ def test_update_backup_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.BackupDRRestInterceptor, "post_update_backup" + transports.BackupDRRestInterceptor, + "post_list_applied_auto_protection_policies", ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_update_backup_with_metadata" + transports.BackupDRRestInterceptor, + "post_list_applied_auto_protection_policies_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_update_backup" + transports.BackupDRRestInterceptor, + "pre_list_applied_auto_protection_policies", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.UpdateBackupRequest.pb( - backupvault.UpdateBackupRequest() + pb_message = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest.pb( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + ) ) transcode.return_value = { "method": "post", @@ -29148,19 +53626,26 @@ def test_update_backup_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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.to_json( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) req.return_value.content = return_value - request = backupvault.UpdateBackupRequest() + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + post_with_metadata.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse(), + metadata, + ) - client.update_backup( + client.list_applied_auto_protection_policies( request, metadata=[ ("key", "val"), @@ -29173,13 +53658,15 @@ def test_update_backup_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_backup_rest_bad_request(request_type=backupvault.DeleteBackupRequest): +def test_initiate_delete_auto_protection_policy_binding_rest_bad_request( + request_type=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" } request = request_type(**request_init) @@ -29196,24 +53683,24 @@ def test_delete_backup_rest_bad_request(request_type=backupvault.DeleteBackupReq 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) + client.initiate_delete_auto_protection_policy_binding(request) @pytest.mark.parametrize( "request_type", [ - backupvault.DeleteBackupRequest, + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, dict, ], ) -def test_delete_backup_rest_call_success(request_type): +def test_initiate_delete_auto_protection_policy_binding_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" } request = request_type(**request_init) @@ -29229,14 +53716,16 @@ def test_delete_backup_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_backup(request) + response = client.initiate_delete_auto_protection_policy_binding(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): +def test_initiate_delete_auto_protection_policy_binding_rest_interceptors( + null_interceptor, +): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -29248,20 +53737,23 @@ def test_delete_backup_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.BackupDRRestInterceptor, "post_delete_backup" + transports.BackupDRRestInterceptor, + "post_initiate_delete_auto_protection_policy_binding", ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_delete_backup_with_metadata" + transports.BackupDRRestInterceptor, + "post_initiate_delete_auto_protection_policy_binding_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_delete_backup" + transports.BackupDRRestInterceptor, + "pre_initiate_delete_auto_protection_policy_binding", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.DeleteBackupRequest.pb( - backupvault.DeleteBackupRequest() + pb_message = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest.pb( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() ) transcode.return_value = { "method": "post", @@ -29276,7 +53768,7 @@ def test_delete_backup_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupvault.DeleteBackupRequest() + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -29285,7 +53777,7 @@ def test_delete_backup_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_backup( + client.initiate_delete_auto_protection_policy_binding( request, metadata=[ ("key", "val"), @@ -29298,13 +53790,15 @@ def test_delete_backup_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_restore_backup_rest_bad_request(request_type=backupvault.RestoreBackupRequest): +def test_list_binding_matching_resources_rest_bad_request( + request_type=bindingmatchingresource.ListBindingMatchingResourcesRequest, +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" } request = request_type(**request_init) @@ -29321,47 +53815,55 @@ def test_restore_backup_rest_bad_request(request_type=backupvault.RestoreBackupR response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.restore_backup(request) + client.list_binding_matching_resources(request) @pytest.mark.parametrize( "request_type", [ - backupvault.RestoreBackupRequest, + bindingmatchingresource.ListBindingMatchingResourcesRequest, dict, ], ) -def test_restore_backup_rest_call_success(request_type): +def test_list_binding_matching_resources_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/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 = bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_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 = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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.restore_backup(request) + response = client.list_binding_matching_resources(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.ListBindingMatchingResourcesPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restore_backup_rest_interceptors(null_interceptor): +def test_list_binding_matching_resources_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -29371,22 +53873,22 @@ def test_restore_backup_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.BackupDRRestInterceptor, "post_restore_backup" + transports.BackupDRRestInterceptor, "post_list_binding_matching_resources" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_restore_backup_with_metadata" + transports.BackupDRRestInterceptor, + "post_list_binding_matching_resources_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_restore_backup" + transports.BackupDRRestInterceptor, "pre_list_binding_matching_resources" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupvault.RestoreBackupRequest.pb( - backupvault.RestoreBackupRequest() + pb_message = bindingmatchingresource.ListBindingMatchingResourcesRequest.pb( + bindingmatchingresource.ListBindingMatchingResourcesRequest() ) transcode.return_value = { "method": "post", @@ -29398,19 +53900,28 @@ def test_restore_backup_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 = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse.to_json( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + ) req.return_value.content = return_value - request = backupvault.RestoreBackupRequest() + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() 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 = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + post_with_metadata.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse(), + metadata, + ) - client.restore_backup( + client.list_binding_matching_resources( request, metadata=[ ("key", "val"), @@ -29423,8 +53934,8 @@ def test_restore_backup_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_backup_plan_rest_bad_request( - request_type=backupplan.CreateBackupPlanRequest, +def test_create_restore_template_rest_bad_request( + request_type=gcb_restore_template.CreateRestoreTemplateRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -29446,67 +53957,53 @@ def test_create_backup_plan_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_backup_plan(request) + client.create_restore_template(request) @pytest.mark.parametrize( "request_type", [ - backupplan.CreateBackupPlanRequest, + gcb_restore_template.CreateRestoreTemplateRequest, dict, ], ) -def test_create_backup_plan_rest_call_success(request_type): +def test_create_restore_template_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["backup_plan"] = { + request_init["restore_template"] = { "name": "name_value", "description": "description_value", - "labels": {}, "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, - "backup_rules": [ - { - "rule_id": "rule_id_value", - "backup_retention_days": 2237, - "standard_schedule": { - "recurrence_type": 1, - "hourly_frequency": 1748, - "days_of_week": [1], - "days_of_month": [1387, 1388], - "week_day_of_month": {"week_of_month": 1, "day_of_week": 1}, - "months": [1], - "backup_window": { - "start_hour_of_day": 1820, - "end_hour_of_day": 1573, - }, - "time_zone": "time_zone_value", - }, - } - ], - "state": 1, "resource_type": "resource_type_value", + "labels": {}, + "backup_selection_config": {"data_source": "data_source_value"}, + "pre_restore_config": { + "timeout": {"seconds": 751, "nanos": 543}, + "cloud_run_job": "cloud_run_job_value", + }, + "post_restore_config": {"timeout": {}, "cloud_run_job": "cloud_run_job_value"}, + "verification_config": {"timeout": {}, "cloud_run_job": "cloud_run_job_value"}, + "restore_properties": {"fields": {}}, + "state": 1, + "execution_summary": { + "last_execution": "last_execution_value", + "last_execution_state": 1, + }, "etag": "etag_value", - "backup_vault": "backup_vault_value", - "backup_vault_service_account": "backup_vault_service_account_value", - "log_retention_days": 1929, - "supported_resource_types": [ - "supported_resource_types_value1", - "supported_resource_types_value2", - ], - "revision_id": "revision_id_value", - "revision_name": "revision_name_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 = backupplan.CreateBackupPlanRequest.meta.fields["backup_plan"] + test_field = gcb_restore_template.CreateRestoreTemplateRequest.meta.fields[ + "restore_template" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -29534,7 +54031,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["backup_plan"].items(): # pragma: NO COVER + for field, value in request_init["restore_template"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -29564,10 +54061,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["backup_plan"][field])): - del request_init["backup_plan"][field][i][subfield] + for i in range(0, len(request_init["restore_template"][field])): + del request_init["restore_template"][field][i][subfield] else: - del request_init["backup_plan"][field][subfield] + del request_init["restore_template"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -29582,14 +54079,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_backup_plan(request) + response = client.create_restore_template(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_backup_plan_rest_interceptors(null_interceptor): +def test_create_restore_template_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -29601,20 +54098,21 @@ def test_create_backup_plan_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.BackupDRRestInterceptor, "post_create_backup_plan" + transports.BackupDRRestInterceptor, "post_create_restore_template" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_create_backup_plan_with_metadata" + transports.BackupDRRestInterceptor, + "post_create_restore_template_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_create_backup_plan" + transports.BackupDRRestInterceptor, "pre_create_restore_template" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplan.CreateBackupPlanRequest.pb( - backupplan.CreateBackupPlanRequest() + pb_message = gcb_restore_template.CreateRestoreTemplateRequest.pb( + gcb_restore_template.CreateRestoreTemplateRequest() ) transcode.return_value = { "method": "post", @@ -29629,7 +54127,7 @@ def test_create_backup_plan_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupplan.CreateBackupPlanRequest() + request = gcb_restore_template.CreateRestoreTemplateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -29638,7 +54136,7 @@ def test_create_backup_plan_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_backup_plan( + client.create_restore_template( request, metadata=[ ("key", "val"), @@ -29651,17 +54149,15 @@ def test_create_backup_plan_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_backup_plan_rest_bad_request( - request_type=backupplan.UpdateBackupPlanRequest, +def test_get_restore_template_rest_bad_request( + request_type=restore_template.GetRestoreTemplateRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "backup_plan": { - "name": "projects/sample1/locations/sample2/backupPlans/sample3" - } + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" } request = request_type(**request_init) @@ -29678,154 +54174,194 @@ def test_update_backup_plan_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_backup_plan(request) + client.get_restore_template(request) @pytest.mark.parametrize( "request_type", [ - backupplan.UpdateBackupPlanRequest, + restore_template.GetRestoreTemplateRequest, dict, ], ) -def test_update_backup_plan_rest_call_success(request_type): +def test_get_restore_template_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "backup_plan": { - "name": "projects/sample1/locations/sample2/backupPlans/sample3" - } - } - request_init["backup_plan"] = { - "name": "projects/sample1/locations/sample2/backupPlans/sample3", - "description": "description_value", - "labels": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "backup_rules": [ - { - "rule_id": "rule_id_value", - "backup_retention_days": 2237, - "standard_schedule": { - "recurrence_type": 1, - "hourly_frequency": 1748, - "days_of_week": [1], - "days_of_month": [1387, 1388], - "week_day_of_month": {"week_of_month": 1, "day_of_week": 1}, - "months": [1], - "backup_window": { - "start_hour_of_day": 1820, - "end_hour_of_day": 1573, - }, - "time_zone": "time_zone_value", - }, - } - ], - "state": 1, - "resource_type": "resource_type_value", - "etag": "etag_value", - "backup_vault": "backup_vault_value", - "backup_vault_service_account": "backup_vault_service_account_value", - "log_retention_days": 1929, - "supported_resource_types": [ - "supported_resource_types_value1", - "supported_resource_types_value2", - ], - "revision_id": "revision_id_value", - "revision_name": "revision_name_value", + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" } - # 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 = backupplan.UpdateBackupPlanRequest.meta.fields["backup_plan"] + # 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 = restore_template.RestoreTemplate( + name="name_value", + description="description_value", + resource_type="resource_type_value", + state=restore_template.RestoreTemplate.State.CREATING, + etag="etag_value", + ) - 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 - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Convert return value to protobuf type + return_value = restore_template.RestoreTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_restore_template(request) - 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 + # Establish that the response is the type that we expect. + assert isinstance(response, restore_template.RestoreTemplate) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.resource_type == "resource_type_value" + assert response.state == restore_template.RestoreTemplate.State.CREATING + assert response.etag == "etag_value" - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_restore_template_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(transport=transport) - # 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["backup_plan"].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 + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, "post_get_restore_template" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_restore_template_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_restore_template" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_template.GetRestoreTemplateRequest.pb( + restore_template.GetRestoreTemplateRequest() + ) + 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 = restore_template.RestoreTemplate.to_json( + restore_template.RestoreTemplate() + ) + req.return_value.content = return_value + + request = restore_template.GetRestoreTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = restore_template.RestoreTemplate() + post_with_metadata.return_value = restore_template.RestoreTemplate(), metadata + + client.get_restore_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_restore_templates_rest_bad_request( + request_type=restore_template.ListRestoreTemplatesRequest, +): + client = BackupDRClient( + 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_restore_templates(request) - 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["backup_plan"][field])): - del request_init["backup_plan"][field][i][subfield] - else: - del request_init["backup_plan"][field][subfield] +@pytest.mark.parametrize( + "request_type", + [ + restore_template.ListRestoreTemplatesRequest, + dict, + ], +) +def test_list_restore_templates_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = restore_template.ListRestoreTemplatesResponse( + 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 = restore_template.ListRestoreTemplatesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_backup_plan(request) + response = client.list_restore_templates(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.ListRestoreTemplatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_backup_plan_rest_interceptors(null_interceptor): +def test_list_restore_templates_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -29835,22 +54371,22 @@ def test_update_backup_plan_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.BackupDRRestInterceptor, "post_update_backup_plan" + transports.BackupDRRestInterceptor, "post_list_restore_templates" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_update_backup_plan_with_metadata" + transports.BackupDRRestInterceptor, + "post_list_restore_templates_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_update_backup_plan" + transports.BackupDRRestInterceptor, "pre_list_restore_templates" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplan.UpdateBackupPlanRequest.pb( - backupplan.UpdateBackupPlanRequest() + pb_message = restore_template.ListRestoreTemplatesRequest.pb( + restore_template.ListRestoreTemplatesRequest() ) transcode.return_value = { "method": "post", @@ -29862,19 +54398,24 @@ def test_update_backup_plan_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 = restore_template.ListRestoreTemplatesResponse.to_json( + restore_template.ListRestoreTemplatesResponse() + ) req.return_value.content = return_value - request = backupplan.UpdateBackupPlanRequest() + request = restore_template.ListRestoreTemplatesRequest() 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 = restore_template.ListRestoreTemplatesResponse() + post_with_metadata.return_value = ( + restore_template.ListRestoreTemplatesResponse(), + metadata, + ) - client.update_backup_plan( + client.list_restore_templates( request, metadata=[ ("key", "val"), @@ -29887,12 +54428,18 @@ def test_update_backup_plan_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_backup_plan_rest_bad_request(request_type=backupplan.GetBackupPlanRequest): +def test_update_restore_template_rest_bad_request( + request_type=gcb_restore_template.UpdateRestoreTemplateRequest, +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backupPlans/sample3"} + request_init = { + "restore_template": { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" + } + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -29908,71 +54455,140 @@ def test_get_backup_plan_rest_bad_request(request_type=backupplan.GetBackupPlanR 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_plan(request) + client.update_restore_template(request) @pytest.mark.parametrize( "request_type", [ - backupplan.GetBackupPlanRequest, + gcb_restore_template.UpdateRestoreTemplateRequest, dict, ], ) -def test_get_backup_plan_rest_call_success(request_type): +def test_update_restore_template_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backupPlans/sample3"} + request_init = { + "restore_template": { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" + } + } + request_init["restore_template"] = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "resource_type": "resource_type_value", + "labels": {}, + "backup_selection_config": {"data_source": "data_source_value"}, + "pre_restore_config": { + "timeout": {"seconds": 751, "nanos": 543}, + "cloud_run_job": "cloud_run_job_value", + }, + "post_restore_config": {"timeout": {}, "cloud_run_job": "cloud_run_job_value"}, + "verification_config": {"timeout": {}, "cloud_run_job": "cloud_run_job_value"}, + "restore_properties": {"fields": {}}, + "state": 1, + "execution_summary": { + "last_execution": "last_execution_value", + "last_execution_state": 1, + }, + "etag": "etag_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 = gcb_restore_template.UpdateRestoreTemplateRequest.meta.fields[ + "restore_template" + ] + + 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["restore_template"].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["restore_template"][field])): + del request_init["restore_template"][field][i][subfield] + else: + del request_init["restore_template"][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 = backupplan.BackupPlan( - name="name_value", - description="description_value", - state=backupplan.BackupPlan.State.CREATING, - resource_type="resource_type_value", - etag="etag_value", - backup_vault="backup_vault_value", - backup_vault_service_account="backup_vault_service_account_value", - log_retention_days=1929, - supported_resource_types=["supported_resource_types_value"], - revision_id="revision_id_value", - revision_name="revision_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 = backupplan.BackupPlan.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_plan(request) + response = client.update_restore_template(request) # Establish that the response is the type that we expect. - assert isinstance(response, backupplan.BackupPlan) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.state == backupplan.BackupPlan.State.CREATING - assert response.resource_type == "resource_type_value" - assert response.etag == "etag_value" - assert response.backup_vault == "backup_vault_value" - assert response.backup_vault_service_account == "backup_vault_service_account_value" - assert response.log_retention_days == 1929 - assert response.supported_resource_types == ["supported_resource_types_value"] - assert response.revision_id == "revision_id_value" - assert response.revision_name == "revision_name_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_plan_rest_interceptors(null_interceptor): +def test_update_restore_template_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -29982,21 +54598,23 @@ def test_get_backup_plan_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.BackupDRRestInterceptor, "post_get_backup_plan" + transports.BackupDRRestInterceptor, "post_update_restore_template" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_get_backup_plan_with_metadata" + transports.BackupDRRestInterceptor, + "post_update_restore_template_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_get_backup_plan" + transports.BackupDRRestInterceptor, "pre_update_restore_template" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplan.GetBackupPlanRequest.pb( - backupplan.GetBackupPlanRequest() + pb_message = gcb_restore_template.UpdateRestoreTemplateRequest.pb( + gcb_restore_template.UpdateRestoreTemplateRequest() ) transcode.return_value = { "method": "post", @@ -30008,19 +54626,19 @@ def test_get_backup_plan_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 = backupplan.BackupPlan.to_json(backupplan.BackupPlan()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupplan.GetBackupPlanRequest() + request = gcb_restore_template.UpdateRestoreTemplateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupplan.BackupPlan() - post_with_metadata.return_value = backupplan.BackupPlan(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_backup_plan( + client.update_restore_template( request, metadata=[ ("key", "val"), @@ -30033,14 +54651,16 @@ def test_get_backup_plan_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_backup_plans_rest_bad_request( - request_type=backupplan.ListBackupPlansRequest, +def test_delete_restore_template_rest_bad_request( + request_type=restore_template.DeleteRestoreTemplateRequest, ): client = BackupDRClient( 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/restoreTemplates/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -30056,53 +54676,47 @@ def test_list_backup_plans_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_backup_plans(request) + client.delete_restore_template(request) @pytest.mark.parametrize( "request_type", [ - backupplan.ListBackupPlansRequest, + restore_template.DeleteRestoreTemplateRequest, dict, ], ) -def test_list_backup_plans_rest_call_success(request_type): +def test_delete_restore_template_rest_call_success(request_type): client = BackupDRClient( 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/restoreTemplates/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 = backupplan.ListBackupPlansResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_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 = backupplan.ListBackupPlansResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_plans(request) + response = client.delete_restore_template(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupPlansPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_backup_plans_rest_interceptors(null_interceptor): +def test_delete_restore_template_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -30112,21 +54726,23 @@ def test_list_backup_plans_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.BackupDRRestInterceptor, "post_list_backup_plans" + transports.BackupDRRestInterceptor, "post_delete_restore_template" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_list_backup_plans_with_metadata" + transports.BackupDRRestInterceptor, + "post_delete_restore_template_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_list_backup_plans" + transports.BackupDRRestInterceptor, "pre_delete_restore_template" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplan.ListBackupPlansRequest.pb( - backupplan.ListBackupPlansRequest() + pb_message = restore_template.DeleteRestoreTemplateRequest.pb( + restore_template.DeleteRestoreTemplateRequest() ) transcode.return_value = { "method": "post", @@ -30138,21 +54754,19 @@ def test_list_backup_plans_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 = backupplan.ListBackupPlansResponse.to_json( - backupplan.ListBackupPlansResponse() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupplan.ListBackupPlansRequest() + request = restore_template.DeleteRestoreTemplateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupplan.ListBackupPlansResponse() - post_with_metadata.return_value = backupplan.ListBackupPlansResponse(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.list_backup_plans( + client.delete_restore_template( request, metadata=[ ("key", "val"), @@ -30165,14 +54779,16 @@ def test_list_backup_plans_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_backup_plan_rest_bad_request( - request_type=backupplan.DeleteBackupPlanRequest, +def test_run_restore_template_rest_bad_request( + request_type=restore_template.RunRestoreTemplateRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backupPlans/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -30188,23 +54804,25 @@ def test_delete_backup_plan_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_backup_plan(request) + client.run_restore_template(request) @pytest.mark.parametrize( "request_type", [ - backupplan.DeleteBackupPlanRequest, + restore_template.RunRestoreTemplateRequest, dict, ], ) -def test_delete_backup_plan_rest_call_success(request_type): +def test_run_restore_template_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backupPlans/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -30219,14 +54837,14 @@ def test_delete_backup_plan_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_backup_plan(request) + response = client.run_restore_template(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_plan_rest_interceptors(null_interceptor): +def test_run_restore_template_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -30238,20 +54856,21 @@ def test_delete_backup_plan_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.BackupDRRestInterceptor, "post_delete_backup_plan" + transports.BackupDRRestInterceptor, "post_run_restore_template" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_delete_backup_plan_with_metadata" + transports.BackupDRRestInterceptor, + "post_run_restore_template_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_delete_backup_plan" + transports.BackupDRRestInterceptor, "pre_run_restore_template" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplan.DeleteBackupPlanRequest.pb( - backupplan.DeleteBackupPlanRequest() + pb_message = restore_template.RunRestoreTemplateRequest.pb( + restore_template.RunRestoreTemplateRequest() ) transcode.return_value = { "method": "post", @@ -30266,7 +54885,7 @@ def test_delete_backup_plan_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupplan.DeleteBackupPlanRequest() + request = restore_template.RunRestoreTemplateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -30275,7 +54894,7 @@ def test_delete_backup_plan_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_backup_plan( + client.run_restore_template( request, metadata=[ ("key", "val"), @@ -30288,15 +54907,15 @@ def test_delete_backup_plan_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_backup_plan_revision_rest_bad_request( - request_type=backupplan.GetBackupPlanRevisionRequest, +def test_get_restore_template_execution_rest_bad_request( + request_type=restore_template_execution.GetRestoreTemplateExecutionRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/sample4" + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/sample4" } request = request_type(**request_init) @@ -30313,34 +54932,36 @@ def test_get_backup_plan_revision_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_backup_plan_revision(request) + client.get_restore_template_execution(request) @pytest.mark.parametrize( "request_type", [ - backupplan.GetBackupPlanRevisionRequest, + restore_template_execution.GetRestoreTemplateExecutionRequest, dict, ], ) -def test_get_backup_plan_revision_rest_call_success(request_type): +def test_get_restore_template_execution_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/sample4" + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/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 = backupplan.BackupPlanRevision( + return_value = restore_template_execution.RestoreTemplateExecution( name="name_value", - revision_id="revision_id_value", - state=backupplan.BackupPlanRevision.State.CREATING, + resource_type="resource_type_value", + type_=restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED, + phase=restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING, + state=restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING, ) # Wrap the value into a proper Response obj @@ -30348,22 +54969,35 @@ def test_get_backup_plan_revision_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupplan.BackupPlanRevision.pb(return_value) + return_value = restore_template_execution.RestoreTemplateExecution.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_plan_revision(request) + response = client.get_restore_template_execution(request) # Establish that the response is the type that we expect. - assert isinstance(response, backupplan.BackupPlanRevision) + assert isinstance(response, restore_template_execution.RestoreTemplateExecution) assert response.name == "name_value" - assert response.revision_id == "revision_id_value" - assert response.state == backupplan.BackupPlanRevision.State.CREATING + assert response.resource_type == "resource_type_value" + assert ( + response.type_ + == restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED + ) + assert ( + response.phase + == restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING + ) + assert ( + response.state + == restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_plan_revision_rest_interceptors(null_interceptor): +def test_get_restore_template_execution_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -30374,21 +55008,21 @@ def test_get_backup_plan_revision_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.BackupDRRestInterceptor, "post_get_backup_plan_revision" + transports.BackupDRRestInterceptor, "post_get_restore_template_execution" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_get_backup_plan_revision_with_metadata", + "post_get_restore_template_execution_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_get_backup_plan_revision" + transports.BackupDRRestInterceptor, "pre_get_restore_template_execution" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplan.GetBackupPlanRevisionRequest.pb( - backupplan.GetBackupPlanRevisionRequest() + pb_message = restore_template_execution.GetRestoreTemplateExecutionRequest.pb( + restore_template_execution.GetRestoreTemplateExecutionRequest() ) transcode.return_value = { "method": "post", @@ -30400,21 +55034,24 @@ def test_get_backup_plan_revision_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 = backupplan.BackupPlanRevision.to_json( - backupplan.BackupPlanRevision() + return_value = restore_template_execution.RestoreTemplateExecution.to_json( + restore_template_execution.RestoreTemplateExecution() ) req.return_value.content = return_value - request = backupplan.GetBackupPlanRevisionRequest() + request = restore_template_execution.GetRestoreTemplateExecutionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupplan.BackupPlanRevision() - post_with_metadata.return_value = backupplan.BackupPlanRevision(), metadata + post.return_value = restore_template_execution.RestoreTemplateExecution() + post_with_metadata.return_value = ( + restore_template_execution.RestoreTemplateExecution(), + metadata, + ) - client.get_backup_plan_revision( + client.get_restore_template_execution( request, metadata=[ ("key", "val"), @@ -30427,14 +55064,16 @@ def test_get_backup_plan_revision_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_backup_plan_revisions_rest_bad_request( - request_type=backupplan.ListBackupPlanRevisionsRequest, +def test_list_restore_template_executions_rest_bad_request( + request_type=restore_template_execution.ListRestoreTemplateExecutionsRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/backupPlans/sample3"} + request_init = { + "parent": "projects/sample1/locations/sample2/restoreTemplates/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -30450,29 +55089,31 @@ def test_list_backup_plan_revisions_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_backup_plan_revisions(request) + client.list_restore_template_executions(request) @pytest.mark.parametrize( "request_type", [ - backupplan.ListBackupPlanRevisionsRequest, + restore_template_execution.ListRestoreTemplateExecutionsRequest, dict, ], ) -def test_list_backup_plan_revisions_rest_call_success(request_type): +def test_list_restore_template_executions_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/backupPlans/sample3"} + request_init = { + "parent": "projects/sample1/locations/sample2/restoreTemplates/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 = backupplan.ListBackupPlanRevisionsResponse( + return_value = restore_template_execution.ListRestoreTemplateExecutionsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -30482,21 +55123,25 @@ def test_list_backup_plan_revisions_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) + return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_plan_revisions(request) + response = client.list_restore_template_executions(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupPlanRevisionsPager) + assert isinstance(response, pagers.ListRestoreTemplateExecutionsPager) 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_plan_revisions_rest_interceptors(null_interceptor): +def test_list_restore_template_executions_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -30507,21 +55152,21 @@ def test_list_backup_plan_revisions_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.BackupDRRestInterceptor, "post_list_backup_plan_revisions" + transports.BackupDRRestInterceptor, "post_list_restore_template_executions" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_list_backup_plan_revisions_with_metadata", + "post_list_restore_template_executions_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_list_backup_plan_revisions" + transports.BackupDRRestInterceptor, "pre_list_restore_template_executions" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplan.ListBackupPlanRevisionsRequest.pb( - backupplan.ListBackupPlanRevisionsRequest() + pb_message = restore_template_execution.ListRestoreTemplateExecutionsRequest.pb( + restore_template_execution.ListRestoreTemplateExecutionsRequest() ) transcode.return_value = { "method": "post", @@ -30533,24 +55178,28 @@ def test_list_backup_plan_revisions_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 = backupplan.ListBackupPlanRevisionsResponse.to_json( - backupplan.ListBackupPlanRevisionsResponse() + return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse.to_json( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) ) req.return_value.content = return_value - request = backupplan.ListBackupPlanRevisionsRequest() + request = restore_template_execution.ListRestoreTemplateExecutionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupplan.ListBackupPlanRevisionsResponse() + post.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) post_with_metadata.return_value = ( - backupplan.ListBackupPlanRevisionsResponse(), + restore_template_execution.ListRestoreTemplateExecutionsResponse(), metadata, ) - client.list_backup_plan_revisions( + client.list_restore_template_executions( request, metadata=[ ("key", "val"), @@ -30563,14 +55212,16 @@ def test_list_backup_plan_revisions_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_backup_plan_association_rest_bad_request( - request_type=backupplanassociation.CreateBackupPlanAssociationRequest, +def test_trigger_restore_cleanup_rest_bad_request( + request_type=restore_template_execution.TriggerRestoreCleanupRequest, ): client = BackupDRClient( 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/restoreTemplates/sample3/executions/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -30586,129 +55237,25 @@ def test_create_backup_plan_association_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_backup_plan_association(request) + client.trigger_restore_cleanup(request) @pytest.mark.parametrize( "request_type", [ - backupplanassociation.CreateBackupPlanAssociationRequest, + restore_template_execution.TriggerRestoreCleanupRequest, dict, ], ) -def test_create_backup_plan_association_rest_call_success(request_type): +def test_trigger_restore_cleanup_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["backup_plan_association"] = { - "name": "name_value", - "resource_type": "resource_type_value", - "resource": "resource_value", - "backup_plan": "backup_plan_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "state": 1, - "rules_config_info": [ - { - "rule_id": "rule_id_value", - "last_backup_state": 1, - "last_backup_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - "last_successful_backup_consistency_time": {}, - } - ], - "data_source": "data_source_value", - "cloud_sql_instance_backup_plan_association_properties": { - "instance_create_time": {} - }, - "alloydb_cluster_backup_plan_association_properties": { - "cluster_uid": "cluster_uid_value" - }, - "backup_plan_revision_id": "backup_plan_revision_id_value", - "backup_plan_revision_name": "backup_plan_revision_name_value", + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/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 = backupplanassociation.CreateBackupPlanAssociationRequest.meta.fields[ - "backup_plan_association" - ] - - 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[ - "backup_plan_association" - ].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["backup_plan_association"][field])): - del request_init["backup_plan_association"][field][i][subfield] - else: - del request_init["backup_plan_association"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -30723,14 +55270,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_backup_plan_association(request) + response = client.trigger_restore_cleanup(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_backup_plan_association_rest_interceptors(null_interceptor): +def test_trigger_restore_cleanup_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -30742,21 +55289,21 @@ def test_create_backup_plan_association_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.BackupDRRestInterceptor, "post_create_backup_plan_association" + transports.BackupDRRestInterceptor, "post_trigger_restore_cleanup" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_create_backup_plan_association_with_metadata", + "post_trigger_restore_cleanup_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_create_backup_plan_association" + transports.BackupDRRestInterceptor, "pre_trigger_restore_cleanup" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplanassociation.CreateBackupPlanAssociationRequest.pb( - backupplanassociation.CreateBackupPlanAssociationRequest() + pb_message = restore_template_execution.TriggerRestoreCleanupRequest.pb( + restore_template_execution.TriggerRestoreCleanupRequest() ) transcode.return_value = { "method": "post", @@ -30771,7 +55318,7 @@ def test_create_backup_plan_association_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupplanassociation.CreateBackupPlanAssociationRequest() + request = restore_template_execution.TriggerRestoreCleanupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -30780,7 +55327,7 @@ def test_create_backup_plan_association_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_backup_plan_association( + client.trigger_restore_cleanup( request, metadata=[ ("key", "val"), @@ -30793,18 +55340,14 @@ def test_create_backup_plan_association_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_backup_plan_association_rest_bad_request( - request_type=backupplanassociation.UpdateBackupPlanAssociationRequest, +def test_create_restore_verification_plan_rest_bad_request( + request_type=gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "backup_plan_association": { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" - } - } + 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. @@ -30820,70 +55363,48 @@ def test_update_backup_plan_association_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_backup_plan_association(request) + client.create_restore_verification_plan(request) @pytest.mark.parametrize( "request_type", [ - backupplanassociation.UpdateBackupPlanAssociationRequest, + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, dict, ], ) -def test_update_backup_plan_association_rest_call_success(request_type): +def test_create_restore_verification_plan_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = { - "backup_plan_association": { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" - } - } - request_init["backup_plan_association"] = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3", - "resource_type": "resource_type_value", - "resource": "resource_value", - "backup_plan": "backup_plan_value", + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["restore_verification_plan"] = { + "name": "name_value", + "description": "description_value", "create_time": {"seconds": 751, "nanos": 543}, "update_time": {}, + "labels": {}, "state": 1, - "rules_config_info": [ - { - "rule_id": "rule_id_value", - "last_backup_state": 1, - "last_backup_error": { - "code": 411, - "message": "message_value", - "details": [ - { - "type_url": "type.googleapis.com/google.protobuf.Duration", - "value": b"\x08\x0c\x10\xdb\x07", - } - ], - }, - "last_successful_backup_consistency_time": {}, - } - ], - "data_source": "data_source_value", - "cloud_sql_instance_backup_plan_association_properties": { - "instance_create_time": {} - }, - "alloydb_cluster_backup_plan_association_properties": { - "cluster_uid": "cluster_uid_value" + "schedule": "schedule_value", + "time_zone": "time_zone_value", + "success_cleanup_rule": { + "cleanup_delay": {"seconds": 751, "nanos": 543}, + "skip_cleanup": True, }, - "backup_plan_revision_id": "backup_plan_revision_id_value", - "backup_plan_revision_name": "backup_plan_revision_name_value", + "failure_cleanup_rule": {}, } # 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 = backupplanassociation.UpdateBackupPlanAssociationRequest.meta.fields[ - "backup_plan_association" - ] + test_field = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest.meta.fields[ + "restore_verification_plan" + ] + ) def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -30912,7 +55433,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[ - "backup_plan_association" + "restore_verification_plan" ].items(): # pragma: NO COVER result = None is_repeated = False @@ -30943,10 +55464,12 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["backup_plan_association"][field])): - del request_init["backup_plan_association"][field][i][subfield] + for i in range( + 0, len(request_init["restore_verification_plan"][field]) + ): + del request_init["restore_verification_plan"][field][i][subfield] else: - del request_init["backup_plan_association"][field][subfield] + del request_init["restore_verification_plan"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -30961,14 +55484,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_backup_plan_association(request) + response = client.create_restore_verification_plan(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_backup_plan_association_rest_interceptors(null_interceptor): +def test_create_restore_verification_plan_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -30980,21 +55503,23 @@ def test_update_backup_plan_association_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.BackupDRRestInterceptor, "post_update_backup_plan_association" + transports.BackupDRRestInterceptor, "post_create_restore_verification_plan" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_update_backup_plan_association_with_metadata", + "post_create_restore_verification_plan_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_update_backup_plan_association" + transports.BackupDRRestInterceptor, "pre_create_restore_verification_plan" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplanassociation.UpdateBackupPlanAssociationRequest.pb( - backupplanassociation.UpdateBackupPlanAssociationRequest() + pb_message = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest.pb( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + ) ) transcode.return_value = { "method": "post", @@ -31009,7 +55534,7 @@ def test_update_backup_plan_association_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupplanassociation.UpdateBackupPlanAssociationRequest() + request = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -31018,7 +55543,7 @@ def test_update_backup_plan_association_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_backup_plan_association( + client.create_restore_verification_plan( request, metadata=[ ("key", "val"), @@ -31031,15 +55556,15 @@ def test_update_backup_plan_association_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_backup_plan_association_rest_bad_request( - request_type=backupplanassociation.GetBackupPlanAssociationRequest, +def test_create_restore_verification_plan_association_rest_bad_request( + request_type=gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" } request = request_type(**request_init) @@ -31056,67 +55581,151 @@ def test_get_backup_plan_association_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_backup_plan_association(request) + client.create_restore_verification_plan_association(request) @pytest.mark.parametrize( "request_type", [ - backupplanassociation.GetBackupPlanAssociationRequest, + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, dict, ], ) -def test_get_backup_plan_association_rest_call_success(request_type): +def test_create_restore_verification_plan_association_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" + } + request_init["restore_verification_plan_association"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "state": 1, + "trigger_summary": { + "last_trigger_time": {}, + "next_trigger_time": {}, + "last_trigger_error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "last_verification_execution": "last_verification_execution_value", + }, + "resource_type": "resource_type_value", + "restore_template": "restore_template_value", + "labels": {}, } + # 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 = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest.meta.fields[ + "restore_verification_plan_association" + ] + + 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[ + "restore_verification_plan_association" + ].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["restore_verification_plan_association"][field]) + ): + del request_init["restore_verification_plan_association"][field][i][ + subfield + ] + else: + del request_init["restore_verification_plan_association"][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 = backupplanassociation.BackupPlanAssociation( - name="name_value", - resource_type="resource_type_value", - resource="resource_value", - backup_plan="backup_plan_value", - state=backupplanassociation.BackupPlanAssociation.State.CREATING, - data_source="data_source_value", - backup_plan_revision_id="backup_plan_revision_id_value", - backup_plan_revision_name="backup_plan_revision_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 = backupplanassociation.BackupPlanAssociation.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_plan_association(request) + response = client.create_restore_verification_plan_association(request) # Establish that the response is the type that we expect. - assert isinstance(response, backupplanassociation.BackupPlanAssociation) - assert response.name == "name_value" - assert response.resource_type == "resource_type_value" - assert response.resource == "resource_value" - assert response.backup_plan == "backup_plan_value" - assert response.state == backupplanassociation.BackupPlanAssociation.State.CREATING - assert response.data_source == "data_source_value" - assert response.backup_plan_revision_id == "backup_plan_revision_id_value" - assert response.backup_plan_revision_name == "backup_plan_revision_name_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_plan_association_rest_interceptors(null_interceptor): +def test_create_restore_verification_plan_association_rest_interceptors( + null_interceptor, +): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -31126,22 +55735,25 @@ def test_get_backup_plan_association_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.BackupDRRestInterceptor, "post_get_backup_plan_association" + transports.BackupDRRestInterceptor, + "post_create_restore_verification_plan_association", ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_get_backup_plan_association_with_metadata", + "post_create_restore_verification_plan_association_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_get_backup_plan_association" + transports.BackupDRRestInterceptor, + "pre_create_restore_verification_plan_association", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplanassociation.GetBackupPlanAssociationRequest.pb( - backupplanassociation.GetBackupPlanAssociationRequest() + pb_message = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest.pb( + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() ) transcode.return_value = { "method": "post", @@ -31153,24 +55765,19 @@ def test_get_backup_plan_association_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 = backupplanassociation.BackupPlanAssociation.to_json( - backupplanassociation.BackupPlanAssociation() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupplanassociation.GetBackupPlanAssociationRequest() + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupplanassociation.BackupPlanAssociation() - post_with_metadata.return_value = ( - backupplanassociation.BackupPlanAssociation(), - metadata, - ) + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_backup_plan_association( + client.create_restore_verification_plan_association( request, metadata=[ ("key", "val"), @@ -31183,14 +55790,16 @@ def test_get_backup_plan_association_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_backup_plan_associations_rest_bad_request( - request_type=backupplanassociation.ListBackupPlanAssociationsRequest, +def test_get_restore_verification_plan_association_rest_bad_request( + request_type=restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, ): client = BackupDRClient( 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/restoreVerificationPlans/sample3/associations/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -31206,31 +55815,36 @@ def test_list_backup_plan_associations_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_backup_plan_associations(request) + client.get_restore_verification_plan_association(request) @pytest.mark.parametrize( "request_type", [ - backupplanassociation.ListBackupPlanAssociationsRequest, + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, dict, ], ) -def test_list_backup_plan_associations_rest_call_success(request_type): +def test_get_restore_verification_plan_association_rest_call_success(request_type): client = BackupDRClient( 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/restoreVerificationPlans/sample3/associations/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 = backupplanassociation.ListBackupPlanAssociationsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value", + description="description_value", + state=restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING, + resource_type="resource_type_value", + restore_template="restore_template_value", ) # Wrap the value into a proper Response obj @@ -31238,23 +55852,33 @@ def test_list_backup_plan_associations_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupplanassociation.ListBackupPlanAssociationsResponse.pb( - return_value + return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation.pb( + return_value + ) ) json_return_value = json_format.MessageToJson(return_value) response_value.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_plan_associations(request) + response = client.get_restore_verification_plan_association(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupPlanAssociationsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance( + response, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING + ) + assert response.resource_type == "resource_type_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_backup_plan_associations_rest_interceptors(null_interceptor): +def test_get_restore_verification_plan_association_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -31265,21 +55889,23 @@ def test_list_backup_plan_associations_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.BackupDRRestInterceptor, "post_list_backup_plan_associations" + transports.BackupDRRestInterceptor, + "post_get_restore_verification_plan_association", ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_list_backup_plan_associations_with_metadata", + "post_get_restore_verification_plan_association_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_list_backup_plan_associations" + transports.BackupDRRestInterceptor, + "pre_get_restore_verification_plan_association", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplanassociation.ListBackupPlanAssociationsRequest.pb( - backupplanassociation.ListBackupPlanAssociationsRequest() + pb_message = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest.pb( + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() ) transcode.return_value = { "method": "post", @@ -31291,24 +55917,26 @@ def test_list_backup_plan_associations_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 = backupplanassociation.ListBackupPlanAssociationsResponse.to_json( - backupplanassociation.ListBackupPlanAssociationsResponse() + return_value = restore_verification_plan_association.RestoreVerificationPlanAssociation.to_json( + restore_verification_plan_association.RestoreVerificationPlanAssociation() ) req.return_value.content = return_value - request = backupplanassociation.ListBackupPlanAssociationsRequest() + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + post.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) post_with_metadata.return_value = ( - backupplanassociation.ListBackupPlanAssociationsResponse(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), metadata, ) - client.list_backup_plan_associations( + client.get_restore_verification_plan_association( request, metadata=[ ("key", "val"), @@ -31321,14 +55949,16 @@ def test_list_backup_plan_associations_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_backup_plan_associations_for_resource_type_rest_bad_request( - request_type=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, +def test_list_restore_verification_plan_associations_rest_bad_request( + request_type=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -31344,34 +55974,33 @@ def test_fetch_backup_plan_associations_for_resource_type_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.fetch_backup_plan_associations_for_resource_type(request) + client.list_restore_verification_plan_associations(request) @pytest.mark.parametrize( "request_type", [ - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, dict, ], ) -def test_fetch_backup_plan_associations_for_resource_type_rest_call_success( - request_type, -): +def test_list_restore_verification_plan_associations_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/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 = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - next_page_token="next_page_token_value", - ) + return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) # Wrap the value into a proper Response obj @@ -31379,24 +56008,23 @@ def test_fetch_backup_plan_associations_for_resource_type_rest_call_success( response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( - return_value - ) + return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.pb( + return_value ) json_return_value = json_format.MessageToJson(return_value) response_value.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.fetch_backup_plan_associations_for_resource_type(request) + response = client.list_restore_verification_plan_associations(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchBackupPlanAssociationsForResourceTypePager) + assert isinstance(response, pagers.ListRestoreVerificationPlanAssociationsPager) assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_backup_plan_associations_for_resource_type_rest_interceptors( +def test_list_restore_verification_plan_associations_rest_interceptors( null_interceptor, ): transport = transports.BackupDRRestTransport( @@ -31410,22 +56038,22 @@ def test_fetch_backup_plan_associations_for_resource_type_rest_interceptors( mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.BackupDRRestInterceptor, - "post_fetch_backup_plan_associations_for_resource_type", + "post_list_restore_verification_plan_associations", ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_fetch_backup_plan_associations_for_resource_type_with_metadata", + "post_list_restore_verification_plan_associations_with_metadata", ) as post_with_metadata, mock.patch.object( transports.BackupDRRestInterceptor, - "pre_fetch_backup_plan_associations_for_resource_type", + "pre_list_restore_verification_plan_associations", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest.pb( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + pb_message = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest.pb( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() ) transcode.return_value = { "method": "post", @@ -31437,28 +56065,24 @@ def test_fetch_backup_plan_associations_for_resource_type_rest_interceptors( 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 = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.to_json( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() ) req.return_value.content = return_value - request = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() - ) + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - ) + post.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() post_with_metadata.return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse(), metadata, ) - client.fetch_backup_plan_associations_for_resource_type( + client.list_restore_verification_plan_associations( request, metadata=[ ("key", "val"), @@ -31471,15 +56095,15 @@ def test_fetch_backup_plan_associations_for_resource_type_rest_interceptors( post_with_metadata.assert_called_once() -def test_delete_backup_plan_association_rest_bad_request( - request_type=backupplanassociation.DeleteBackupPlanAssociationRequest, +def test_delete_restore_verification_plan_association_rest_bad_request( + request_type=restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/sample4" } request = request_type(**request_init) @@ -31496,24 +56120,24 @@ def test_delete_backup_plan_association_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_backup_plan_association(request) + client.delete_restore_verification_plan_association(request) @pytest.mark.parametrize( "request_type", [ - backupplanassociation.DeleteBackupPlanAssociationRequest, + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, dict, ], ) -def test_delete_backup_plan_association_rest_call_success(request_type): +def test_delete_restore_verification_plan_association_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/sample4" } request = request_type(**request_init) @@ -31529,14 +56153,16 @@ def test_delete_backup_plan_association_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_backup_plan_association(request) + response = client.delete_restore_verification_plan_association(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_plan_association_rest_interceptors(null_interceptor): +def test_delete_restore_verification_plan_association_rest_interceptors( + null_interceptor, +): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -31548,21 +56174,23 @@ def test_delete_backup_plan_association_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.BackupDRRestInterceptor, "post_delete_backup_plan_association" + transports.BackupDRRestInterceptor, + "post_delete_restore_verification_plan_association", ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_delete_backup_plan_association_with_metadata", + "post_delete_restore_verification_plan_association_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_delete_backup_plan_association" + transports.BackupDRRestInterceptor, + "pre_delete_restore_verification_plan_association", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplanassociation.DeleteBackupPlanAssociationRequest.pb( - backupplanassociation.DeleteBackupPlanAssociationRequest() + pb_message = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest.pb( + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() ) transcode.return_value = { "method": "post", @@ -31577,7 +56205,7 @@ def test_delete_backup_plan_association_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupplanassociation.DeleteBackupPlanAssociationRequest() + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -31586,7 +56214,7 @@ def test_delete_backup_plan_association_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_backup_plan_association( + client.delete_restore_verification_plan_association( request, metadata=[ ("key", "val"), @@ -31599,15 +56227,15 @@ def test_delete_backup_plan_association_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_trigger_backup_rest_bad_request( - request_type=backupplanassociation.TriggerBackupRequest, +def test_trigger_restore_verification_rest_bad_request( + request_type=restore_verification_plan_association.TriggerRestoreVerificationRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/sample4" } request = request_type(**request_init) @@ -31624,24 +56252,24 @@ def test_trigger_backup_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.trigger_backup(request) + client.trigger_restore_verification(request) @pytest.mark.parametrize( "request_type", [ - backupplanassociation.TriggerBackupRequest, + restore_verification_plan_association.TriggerRestoreVerificationRequest, dict, ], ) -def test_trigger_backup_rest_call_success(request_type): +def test_trigger_restore_verification_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/sample4" } request = request_type(**request_init) @@ -31657,14 +56285,14 @@ def test_trigger_backup_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.trigger_backup(request) + response = client.trigger_restore_verification(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_trigger_backup_rest_interceptors(null_interceptor): +def test_trigger_restore_verification_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -31676,20 +56304,21 @@ def test_trigger_backup_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.BackupDRRestInterceptor, "post_trigger_backup" + transports.BackupDRRestInterceptor, "post_trigger_restore_verification" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_trigger_backup_with_metadata" + transports.BackupDRRestInterceptor, + "post_trigger_restore_verification_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_trigger_backup" + transports.BackupDRRestInterceptor, "pre_trigger_restore_verification" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupplanassociation.TriggerBackupRequest.pb( - backupplanassociation.TriggerBackupRequest() + pb_message = restore_verification_plan_association.TriggerRestoreVerificationRequest.pb( + restore_verification_plan_association.TriggerRestoreVerificationRequest() ) transcode.return_value = { "method": "post", @@ -31704,7 +56333,9 @@ def test_trigger_backup_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupplanassociation.TriggerBackupRequest() + request = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -31713,7 +56344,7 @@ def test_trigger_backup_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.trigger_backup( + client.trigger_restore_verification( request, metadata=[ ("key", "val"), @@ -31726,15 +56357,15 @@ def test_trigger_backup_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_data_source_reference_rest_bad_request( - request_type=datasourcereference.GetDataSourceReferenceRequest, +def test_get_restore_verification_plan_rest_bad_request( + request_type=restore_verification_plan.GetRestoreVerificationPlanRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataSourceReferences/sample3" + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" } request = request_type(**request_init) @@ -31751,36 +56382,36 @@ def test_get_data_source_reference_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_data_source_reference(request) + client.get_restore_verification_plan(request) @pytest.mark.parametrize( "request_type", [ - datasourcereference.GetDataSourceReferenceRequest, + restore_verification_plan.GetRestoreVerificationPlanRequest, dict, ], ) -def test_get_data_source_reference_rest_call_success(request_type): +def test_get_restore_verification_plan_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/dataSourceReferences/sample3" + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/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 = datasourcereference.DataSourceReference( + return_value = restore_verification_plan.RestoreVerificationPlan( name="name_value", - data_source="data_source_value", - data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, - data_source_backup_count=2535, - total_stored_bytes=1946, + description="description_value", + state=restore_verification_plan.RestoreVerificationPlan.State.CREATING, + schedule="schedule_value", + time_zone="time_zone_value", ) # Wrap the value into a proper Response obj @@ -31788,26 +56419,29 @@ def test_get_data_source_reference_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = datasourcereference.DataSourceReference.pb(return_value) + return_value = restore_verification_plan.RestoreVerificationPlan.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_data_source_reference(request) + response = client.get_restore_verification_plan(request) # Establish that the response is the type that we expect. - assert isinstance(response, datasourcereference.DataSourceReference) + assert isinstance(response, restore_verification_plan.RestoreVerificationPlan) assert response.name == "name_value" - assert response.data_source == "data_source_value" + assert response.description == "description_value" assert ( - response.data_source_backup_config_state == backupvault.BackupConfigState.ACTIVE + response.state + == restore_verification_plan.RestoreVerificationPlan.State.CREATING ) - assert response.data_source_backup_count == 2535 - assert response.total_stored_bytes == 1946 + assert response.schedule == "schedule_value" + assert response.time_zone == "time_zone_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_data_source_reference_rest_interceptors(null_interceptor): +def test_get_restore_verification_plan_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -31818,21 +56452,21 @@ def test_get_data_source_reference_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.BackupDRRestInterceptor, "post_get_data_source_reference" + transports.BackupDRRestInterceptor, "post_get_restore_verification_plan" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_get_data_source_reference_with_metadata", + "post_get_restore_verification_plan_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_get_data_source_reference" + transports.BackupDRRestInterceptor, "pre_get_restore_verification_plan" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = datasourcereference.GetDataSourceReferenceRequest.pb( - datasourcereference.GetDataSourceReferenceRequest() + pb_message = restore_verification_plan.GetRestoreVerificationPlanRequest.pb( + restore_verification_plan.GetRestoreVerificationPlanRequest() ) transcode.return_value = { "method": "post", @@ -31844,24 +56478,24 @@ def test_get_data_source_reference_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 = datasourcereference.DataSourceReference.to_json( - datasourcereference.DataSourceReference() + return_value = restore_verification_plan.RestoreVerificationPlan.to_json( + restore_verification_plan.RestoreVerificationPlan() ) req.return_value.content = return_value - request = datasourcereference.GetDataSourceReferenceRequest() + request = restore_verification_plan.GetRestoreVerificationPlanRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = datasourcereference.DataSourceReference() + post.return_value = restore_verification_plan.RestoreVerificationPlan() post_with_metadata.return_value = ( - datasourcereference.DataSourceReference(), + restore_verification_plan.RestoreVerificationPlan(), metadata, ) - client.get_data_source_reference( + client.get_restore_verification_plan( request, metadata=[ ("key", "val"), @@ -31874,8 +56508,8 @@ def test_get_data_source_reference_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_data_source_references_rest_bad_request( - request_type=datasourcereference.ListDataSourceReferencesRequest, +def test_list_restore_verification_plans_rest_bad_request( + request_type=restore_verification_plan.ListRestoreVerificationPlansRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -31897,17 +56531,17 @@ def test_list_data_source_references_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_data_source_references(request) + client.list_restore_verification_plans(request) @pytest.mark.parametrize( "request_type", [ - datasourcereference.ListDataSourceReferencesRequest, + restore_verification_plan.ListRestoreVerificationPlansRequest, dict, ], ) -def test_list_data_source_references_rest_call_success(request_type): +def test_list_restore_verification_plans_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -31919,7 +56553,7 @@ def test_list_data_source_references_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 = datasourcereference.ListDataSourceReferencesResponse( + return_value = restore_verification_plan.ListRestoreVerificationPlansResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -31928,148 +56562,9 @@ def test_list_data_source_references_rest_call_success(request_type): response_value = mock.Mock() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = datasourcereference.ListDataSourceReferencesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value.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_data_source_references(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourceReferencesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_data_source_references_rest_interceptors(null_interceptor): - transport = transports.BackupDRRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), - ) - client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_data_source_references" - ) as post, - mock.patch.object( - transports.BackupDRRestInterceptor, - "post_list_data_source_references_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.BackupDRRestInterceptor, "pre_list_data_source_references" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = datasourcereference.ListDataSourceReferencesRequest.pb( - datasourcereference.ListDataSourceReferencesRequest() - ) - 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 = datasourcereference.ListDataSourceReferencesResponse.to_json( - datasourcereference.ListDataSourceReferencesResponse() - ) - req.return_value.content = return_value - - request = datasourcereference.ListDataSourceReferencesRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = datasourcereference.ListDataSourceReferencesResponse() - post_with_metadata.return_value = ( - datasourcereference.ListDataSourceReferencesResponse(), - metadata, - ) - - client.list_data_source_references( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_fetch_data_source_references_for_resource_type_rest_bad_request( - request_type=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, -): - client = BackupDRClient( - 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.fetch_data_source_references_for_resource_type(request) - - -@pytest.mark.parametrize( - "request_type", - [ - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, - dict, - ], -) -def test_fetch_data_source_references_for_resource_type_rest_call_success(request_type): - client = BackupDRClient( - 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 = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - next_page_token="next_page_token_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 = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + restore_verification_plan.ListRestoreVerificationPlansResponse.pb( return_value ) ) @@ -32077,17 +56572,16 @@ def test_fetch_data_source_references_for_resource_type_rest_call_success(reques response_value.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.fetch_data_source_references_for_resource_type(request) + response = client.list_restore_verification_plans(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchDataSourceReferencesForResourceTypePager) + assert isinstance(response, pagers.ListRestoreVerificationPlansPager) assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_data_source_references_for_resource_type_rest_interceptors( - null_interceptor, -): +def test_list_restore_verification_plans_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -32098,25 +56592,21 @@ def test_fetch_data_source_references_for_resource_type_rest_interceptors( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.BackupDRRestInterceptor, - "post_fetch_data_source_references_for_resource_type", + transports.BackupDRRestInterceptor, "post_list_restore_verification_plans" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_fetch_data_source_references_for_resource_type_with_metadata", + "post_list_restore_verification_plans_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, - "pre_fetch_data_source_references_for_resource_type", + transports.BackupDRRestInterceptor, "pre_list_restore_verification_plans" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest.pb( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() - ) + pb_message = restore_verification_plan.ListRestoreVerificationPlansRequest.pb( + restore_verification_plan.ListRestoreVerificationPlansRequest() ) transcode.return_value = { "method": "post", @@ -32128,26 +56618,28 @@ def test_fetch_data_source_references_for_resource_type_rest_interceptors( 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 = datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.to_json( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse.to_json( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) ) req.return_value.content = return_value - request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + request = restore_verification_plan.ListRestoreVerificationPlansRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata post.return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + restore_verification_plan.ListRestoreVerificationPlansResponse() ) post_with_metadata.return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse(), + restore_verification_plan.ListRestoreVerificationPlansResponse(), metadata, ) - client.fetch_data_source_references_for_resource_type( + client.list_restore_verification_plans( request, metadata=[ ("key", "val"), @@ -32160,14 +56652,16 @@ def test_fetch_data_source_references_for_resource_type_rest_interceptors( post_with_metadata.assert_called_once() -def test_initialize_service_rest_bad_request( - request_type=backupdr.InitializeServiceRequest, +def test_delete_restore_verification_plan_rest_bad_request( + request_type=restore_verification_plan.DeleteRestoreVerificationPlanRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/serviceConfig"} + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -32183,23 +56677,25 @@ def test_initialize_service_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.initialize_service(request) + client.delete_restore_verification_plan(request) @pytest.mark.parametrize( "request_type", [ - backupdr.InitializeServiceRequest, + restore_verification_plan.DeleteRestoreVerificationPlanRequest, dict, ], ) -def test_initialize_service_rest_call_success(request_type): +def test_delete_restore_verification_plan_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/serviceConfig"} + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -32214,14 +56710,14 @@ def test_initialize_service_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.initialize_service(request) + response = client.delete_restore_verification_plan(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_initialize_service_rest_interceptors(null_interceptor): +def test_delete_restore_verification_plan_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -32233,20 +56729,21 @@ def test_initialize_service_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.BackupDRRestInterceptor, "post_initialize_service" + transports.BackupDRRestInterceptor, "post_delete_restore_verification_plan" ) as post, mock.patch.object( - transports.BackupDRRestInterceptor, "post_initialize_service_with_metadata" + transports.BackupDRRestInterceptor, + "post_delete_restore_verification_plan_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_initialize_service" + transports.BackupDRRestInterceptor, "pre_delete_restore_verification_plan" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupdr.InitializeServiceRequest.pb( - backupdr.InitializeServiceRequest() + pb_message = restore_verification_plan.DeleteRestoreVerificationPlanRequest.pb( + restore_verification_plan.DeleteRestoreVerificationPlanRequest() ) transcode.return_value = { "method": "post", @@ -32261,7 +56758,7 @@ def test_initialize_service_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupdr.InitializeServiceRequest() + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -32270,7 +56767,7 @@ def test_initialize_service_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.initialize_service( + client.delete_restore_verification_plan( request, metadata=[ ("key", "val"), @@ -33627,6 +58124,628 @@ def test_initialize_service_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_create_auto_protection_policy_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + client.create_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + 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_auto_protection_policies_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + client.list_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + 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_auto_protection_policy_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + client.get_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + client.update_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + client.delete_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + 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_auto_protection_policy_binding_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + client.create_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_binding_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + client.get_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_bindings_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + client.list_auto_protection_policy_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + 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_applied_auto_protection_policies_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + client.list_applied_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + ) + 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_initiate_delete_auto_protection_policy_binding_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + client.initiate_delete_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + 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_binding_matching_resources_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + client.list_binding_matching_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() + 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_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + client.create_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.CreateRestoreTemplateRequest() + 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_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template), "__call__" + ) as call: + client.get_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.GetRestoreTemplateRequest() + 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_restore_templates_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + client.list_restore_templates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.ListRestoreTemplatesRequest() + 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_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: + client.update_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.UpdateRestoreTemplateRequest() + 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_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__call__" + ) as call: + client.delete_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.DeleteRestoreTemplateRequest() + 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_run_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__call__" + ) as call: + client.run_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.RunRestoreTemplateRequest() + 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_restore_template_execution_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + client.get_restore_template_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.GetRestoreTemplateExecutionRequest() + 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_restore_template_executions_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + client.list_restore_template_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.ListRestoreTemplateExecutionsRequest() + 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_trigger_restore_cleanup_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: + client.trigger_restore_cleanup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.TriggerRestoreCleanupRequest() + 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_restore_verification_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__call__" + ) as call: + client.create_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + ) + 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_restore_verification_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + client.create_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + client.get_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_associations_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + client.list_restore_verification_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + 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_restore_verification_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: + client.delete_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + 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_trigger_restore_verification_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__call__" + ) as call: + client.trigger_restore_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) + 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_restore_verification_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: + client.get_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.GetRestoreVerificationPlanRequest() + 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_restore_verification_plans_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: + client.list_restore_verification_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.ListRestoreVerificationPlansRequest() + 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_restore_verification_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan), "__call__" + ) as call: + client.delete_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + assert args[0] == request_msg + + def test_backup_dr_rest_lro_client(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -33714,6 +58833,35 @@ def test_backup_dr_base_transport(): "list_data_source_references", "fetch_data_source_references_for_resource_type", "initialize_service", + "create_auto_protection_policy", + "list_auto_protection_policies", + "get_auto_protection_policy", + "update_auto_protection_policy", + "delete_auto_protection_policy", + "create_auto_protection_policy_binding", + "get_auto_protection_policy_binding", + "list_auto_protection_policy_bindings", + "list_applied_auto_protection_policies", + "initiate_delete_auto_protection_policy_binding", + "list_binding_matching_resources", + "create_restore_template", + "get_restore_template", + "list_restore_templates", + "update_restore_template", + "delete_restore_template", + "run_restore_template", + "get_restore_template_execution", + "list_restore_template_executions", + "trigger_restore_cleanup", + "create_restore_verification_plan", + "create_restore_verification_plan_association", + "get_restore_verification_plan_association", + "list_restore_verification_plan_associations", + "delete_restore_verification_plan_association", + "trigger_restore_verification", + "get_restore_verification_plan", + "list_restore_verification_plans", + "delete_restore_verification_plan", "set_iam_policy", "get_iam_policy", "test_iam_permissions", @@ -34105,6 +59253,93 @@ def test_backup_dr_client_transport_session_collision(transport_name): session1 = client1.transport.initialize_service._session session2 = client2.transport.initialize_service._session assert session1 != session2 + session1 = client1.transport.create_auto_protection_policy._session + session2 = client2.transport.create_auto_protection_policy._session + assert session1 != session2 + session1 = client1.transport.list_auto_protection_policies._session + session2 = client2.transport.list_auto_protection_policies._session + assert session1 != session2 + session1 = client1.transport.get_auto_protection_policy._session + session2 = client2.transport.get_auto_protection_policy._session + assert session1 != session2 + session1 = client1.transport.update_auto_protection_policy._session + session2 = client2.transport.update_auto_protection_policy._session + assert session1 != session2 + session1 = client1.transport.delete_auto_protection_policy._session + session2 = client2.transport.delete_auto_protection_policy._session + assert session1 != session2 + session1 = client1.transport.create_auto_protection_policy_binding._session + session2 = client2.transport.create_auto_protection_policy_binding._session + assert session1 != session2 + session1 = client1.transport.get_auto_protection_policy_binding._session + session2 = client2.transport.get_auto_protection_policy_binding._session + assert session1 != session2 + session1 = client1.transport.list_auto_protection_policy_bindings._session + session2 = client2.transport.list_auto_protection_policy_bindings._session + assert session1 != session2 + session1 = client1.transport.list_applied_auto_protection_policies._session + session2 = client2.transport.list_applied_auto_protection_policies._session + assert session1 != session2 + session1 = client1.transport.initiate_delete_auto_protection_policy_binding._session + session2 = client2.transport.initiate_delete_auto_protection_policy_binding._session + assert session1 != session2 + session1 = client1.transport.list_binding_matching_resources._session + session2 = client2.transport.list_binding_matching_resources._session + assert session1 != session2 + session1 = client1.transport.create_restore_template._session + session2 = client2.transport.create_restore_template._session + assert session1 != session2 + session1 = client1.transport.get_restore_template._session + session2 = client2.transport.get_restore_template._session + assert session1 != session2 + session1 = client1.transport.list_restore_templates._session + session2 = client2.transport.list_restore_templates._session + assert session1 != session2 + session1 = client1.transport.update_restore_template._session + session2 = client2.transport.update_restore_template._session + assert session1 != session2 + session1 = client1.transport.delete_restore_template._session + session2 = client2.transport.delete_restore_template._session + assert session1 != session2 + session1 = client1.transport.run_restore_template._session + session2 = client2.transport.run_restore_template._session + assert session1 != session2 + session1 = client1.transport.get_restore_template_execution._session + session2 = client2.transport.get_restore_template_execution._session + assert session1 != session2 + session1 = client1.transport.list_restore_template_executions._session + session2 = client2.transport.list_restore_template_executions._session + assert session1 != session2 + session1 = client1.transport.trigger_restore_cleanup._session + session2 = client2.transport.trigger_restore_cleanup._session + assert session1 != session2 + session1 = client1.transport.create_restore_verification_plan._session + session2 = client2.transport.create_restore_verification_plan._session + assert session1 != session2 + session1 = client1.transport.create_restore_verification_plan_association._session + session2 = client2.transport.create_restore_verification_plan_association._session + assert session1 != session2 + session1 = client1.transport.get_restore_verification_plan_association._session + session2 = client2.transport.get_restore_verification_plan_association._session + assert session1 != session2 + session1 = client1.transport.list_restore_verification_plan_associations._session + session2 = client2.transport.list_restore_verification_plan_associations._session + assert session1 != session2 + session1 = client1.transport.delete_restore_verification_plan_association._session + session2 = client2.transport.delete_restore_verification_plan_association._session + assert session1 != session2 + session1 = client1.transport.trigger_restore_verification._session + session2 = client2.transport.trigger_restore_verification._session + assert session1 != session2 + session1 = client1.transport.get_restore_verification_plan._session + session2 = client2.transport.get_restore_verification_plan._session + assert session1 != session2 + session1 = client1.transport.list_restore_verification_plans._session + session2 = client2.transport.list_restore_verification_plans._session + assert session1 != session2 + session1 = client1.transport.delete_restore_verification_plan._session + session2 = client2.transport.delete_restore_verification_plan._session + assert session1 != session2 def test_backup_dr_grpc_transport_channel(): @@ -34260,12 +59495,99 @@ def test_backup_dr_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client -def test_backup_path(): +def test_applied_auto_protection_policy_path(): + project = "squid" + location = "clam" + applied_auto_protection_policy = "whelk" + expected = "projects/{project}/locations/{location}/appliedAutoProtectionPolicies/{applied_auto_protection_policy}".format( + project=project, + location=location, + applied_auto_protection_policy=applied_auto_protection_policy, + ) + actual = BackupDRClient.applied_auto_protection_policy_path( + project, location, applied_auto_protection_policy + ) + assert expected == actual + + +def test_parse_applied_auto_protection_policy_path(): + expected = { + "project": "octopus", + "location": "oyster", + "applied_auto_protection_policy": "nudibranch", + } + path = BackupDRClient.applied_auto_protection_policy_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_applied_auto_protection_policy_path(path) + assert expected == actual + + +def test_auto_protection_policy_path(): + project = "cuttlefish" + location = "mussel" + auto_protection_policy = "winkle" + expected = "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + ) + actual = BackupDRClient.auto_protection_policy_path( + project, location, auto_protection_policy + ) + assert expected == actual + + +def test_parse_auto_protection_policy_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "auto_protection_policy": "abalone", + } + path = BackupDRClient.auto_protection_policy_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_auto_protection_policy_path(path) + assert expected == actual + + +def test_auto_protection_policy_binding_path(): project = "squid" location = "clam" - backupvault = "whelk" - datasource = "octopus" - backup = "oyster" + auto_protection_policy = "whelk" + binding = "octopus" + expected = "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + binding=binding, + ) + actual = BackupDRClient.auto_protection_policy_binding_path( + project, location, auto_protection_policy, binding + ) + assert expected == actual + + +def test_parse_auto_protection_policy_binding_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "auto_protection_policy": "cuttlefish", + "binding": "mussel", + } + path = BackupDRClient.auto_protection_policy_binding_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_auto_protection_policy_binding_path(path) + assert expected == actual + + +def test_backup_path(): + project = "winkle" + location = "nautilus" + backupvault = "scallop" + datasource = "abalone" + backup = "squid" expected = "projects/{project}/locations/{location}/backupVaults/{backupvault}/dataSources/{datasource}/backups/{backup}".format( project=project, location=location, @@ -34281,11 +59603,11 @@ def test_backup_path(): def test_parse_backup_path(): expected = { - "project": "nudibranch", - "location": "cuttlefish", - "backupvault": "mussel", - "datasource": "winkle", - "backup": "nautilus", + "project": "clam", + "location": "whelk", + "backupvault": "octopus", + "datasource": "oyster", + "backup": "nudibranch", } path = BackupDRClient.backup_path(**expected) @@ -34295,9 +59617,9 @@ def test_parse_backup_path(): def test_backup_plan_path(): - project = "scallop" - location = "abalone" - backup_plan = "squid" + project = "cuttlefish" + location = "mussel" + backup_plan = "winkle" expected = ( "projects/{project}/locations/{location}/backupPlans/{backup_plan}".format( project=project, @@ -34311,9 +59633,9 @@ def test_backup_plan_path(): def test_parse_backup_plan_path(): expected = { - "project": "clam", - "location": "whelk", - "backup_plan": "octopus", + "project": "nautilus", + "location": "scallop", + "backup_plan": "abalone", } path = BackupDRClient.backup_plan_path(**expected) @@ -34323,9 +59645,9 @@ def test_parse_backup_plan_path(): def test_backup_plan_association_path(): - project = "oyster" - location = "nudibranch" - backup_plan_association = "cuttlefish" + project = "squid" + location = "clam" + backup_plan_association = "whelk" expected = "projects/{project}/locations/{location}/backupPlanAssociations/{backup_plan_association}".format( project=project, location=location, @@ -34339,9 +59661,9 @@ def test_backup_plan_association_path(): def test_parse_backup_plan_association_path(): expected = { - "project": "mussel", - "location": "winkle", - "backup_plan_association": "nautilus", + "project": "octopus", + "location": "oyster", + "backup_plan_association": "nudibranch", } path = BackupDRClient.backup_plan_association_path(**expected) @@ -34351,10 +59673,10 @@ def test_parse_backup_plan_association_path(): def test_backup_plan_revision_path(): - project = "scallop" - location = "abalone" - backup_plan = "squid" - revision = "clam" + project = "cuttlefish" + location = "mussel" + backup_plan = "winkle" + revision = "nautilus" expected = "projects/{project}/locations/{location}/backupPlans/{backup_plan}/revisions/{revision}".format( project=project, location=location, @@ -34369,10 +59691,10 @@ def test_backup_plan_revision_path(): def test_parse_backup_plan_revision_path(): expected = { - "project": "whelk", - "location": "octopus", - "backup_plan": "oyster", - "revision": "nudibranch", + "project": "scallop", + "location": "abalone", + "backup_plan": "squid", + "revision": "clam", } path = BackupDRClient.backup_plan_revision_path(**expected) @@ -34382,9 +59704,9 @@ def test_parse_backup_plan_revision_path(): def test_backup_vault_path(): - project = "cuttlefish" - location = "mussel" - backupvault = "winkle" + project = "whelk" + location = "octopus" + backupvault = "oyster" expected = ( "projects/{project}/locations/{location}/backupVaults/{backupvault}".format( project=project, @@ -34398,9 +59720,9 @@ def test_backup_vault_path(): def test_parse_backup_vault_path(): expected = { - "project": "nautilus", - "location": "scallop", - "backupvault": "abalone", + "project": "nudibranch", + "location": "cuttlefish", + "backupvault": "mussel", } path = BackupDRClient.backup_vault_path(**expected) @@ -34409,10 +59731,44 @@ def test_parse_backup_vault_path(): assert expected == actual +def test_binding_matching_resource_path(): + project = "winkle" + location = "nautilus" + auto_protection_policy = "scallop" + binding = "abalone" + matching_resource = "squid" + expected = "projects/{project}/locations/{location}/autoProtectionPolicies/{auto_protection_policy}/bindings/{binding}/matchingResources/{matching_resource}".format( + project=project, + location=location, + auto_protection_policy=auto_protection_policy, + binding=binding, + matching_resource=matching_resource, + ) + actual = BackupDRClient.binding_matching_resource_path( + project, location, auto_protection_policy, binding, matching_resource + ) + assert expected == actual + + +def test_parse_binding_matching_resource_path(): + expected = { + "project": "clam", + "location": "whelk", + "auto_protection_policy": "octopus", + "binding": "oyster", + "matching_resource": "nudibranch", + } + path = BackupDRClient.binding_matching_resource_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_binding_matching_resource_path(path) + assert expected == actual + + def test_cluster_path(): - project = "squid" - location = "clam" - cluster = "whelk" + project = "cuttlefish" + location = "mussel" + cluster = "winkle" expected = "projects/{project}/locations/{location}/clusters/{cluster}".format( project=project, location=location, @@ -34424,9 +59780,9 @@ def test_cluster_path(): def test_parse_cluster_path(): expected = { - "project": "octopus", - "location": "oyster", - "cluster": "nudibranch", + "project": "nautilus", + "location": "scallop", + "cluster": "abalone", } path = BackupDRClient.cluster_path(**expected) @@ -34436,10 +59792,10 @@ def test_parse_cluster_path(): def test_crypto_key_path(): - project = "cuttlefish" - location = "mussel" - ring = "winkle" - key = "nautilus" + project = "squid" + location = "clam" + ring = "whelk" + key = "octopus" expected = "projects/{project}/locations/{location}/keyRings/{ring}/cryptoKeys/{key}".format( project=project, location=location, @@ -34452,10 +59808,10 @@ def test_crypto_key_path(): def test_parse_crypto_key_path(): expected = { - "project": "scallop", - "location": "abalone", - "ring": "squid", - "key": "clam", + "project": "oyster", + "location": "nudibranch", + "ring": "cuttlefish", + "key": "mussel", } path = BackupDRClient.crypto_key_path(**expected) @@ -34465,11 +59821,11 @@ def test_parse_crypto_key_path(): def test_crypto_key_version_path(): - project = "whelk" - location = "octopus" - key_ring = "oyster" - crypto_key = "nudibranch" - crypto_key_version = "cuttlefish" + 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, @@ -34485,11 +59841,11 @@ def test_crypto_key_version_path(): def test_parse_crypto_key_version_path(): expected = { - "project": "mussel", - "location": "winkle", - "key_ring": "nautilus", - "crypto_key": "scallop", - "crypto_key_version": "abalone", + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", } path = BackupDRClient.crypto_key_version_path(**expected) @@ -34499,10 +59855,10 @@ def test_parse_crypto_key_version_path(): def test_data_source_path(): - project = "squid" - location = "clam" - backupvault = "whelk" - datasource = "octopus" + project = "cuttlefish" + location = "mussel" + backupvault = "winkle" + datasource = "nautilus" expected = "projects/{project}/locations/{location}/backupVaults/{backupvault}/dataSources/{datasource}".format( project=project, location=location, @@ -34515,10 +59871,10 @@ def test_data_source_path(): def test_parse_data_source_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "backupvault": "cuttlefish", - "datasource": "mussel", + "project": "scallop", + "location": "abalone", + "backupvault": "squid", + "datasource": "clam", } path = BackupDRClient.data_source_path(**expected) @@ -34528,9 +59884,9 @@ def test_parse_data_source_path(): def test_data_source_reference_path(): - project = "winkle" - location = "nautilus" - data_source_reference = "scallop" + project = "whelk" + location = "octopus" + data_source_reference = "oyster" expected = "projects/{project}/locations/{location}/dataSourceReferences/{data_source_reference}".format( project=project, location=location, @@ -34544,9 +59900,9 @@ def test_data_source_reference_path(): def test_parse_data_source_reference_path(): expected = { - "project": "abalone", - "location": "squid", - "data_source_reference": "clam", + "project": "nudibranch", + "location": "cuttlefish", + "data_source_reference": "mussel", } path = BackupDRClient.data_source_reference_path(**expected) @@ -34555,9 +59911,38 @@ def test_parse_data_source_reference_path(): assert expected == actual +def test_execution_path(): + project = "winkle" + location = "nautilus" + job = "scallop" + execution = "abalone" + expected = "projects/{project}/locations/{location}/jobs/{job}/executions/{execution}".format( + project=project, + location=location, + job=job, + execution=execution, + ) + actual = BackupDRClient.execution_path(project, location, job, execution) + assert expected == actual + + +def test_parse_execution_path(): + expected = { + "project": "squid", + "location": "clam", + "job": "whelk", + "execution": "octopus", + } + path = BackupDRClient.execution_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_execution_path(path) + assert expected == actual + + def test_instance_path(): - project = "whelk" - instance = "octopus" + project = "oyster" + instance = "nudibranch" expected = "projects/{project}/instances/{instance}".format( project=project, instance=instance, @@ -34568,8 +59953,8 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "oyster", - "instance": "nudibranch", + "project": "cuttlefish", + "instance": "mussel", } path = BackupDRClient.instance_path(**expected) @@ -34578,10 +59963,36 @@ def test_parse_instance_path(): assert expected == actual +def test_job_path(): + project = "winkle" + location = "nautilus" + job = "scallop" + expected = "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, + location=location, + job=job, + ) + actual = BackupDRClient.job_path(project, location, job) + assert expected == actual + + +def test_parse_job_path(): + expected = { + "project": "abalone", + "location": "squid", + "job": "clam", + } + path = BackupDRClient.job_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_job_path(path) + assert expected == actual + + def test_management_server_path(): - project = "cuttlefish" - location = "mussel" - managementserver = "winkle" + project = "whelk" + location = "octopus" + managementserver = "oyster" expected = "projects/{project}/locations/{location}/managementServers/{managementserver}".format( project=project, location=location, @@ -34593,9 +60004,9 @@ def test_management_server_path(): def test_parse_management_server_path(): expected = { - "project": "nautilus", - "location": "scallop", - "managementserver": "abalone", + "project": "nudibranch", + "location": "cuttlefish", + "managementserver": "mussel", } path = BackupDRClient.management_server_path(**expected) @@ -34604,6 +60015,122 @@ def test_parse_management_server_path(): assert expected == actual +def test_restore_template_path(): + project = "winkle" + location = "nautilus" + restore_template = "scallop" + expected = "projects/{project}/locations/{location}/restoreTemplates/{restore_template}".format( + project=project, + location=location, + restore_template=restore_template, + ) + actual = BackupDRClient.restore_template_path(project, location, restore_template) + assert expected == actual + + +def test_parse_restore_template_path(): + expected = { + "project": "abalone", + "location": "squid", + "restore_template": "clam", + } + path = BackupDRClient.restore_template_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_restore_template_path(path) + assert expected == actual + + +def test_restore_template_execution_path(): + project = "whelk" + location = "octopus" + restore_template = "oyster" + execution = "nudibranch" + expected = "projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}".format( + project=project, + location=location, + restore_template=restore_template, + execution=execution, + ) + actual = BackupDRClient.restore_template_execution_path( + project, location, restore_template, execution + ) + assert expected == actual + + +def test_parse_restore_template_execution_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "restore_template": "winkle", + "execution": "nautilus", + } + path = BackupDRClient.restore_template_execution_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_restore_template_execution_path(path) + assert expected == actual + + +def test_restore_verification_plan_path(): + project = "scallop" + location = "abalone" + restoreVerificationPlan = "squid" + expected = "projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}".format( + project=project, + location=location, + restoreVerificationPlan=restoreVerificationPlan, + ) + actual = BackupDRClient.restore_verification_plan_path( + project, location, restoreVerificationPlan + ) + assert expected == actual + + +def test_parse_restore_verification_plan_path(): + expected = { + "project": "clam", + "location": "whelk", + "restoreVerificationPlan": "octopus", + } + path = BackupDRClient.restore_verification_plan_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_restore_verification_plan_path(path) + assert expected == actual + + +def test_restore_verification_plan_association_path(): + project = "oyster" + location = "nudibranch" + restore_verification_plan = "cuttlefish" + association = "mussel" + expected = "projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}".format( + project=project, + location=location, + restore_verification_plan=restore_verification_plan, + association=association, + ) + actual = BackupDRClient.restore_verification_plan_association_path( + project, location, restore_verification_plan, association + ) + assert expected == actual + + +def test_parse_restore_verification_plan_association_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "restore_verification_plan": "scallop", + "association": "abalone", + } + path = BackupDRClient.restore_verification_plan_association_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_restore_verification_plan_association_path(path) + assert expected == actual + + def test_storage_pool_path(): project = "squid" zone = "clam" diff --git a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr.py b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr.py index 1b1d6133aa72..87e98c583446 100644 --- a/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr.py +++ b/packages/google-cloud-backupdr/tests/unit/gapic/backupdr_v1beta/test_backup_dr.py @@ -44,6 +44,7 @@ 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.struct_pb2 as struct_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import google.protobuf.wrappers_pb2 as wrappers_pb2 # type: ignore import google.rpc.status_pb2 as status_pb2 # type: ignore @@ -93,6 +94,18 @@ backupvault_gce, bindingmatchingresource, datasourcereference, + restore_template, + restore_template_common, + restore_template_execution, + restore_verification_plan, + restore_verification_plan_association, +) +from google.cloud.backupdr_v1beta.types import restore_template as gcb_restore_template +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan as gcb_restore_verification_plan, +) +from google.cloud.backupdr_v1beta.types import ( + restore_verification_plan_association as gcb_restore_verification_plan_association, ) CRED_INFO_JSON = { @@ -2723,11 +2736,11 @@ async def test_delete_management_server_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - backupvault.CreateBackupVaultRequest(), + gcb_restore_template.CreateRestoreTemplateRequest(), {}, ], ) -def test_create_backup_vault(request_type, transport: str = "grpc"): +def test_create_restore_template(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2739,23 +2752,23 @@ def test_create_backup_vault(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_backup_vault), "__call__" + type(client.transport.create_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_backup_vault(request) + response = client.create_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.CreateBackupVaultRequest() + request = gcb_restore_template.CreateRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_backup_vault_non_empty_request_with_auto_populated_field(): +def test_create_restore_template_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 = BackupDRClient( @@ -2766,29 +2779,29 @@ def test_create_backup_vault_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 = backupvault.CreateBackupVaultRequest( + request = gcb_restore_template.CreateRestoreTemplateRequest( parent="parent_value", - backup_vault_id="backup_vault_id_value", + restore_template_id="restore_template_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" + type(client.transport.create_restore_template), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_backup_vault(request=request) + client.create_restore_template(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.CreateBackupVaultRequest( + request_msg = gcb_restore_template.CreateRestoreTemplateRequest( parent="parent_value", - backup_vault_id="backup_vault_id_value", + restore_template_id="restore_template_id_value", ) assert args[0] == request_msg -def test_create_backup_vault_use_cached_wrapped_rpc(): +def test_create_restore_template_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: @@ -2803,7 +2816,8 @@ def test_create_backup_vault_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_backup_vault in client._transport._wrapped_methods + client._transport.create_restore_template + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -2811,11 +2825,11 @@ def test_create_backup_vault_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.create_backup_vault] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_restore_template + ] = mock_rpc request = {} - client.create_backup_vault(request) + client.create_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -2825,7 +2839,7 @@ def test_create_backup_vault_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_backup_vault(request) + client.create_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2833,7 +2847,7 @@ def test_create_backup_vault_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_backup_vault_async_use_cached_wrapped_rpc( +async def test_create_restore_template_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -2850,7 +2864,7 @@ async def test_create_backup_vault_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_backup_vault + client._client._transport.create_restore_template in client._client._transport._wrapped_methods ) @@ -2858,11 +2872,11 @@ async def test_create_backup_vault_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_backup_vault + client._client._transport.create_restore_template ] = mock_rpc request = {} - await client.create_backup_vault(request) + await client.create_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -2872,7 +2886,7 @@ async def test_create_backup_vault_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_backup_vault(request) + await client.create_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -2883,11 +2897,13 @@ async def test_create_backup_vault_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.CreateBackupVaultRequest(), + gcb_restore_template.CreateRestoreTemplateRequest(), {}, ], ) -async def test_create_backup_vault_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_restore_template_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -2899,41 +2915,41 @@ async def test_create_backup_vault_async(request_type, transport: str = "grpc_as # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" + type(client.transport.create_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_backup_vault(request) + response = await client.create_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.CreateBackupVaultRequest() + request = gcb_restore_template.CreateRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_backup_vault_field_headers(): +def test_create_restore_template_field_headers(): client = BackupDRClient( 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 = backupvault.CreateBackupVaultRequest() + request = gcb_restore_template.CreateRestoreTemplateRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" + type(client.transport.create_restore_template), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup_vault(request) + client.create_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2949,25 +2965,25 @@ def test_create_backup_vault_field_headers(): @pytest.mark.asyncio -async def test_create_backup_vault_field_headers_async(): +async def test_create_restore_template_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.CreateBackupVaultRequest() + request = gcb_restore_template.CreateRestoreTemplateRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" + type(client.transport.create_restore_template), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_backup_vault(request) + await client.create_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2982,23 +2998,23 @@ async def test_create_backup_vault_field_headers_async(): ) in kw["metadata"] -def test_create_backup_vault_flattened(): +def test_create_restore_template_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" + type(client.transport.create_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_backup_vault( + client.create_restore_template( parent="parent_value", - backup_vault=backupvault.BackupVault(name="name_value"), - backup_vault_id="backup_vault_id_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", ) # Establish that the underlying call was made with the expected @@ -3008,15 +3024,15 @@ def test_create_backup_vault_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].backup_vault - mock_val = backupvault.BackupVault(name="name_value") + arg = args[0].restore_template + mock_val = gcb_restore_template.RestoreTemplate(name="name_value") assert arg == mock_val - arg = args[0].backup_vault_id - mock_val = "backup_vault_id_value" + arg = args[0].restore_template_id + mock_val = "restore_template_id_value" assert arg == mock_val -def test_create_backup_vault_flattened_error(): +def test_create_restore_template_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3024,23 +3040,23 @@ def test_create_backup_vault_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_backup_vault( - backupvault.CreateBackupVaultRequest(), + client.create_restore_template( + gcb_restore_template.CreateRestoreTemplateRequest(), parent="parent_value", - backup_vault=backupvault.BackupVault(name="name_value"), - backup_vault_id="backup_vault_id_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", ) @pytest.mark.asyncio -async def test_create_backup_vault_flattened_async(): +async def test_create_restore_template_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" + type(client.transport.create_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -3050,10 +3066,10 @@ async def test_create_backup_vault_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_backup_vault( + response = await client.create_restore_template( parent="parent_value", - backup_vault=backupvault.BackupVault(name="name_value"), - backup_vault_id="backup_vault_id_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", ) # Establish that the underlying call was made with the expected @@ -3063,16 +3079,16 @@ async def test_create_backup_vault_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].backup_vault - mock_val = backupvault.BackupVault(name="name_value") + arg = args[0].restore_template + mock_val = gcb_restore_template.RestoreTemplate(name="name_value") assert arg == mock_val - arg = args[0].backup_vault_id - mock_val = "backup_vault_id_value" + arg = args[0].restore_template_id + mock_val = "restore_template_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_backup_vault_flattened_error_async(): +async def test_create_restore_template_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3080,22 +3096,22 @@ async def test_create_backup_vault_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.create_backup_vault( - backupvault.CreateBackupVaultRequest(), + await client.create_restore_template( + gcb_restore_template.CreateRestoreTemplateRequest(), parent="parent_value", - backup_vault=backupvault.BackupVault(name="name_value"), - backup_vault_id="backup_vault_id_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", ) @pytest.mark.parametrize( "request_type", [ - backupvault.ListBackupVaultsRequest(), + restore_template.GetRestoreTemplateRequest(), {}, ], ) -def test_list_backup_vaults(request_type, transport: str = "grpc"): +def test_get_restore_template(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3107,28 +3123,34 @@ def test_list_backup_vaults(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" + type(client.transport.get_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.ListBackupVaultsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + call.return_value = restore_template.RestoreTemplate( + name="name_value", + description="description_value", + resource_type="resource_type_value", + state=restore_template.RestoreTemplate.State.CREATING, + etag="etag_value", ) - response = client.list_backup_vaults(request) + response = client.get_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.ListBackupVaultsRequest() + request = restore_template.GetRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupVaultsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, restore_template.RestoreTemplate) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.resource_type == "resource_type_value" + assert response.state == restore_template.RestoreTemplate.State.CREATING + assert response.etag == "etag_value" -def test_list_backup_vaults_non_empty_request_with_auto_populated_field(): +def test_get_restore_template_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 = BackupDRClient( @@ -3139,33 +3161,27 @@ def test_list_backup_vaults_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 = backupvault.ListBackupVaultsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = restore_template.GetRestoreTemplateRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" + type(client.transport.get_restore_template), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_backup_vaults(request=request) + client.get_restore_template(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListBackupVaultsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request_msg = restore_template.GetRestoreTemplateRequest( + name="name_value", ) assert args[0] == request_msg -def test_list_backup_vaults_use_cached_wrapped_rpc(): +def test_get_restore_template_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: @@ -3180,7 +3196,7 @@ def test_list_backup_vaults_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_backup_vaults in client._transport._wrapped_methods + client._transport.get_restore_template in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -3188,16 +3204,16 @@ def test_list_backup_vaults_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_backup_vaults] = ( + client._transport._wrapped_methods[client._transport.get_restore_template] = ( mock_rpc ) request = {} - client.list_backup_vaults(request) + client.get_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backup_vaults(request) + client.get_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3205,7 +3221,7 @@ def test_list_backup_vaults_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_backup_vaults_async_use_cached_wrapped_rpc( +async def test_get_restore_template_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3222,7 +3238,7 @@ async def test_list_backup_vaults_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_backup_vaults + client._client._transport.get_restore_template in client._client._transport._wrapped_methods ) @@ -3230,16 +3246,16 @@ async def test_list_backup_vaults_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_backup_vaults + client._client._transport.get_restore_template ] = mock_rpc request = {} - await client.list_backup_vaults(request) + await client.get_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_backup_vaults(request) + await client.get_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3250,11 +3266,13 @@ async def test_list_backup_vaults_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.ListBackupVaultsRequest(), + restore_template.GetRestoreTemplateRequest(), {}, ], ) -async def test_list_backup_vaults_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_restore_template_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -3266,46 +3284,52 @@ async def test_list_backup_vaults_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" + type(client.transport.get_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListBackupVaultsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + restore_template.RestoreTemplate( + name="name_value", + description="description_value", + resource_type="resource_type_value", + state=restore_template.RestoreTemplate.State.CREATING, + etag="etag_value", ) ) - response = await client.list_backup_vaults(request) + response = await client.get_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.ListBackupVaultsRequest() + request = restore_template.GetRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupVaultsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, restore_template.RestoreTemplate) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.resource_type == "resource_type_value" + assert response.state == restore_template.RestoreTemplate.State.CREATING + assert response.etag == "etag_value" -def test_list_backup_vaults_field_headers(): +def test_get_restore_template_field_headers(): client = BackupDRClient( 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 = backupvault.ListBackupVaultsRequest() + request = restore_template.GetRestoreTemplateRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" + type(client.transport.get_restore_template), "__call__" ) as call: - call.return_value = backupvault.ListBackupVaultsResponse() - client.list_backup_vaults(request) + call.return_value = restore_template.RestoreTemplate() + client.get_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3316,30 +3340,30 @@ def test_list_backup_vaults_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_backup_vaults_field_headers_async(): +async def test_get_restore_template_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.ListBackupVaultsRequest() + request = restore_template.GetRestoreTemplateRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" + type(client.transport.get_restore_template), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListBackupVaultsResponse() + restore_template.RestoreTemplate() ) - await client.list_backup_vaults(request) + await client.get_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3350,37 +3374,37 @@ async def test_list_backup_vaults_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_backup_vaults_flattened(): +def test_get_restore_template_flattened(): client = BackupDRClient( 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_vaults), "__call__" + type(client.transport.get_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.ListBackupVaultsResponse() + call.return_value = restore_template.RestoreTemplate() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_backup_vaults( - parent="parent_value", + client.get_restore_template( + 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_backup_vaults_flattened_error(): +def test_get_restore_template_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3388,45 +3412,45 @@ def test_list_backup_vaults_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backup_vaults( - backupvault.ListBackupVaultsRequest(), - parent="parent_value", + client.get_restore_template( + restore_template.GetRestoreTemplateRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_backup_vaults_flattened_async(): +async def test_get_restore_template_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" + type(client.transport.get_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.ListBackupVaultsResponse() + call.return_value = restore_template.RestoreTemplate() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListBackupVaultsResponse() + restore_template.RestoreTemplate() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_backup_vaults( - parent="parent_value", + response = await client.get_restore_template( + 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_backup_vaults_flattened_error_async(): +async def test_get_restore_template_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3434,223 +3458,20 @@ async def test_list_backup_vaults_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.list_backup_vaults( - backupvault.ListBackupVaultsRequest(), - parent="parent_value", - ) - - -def test_list_backup_vaults_pager(transport_name: str = "grpc"): - client = BackupDRClient( - 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_backup_vaults), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - next_page_token="abc", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[], - next_page_token="def", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_backup_vaults(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, backupvault.BackupVault) for i in results) - - -def test_list_backup_vaults_pages(transport_name: str = "grpc"): - client = BackupDRClient( - 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_backup_vaults), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - next_page_token="abc", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[], - next_page_token="def", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - ), - RuntimeError, - ) - pages = list(client.list_backup_vaults(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_backup_vaults_async_pager(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_vaults), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - next_page_token="abc", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[], - next_page_token="def", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_backup_vaults( - 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, backupvault.BackupVault) for i in responses) - - -@pytest.mark.asyncio -async def test_list_backup_vaults_async_pages(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_vaults), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - next_page_token="abc", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[], - next_page_token="def", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - ], - ), - RuntimeError, + await client.get_restore_template( + restore_template.GetRestoreTemplateRequest(), + name="name_value", ) - pages = [] - async for page_ in (await client.list_backup_vaults(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", [ - backupvault.FetchUsableBackupVaultsRequest(), + restore_template.ListRestoreTemplatesRequest(), {}, ], ) -def test_fetch_usable_backup_vaults(request_type, transport: str = "grpc"): +def test_list_restore_templates(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3662,28 +3483,28 @@ def test_fetch_usable_backup_vaults(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_templates), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.FetchUsableBackupVaultsResponse( + call.return_value = restore_template.ListRestoreTemplatesResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) - response = client.fetch_usable_backup_vaults(request) + response = client.list_restore_templates(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.FetchUsableBackupVaultsRequest() + request = restore_template.ListRestoreTemplatesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchUsableBackupVaultsPager) + assert isinstance(response, pagers.ListRestoreTemplatesPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_fetch_usable_backup_vaults_non_empty_request_with_auto_populated_field(): +def test_list_restore_templates_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 = BackupDRClient( @@ -3694,7 +3515,7 @@ def test_fetch_usable_backup_vaults_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 = backupvault.FetchUsableBackupVaultsRequest( + request = restore_template.ListRestoreTemplatesRequest( parent="parent_value", page_token="page_token_value", filter="filter_value", @@ -3703,15 +3524,15 @@ def test_fetch_usable_backup_vaults_non_empty_request_with_auto_populated_field( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_templates), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.fetch_usable_backup_vaults(request=request) + client.list_restore_templates(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.FetchUsableBackupVaultsRequest( + request_msg = restore_template.ListRestoreTemplatesRequest( parent="parent_value", page_token="page_token_value", filter="filter_value", @@ -3720,7 +3541,7 @@ def test_fetch_usable_backup_vaults_non_empty_request_with_auto_populated_field( assert args[0] == request_msg -def test_fetch_usable_backup_vaults_use_cached_wrapped_rpc(): +def test_list_restore_templates_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: @@ -3735,7 +3556,7 @@ def test_fetch_usable_backup_vaults_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_usable_backup_vaults + client._transport.list_restore_templates in client._transport._wrapped_methods ) @@ -3744,16 +3565,16 @@ def test_fetch_usable_backup_vaults_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.fetch_usable_backup_vaults - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_restore_templates] = ( + mock_rpc + ) request = {} - client.fetch_usable_backup_vaults(request) + client.list_restore_templates(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_usable_backup_vaults(request) + client.list_restore_templates(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3761,7 +3582,7 @@ def test_fetch_usable_backup_vaults_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_fetch_usable_backup_vaults_async_use_cached_wrapped_rpc( +async def test_list_restore_templates_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3778,7 +3599,7 @@ async def test_fetch_usable_backup_vaults_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.fetch_usable_backup_vaults + client._client._transport.list_restore_templates in client._client._transport._wrapped_methods ) @@ -3786,16 +3607,16 @@ async def test_fetch_usable_backup_vaults_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.fetch_usable_backup_vaults + client._client._transport.list_restore_templates ] = mock_rpc request = {} - await client.fetch_usable_backup_vaults(request) + await client.list_restore_templates(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_usable_backup_vaults(request) + await client.list_restore_templates(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3806,11 +3627,11 @@ async def test_fetch_usable_backup_vaults_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.FetchUsableBackupVaultsRequest(), + restore_template.ListRestoreTemplatesRequest(), {}, ], ) -async def test_fetch_usable_backup_vaults_async( +async def test_list_restore_templates_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -3824,46 +3645,46 @@ async def test_fetch_usable_backup_vaults_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_templates), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchUsableBackupVaultsResponse( + restore_template.ListRestoreTemplatesResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) ) - response = await client.fetch_usable_backup_vaults(request) + response = await client.list_restore_templates(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.FetchUsableBackupVaultsRequest() + request = restore_template.ListRestoreTemplatesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchUsableBackupVaultsAsyncPager) + assert isinstance(response, pagers.ListRestoreTemplatesAsyncPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_fetch_usable_backup_vaults_field_headers(): +def test_list_restore_templates_field_headers(): client = BackupDRClient( 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 = backupvault.FetchUsableBackupVaultsRequest() + request = restore_template.ListRestoreTemplatesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_templates), "__call__" ) as call: - call.return_value = backupvault.FetchUsableBackupVaultsResponse() - client.fetch_usable_backup_vaults(request) + call.return_value = restore_template.ListRestoreTemplatesResponse() + client.list_restore_templates(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3879,25 +3700,25 @@ def test_fetch_usable_backup_vaults_field_headers(): @pytest.mark.asyncio -async def test_fetch_usable_backup_vaults_field_headers_async(): +async def test_list_restore_templates_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.FetchUsableBackupVaultsRequest() + request = restore_template.ListRestoreTemplatesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_templates), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchUsableBackupVaultsResponse() + restore_template.ListRestoreTemplatesResponse() ) - await client.fetch_usable_backup_vaults(request) + await client.list_restore_templates(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3912,20 +3733,20 @@ async def test_fetch_usable_backup_vaults_field_headers_async(): ) in kw["metadata"] -def test_fetch_usable_backup_vaults_flattened(): +def test_list_restore_templates_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_templates), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.FetchUsableBackupVaultsResponse() + call.return_value = restore_template.ListRestoreTemplatesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.fetch_usable_backup_vaults( + client.list_restore_templates( parent="parent_value", ) @@ -3938,7 +3759,7 @@ def test_fetch_usable_backup_vaults_flattened(): assert arg == mock_val -def test_fetch_usable_backup_vaults_flattened_error(): +def test_list_restore_templates_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3946,31 +3767,31 @@ def test_fetch_usable_backup_vaults_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_usable_backup_vaults( - backupvault.FetchUsableBackupVaultsRequest(), + client.list_restore_templates( + restore_template.ListRestoreTemplatesRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_fetch_usable_backup_vaults_flattened_async(): +async def test_list_restore_templates_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_templates), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.FetchUsableBackupVaultsResponse() + call.return_value = restore_template.ListRestoreTemplatesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchUsableBackupVaultsResponse() + restore_template.ListRestoreTemplatesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.fetch_usable_backup_vaults( + response = await client.list_restore_templates( parent="parent_value", ) @@ -3984,7 +3805,7 @@ async def test_fetch_usable_backup_vaults_flattened_async(): @pytest.mark.asyncio -async def test_fetch_usable_backup_vaults_flattened_error_async(): +async def test_list_restore_templates_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -3992,13 +3813,13 @@ async def test_fetch_usable_backup_vaults_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.fetch_usable_backup_vaults( - backupvault.FetchUsableBackupVaultsRequest(), + await client.list_restore_templates( + restore_template.ListRestoreTemplatesRequest(), parent="parent_value", ) -def test_fetch_usable_backup_vaults_pager(transport_name: str = "grpc"): +def test_list_restore_templates_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -4006,32 +3827,32 @@ def test_fetch_usable_backup_vaults_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_templates), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), ], next_page_token="abc", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[], + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], next_page_token="def", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), ], next_page_token="ghi", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), ], ), RuntimeError, @@ -4043,9 +3864,7 @@ def test_fetch_usable_backup_vaults_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.fetch_usable_backup_vaults( - request={}, retry=retry, timeout=timeout - ) + pager = client.list_restore_templates(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -4056,10 +3875,10 @@ def test_fetch_usable_backup_vaults_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, backupvault.BackupVault) for i in results) + assert all(isinstance(i, restore_template.RestoreTemplate) for i in results) -def test_fetch_usable_backup_vaults_pages(transport_name: str = "grpc"): +def test_list_restore_templates_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -4067,82 +3886,82 @@ def test_fetch_usable_backup_vaults_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" + type(client.transport.list_restore_templates), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), ], next_page_token="abc", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[], + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], next_page_token="def", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), ], next_page_token="ghi", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), ], ), RuntimeError, ) - pages = list(client.fetch_usable_backup_vaults(request={}).pages) + pages = list(client.list_restore_templates(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_fetch_usable_backup_vaults_async_pager(): +async def test_list_restore_templates_async_pager(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), + type(client.transport.list_restore_templates), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), ], next_page_token="abc", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[], + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], next_page_token="def", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), ], next_page_token="ghi", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), ], ), RuntimeError, ) - async_pager = await client.fetch_usable_backup_vaults( + async_pager = await client.list_restore_templates( request={}, ) assert async_pager.next_page_token == "abc" @@ -4153,51 +3972,51 @@ async def test_fetch_usable_backup_vaults_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, backupvault.BackupVault) for i in responses) + assert all(isinstance(i, restore_template.RestoreTemplate) for i in responses) @pytest.mark.asyncio -async def test_fetch_usable_backup_vaults_async_pages(): +async def test_list_restore_templates_async_pages(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), + type(client.transport.list_restore_templates), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), ], next_page_token="abc", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[], + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], next_page_token="def", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), ], next_page_token="ghi", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), ], ), RuntimeError, ) pages = [] - async for page_ in (await client.fetch_usable_backup_vaults(request={})).pages: + async for page_ in (await client.list_restore_templates(request={})).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -4206,11 +4025,11 @@ async def test_fetch_usable_backup_vaults_async_pages(): @pytest.mark.parametrize( "request_type", [ - backupvault.GetBackupVaultRequest(), + gcb_restore_template.UpdateRestoreTemplateRequest(), {}, ], ) -def test_get_backup_vault(request_type, transport: str = "grpc"): +def test_update_restore_template(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4221,51 +4040,24 @@ def test_get_backup_vault(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.get_backup_vault), "__call__") as call: + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.BackupVault( - name="name_value", - description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, - deletable=True, - etag="etag_value", - state=backupvault.BackupVault.State.CREATING, - backup_count=1278, - service_account="service_account_value", - total_stored_bytes=1946, - uid="uid_value", - access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, - ) - response = client.get_backup_vault(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.GetBackupVaultRequest() + request = gcb_restore_template.UpdateRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupvault.BackupVault) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( - response.backup_retention_inheritance - == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION - ) - assert response.deletable is True - assert response.etag == "etag_value" - assert response.state == backupvault.BackupVault.State.CREATING - assert response.backup_count == 1278 - assert response.service_account == "service_account_value" - assert response.total_stored_bytes == 1946 - assert response.uid == "uid_value" - assert ( - response.access_restriction - == backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT - ) + assert isinstance(response, future.Future) -def test_get_backup_vault_non_empty_request_with_auto_populated_field(): +def test_update_restore_template_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 = BackupDRClient( @@ -4276,25 +4068,23 @@ def test_get_backup_vault_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 = backupvault.GetBackupVaultRequest( - name="name_value", - ) + request = gcb_restore_template.UpdateRestoreTemplateRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_backup_vault(request=request) + client.update_restore_template(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetBackupVaultRequest( - name="name_value", - ) + request_msg = gcb_restore_template.UpdateRestoreTemplateRequest() assert args[0] == request_msg -def test_get_backup_vault_use_cached_wrapped_rpc(): +def test_update_restore_template_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: @@ -4308,23 +4098,31 @@ def test_get_backup_vault_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup_vault in client._transport._wrapped_methods + assert ( + client._transport.update_restore_template + 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_vault] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.update_restore_template + ] = mock_rpc request = {} - client.get_backup_vault(request) + client.update_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup_vault(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.update_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4332,7 +4130,7 @@ def test_get_backup_vault_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_backup_vault_async_use_cached_wrapped_rpc( +async def test_update_restore_template_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4349,7 +4147,7 @@ async def test_get_backup_vault_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_backup_vault + client._client._transport.update_restore_template in client._client._transport._wrapped_methods ) @@ -4357,16 +4155,21 @@ async def test_get_backup_vault_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_backup_vault + client._client._transport.update_restore_template ] = mock_rpc request = {} - await client.get_backup_vault(request) + await client.update_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_backup_vault(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() + + await client.update_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4377,11 +4180,13 @@ async def test_get_backup_vault_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.GetBackupVaultRequest(), + gcb_restore_template.UpdateRestoreTemplateRequest(), {}, ], ) -async def test_get_backup_vault_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_restore_template_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4392,67 +4197,42 @@ async def test_get_backup_vault_async(request_type, transport: str = "grpc_async request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.BackupVault( - name="name_value", - description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, - deletable=True, - etag="etag_value", - state=backupvault.BackupVault.State.CREATING, - backup_count=1278, - service_account="service_account_value", - total_stored_bytes=1946, - uid="uid_value", - access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_backup_vault(request) + response = await client.update_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.GetBackupVaultRequest() + request = gcb_restore_template.UpdateRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupvault.BackupVault) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( - response.backup_retention_inheritance - == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION - ) - assert response.deletable is True - assert response.etag == "etag_value" - assert response.state == backupvault.BackupVault.State.CREATING - assert response.backup_count == 1278 - assert response.service_account == "service_account_value" - assert response.total_stored_bytes == 1946 - assert response.uid == "uid_value" - assert ( - response.access_restriction - == backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT - ) + assert isinstance(response, future.Future) -def test_get_backup_vault_field_headers(): +def test_update_restore_template_field_headers(): client = BackupDRClient( 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 = backupvault.GetBackupVaultRequest() + request = gcb_restore_template.UpdateRestoreTemplateRequest() - request.name = "name_value" + request.restore_template.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: - call.return_value = backupvault.BackupVault() - client.get_backup_vault(request) + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4463,28 +4243,30 @@ def test_get_backup_vault_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "restore_template.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_backup_vault_field_headers_async(): +async def test_update_restore_template_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.GetBackupVaultRequest() + request = gcb_restore_template.UpdateRestoreTemplateRequest() - request.name = "name_value" + request.restore_template.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.BackupVault() + operations_pb2.Operation(name="operations/op") ) - await client.get_backup_vault(request) + await client.update_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4495,35 +4277,41 @@ async def test_get_backup_vault_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "restore_template.name=name_value", ) in kw["metadata"] -def test_get_backup_vault_flattened(): +def test_update_restore_template_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.BackupVault() + 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.get_backup_vault( - name="name_value", + client.update_restore_template( + restore_template=gcb_restore_template.RestoreTemplate(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].restore_template + mock_val = gcb_restore_template.RestoreTemplate(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_get_backup_vault_flattened_error(): +def test_update_restore_template_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4531,43 +4319,50 @@ def test_get_backup_vault_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_backup_vault( - backupvault.GetBackupVaultRequest(), - name="name_value", + client.update_restore_template( + gcb_restore_template.UpdateRestoreTemplateRequest(), + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_get_backup_vault_flattened_async(): +async def test_update_restore_template_flattened_async(): client = BackupDRAsyncClient( 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_vault), "__call__") as call: + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.BackupVault() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.BackupVault() + 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.get_backup_vault( - name="name_value", + response = await client.update_restore_template( + restore_template=gcb_restore_template.RestoreTemplate(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].restore_template + mock_val = gcb_restore_template.RestoreTemplate(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_get_backup_vault_flattened_error_async(): +async def test_update_restore_template_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4575,20 +4370,21 @@ async def test_get_backup_vault_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.get_backup_vault( - backupvault.GetBackupVaultRequest(), - name="name_value", + await client.update_restore_template( + gcb_restore_template.UpdateRestoreTemplateRequest(), + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - backupvault.UpdateBackupVaultRequest(), + restore_template.DeleteRestoreTemplateRequest(), {}, ], ) -def test_update_backup_vault(request_type, transport: str = "grpc"): +def test_delete_restore_template(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4600,23 +4396,23 @@ def test_update_backup_vault(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_backup_vault), "__call__" + type(client.transport.delete_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_backup_vault(request) + response = client.delete_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.UpdateBackupVaultRequest() + request = restore_template.DeleteRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_backup_vault_non_empty_request_with_auto_populated_field(): +def test_delete_restore_template_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 = BackupDRClient( @@ -4627,23 +4423,27 @@ def test_update_backup_vault_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 = backupvault.UpdateBackupVaultRequest() + request = restore_template.DeleteRestoreTemplateRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_vault), "__call__" + type(client.transport.delete_restore_template), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_backup_vault(request=request) + client.delete_restore_template(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateBackupVaultRequest() + request_msg = restore_template.DeleteRestoreTemplateRequest( + name="name_value", + ) assert args[0] == request_msg -def test_update_backup_vault_use_cached_wrapped_rpc(): +def test_delete_restore_template_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: @@ -4658,7 +4458,8 @@ def test_update_backup_vault_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_backup_vault in client._transport._wrapped_methods + client._transport.delete_restore_template + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -4666,11 +4467,11 @@ def test_update_backup_vault_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_backup_vault] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_restore_template + ] = mock_rpc request = {} - client.update_backup_vault(request) + client.delete_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4680,7 +4481,7 @@ def test_update_backup_vault_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_backup_vault(request) + client.delete_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4688,7 +4489,7 @@ def test_update_backup_vault_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_backup_vault_async_use_cached_wrapped_rpc( +async def test_delete_restore_template_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4705,7 +4506,7 @@ async def test_update_backup_vault_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_backup_vault + client._client._transport.delete_restore_template in client._client._transport._wrapped_methods ) @@ -4713,11 +4514,11 @@ async def test_update_backup_vault_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_backup_vault + client._client._transport.delete_restore_template ] = mock_rpc request = {} - await client.update_backup_vault(request) + await client.delete_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -4727,7 +4528,7 @@ async def test_update_backup_vault_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_backup_vault(request) + await client.delete_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4738,11 +4539,13 @@ async def test_update_backup_vault_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.UpdateBackupVaultRequest(), + restore_template.DeleteRestoreTemplateRequest(), {}, ], ) -async def test_update_backup_vault_async(request_type, transport: str = "grpc_asyncio"): +async def test_delete_restore_template_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -4754,41 +4557,41 @@ async def test_update_backup_vault_async(request_type, transport: str = "grpc_as # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_vault), "__call__" + type(client.transport.delete_restore_template), "__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.update_backup_vault(request) + response = await client.delete_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.UpdateBackupVaultRequest() + request = restore_template.DeleteRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_backup_vault_field_headers(): +def test_delete_restore_template_field_headers(): client = BackupDRClient( 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 = backupvault.UpdateBackupVaultRequest() + request = restore_template.DeleteRestoreTemplateRequest() - request.backup_vault.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_backup_vault), "__call__" + type(client.transport.delete_restore_template), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup_vault(request) + client.delete_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4799,30 +4602,30 @@ def test_update_backup_vault_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup_vault.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_backup_vault_field_headers_async(): +async def test_delete_restore_template_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.UpdateBackupVaultRequest() + request = restore_template.DeleteRestoreTemplateRequest() - request.backup_vault.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_backup_vault), "__call__" + type(client.transport.delete_restore_template), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_backup_vault(request) + await client.delete_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4833,41 +4636,37 @@ async def test_update_backup_vault_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup_vault.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_backup_vault_flattened(): +def test_delete_restore_template_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_vault), "__call__" + type(client.transport.delete_restore_template), "__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.update_backup_vault( - backup_vault=backupvault.BackupVault(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_restore_template( + 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].backup_vault - mock_val = backupvault.BackupVault(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_backup_vault_flattened_error(): +def test_delete_restore_template_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4875,22 +4674,21 @@ def test_update_backup_vault_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_backup_vault( - backupvault.UpdateBackupVaultRequest(), - backup_vault=backupvault.BackupVault(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_restore_template( + restore_template.DeleteRestoreTemplateRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_backup_vault_flattened_async(): +async def test_delete_restore_template_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_vault), "__call__" + type(client.transport.delete_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -4900,25 +4698,21 @@ async def test_update_backup_vault_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_backup_vault( - backup_vault=backupvault.BackupVault(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.delete_restore_template( + 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].backup_vault - mock_val = backupvault.BackupVault(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_backup_vault_flattened_error_async(): +async def test_delete_restore_template_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4926,21 +4720,20 @@ async def test_update_backup_vault_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_backup_vault( - backupvault.UpdateBackupVaultRequest(), - backup_vault=backupvault.BackupVault(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.delete_restore_template( + restore_template.DeleteRestoreTemplateRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - backupvault.DeleteBackupVaultRequest(), + restore_template.RunRestoreTemplateRequest(), {}, ], ) -def test_delete_backup_vault(request_type, transport: str = "grpc"): +def test_run_restore_template(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4952,23 +4745,23 @@ def test_delete_backup_vault(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_backup_vault), "__call__" + type(client.transport.run_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_backup_vault(request) + response = client.run_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.DeleteBackupVaultRequest() + request = restore_template.RunRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_delete_backup_vault_non_empty_request_with_auto_populated_field(): +def test_run_restore_template_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 = BackupDRClient( @@ -4979,29 +4772,29 @@ def test_delete_backup_vault_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 = backupvault.DeleteBackupVaultRequest( + request = restore_template.RunRestoreTemplateRequest( name="name_value", - etag="etag_value", + backup="backup_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_backup_vault), "__call__" + type(client.transport.run_restore_template), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_backup_vault(request=request) + client.run_restore_template(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.DeleteBackupVaultRequest( + request_msg = restore_template.RunRestoreTemplateRequest( name="name_value", - etag="etag_value", + backup="backup_value", ) assert args[0] == request_msg -def test_delete_backup_vault_use_cached_wrapped_rpc(): +def test_run_restore_template_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: @@ -5016,7 +4809,7 @@ def test_delete_backup_vault_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_backup_vault in client._transport._wrapped_methods + client._transport.run_restore_template in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5024,11 +4817,11 @@ def test_delete_backup_vault_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.delete_backup_vault] = ( + client._transport._wrapped_methods[client._transport.run_restore_template] = ( mock_rpc ) request = {} - client.delete_backup_vault(request) + client.run_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5038,7 +4831,7 @@ def test_delete_backup_vault_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_backup_vault(request) + client.run_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5046,7 +4839,7 @@ def test_delete_backup_vault_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_backup_vault_async_use_cached_wrapped_rpc( +async def test_run_restore_template_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5063,7 +4856,7 @@ async def test_delete_backup_vault_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_backup_vault + client._client._transport.run_restore_template in client._client._transport._wrapped_methods ) @@ -5071,11 +4864,11 @@ async def test_delete_backup_vault_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_backup_vault + client._client._transport.run_restore_template ] = mock_rpc request = {} - await client.delete_backup_vault(request) + await client.run_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5085,7 +4878,7 @@ async def test_delete_backup_vault_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.delete_backup_vault(request) + await client.run_restore_template(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5096,11 +4889,13 @@ async def test_delete_backup_vault_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.DeleteBackupVaultRequest(), + restore_template.RunRestoreTemplateRequest(), {}, ], ) -async def test_delete_backup_vault_async(request_type, transport: str = "grpc_asyncio"): +async def test_run_restore_template_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5112,41 +4907,41 @@ async def test_delete_backup_vault_async(request_type, transport: str = "grpc_as # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_backup_vault), "__call__" + type(client.transport.run_restore_template), "__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_backup_vault(request) + response = await client.run_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.DeleteBackupVaultRequest() + request = restore_template.RunRestoreTemplateRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_delete_backup_vault_field_headers(): +def test_run_restore_template_field_headers(): client = BackupDRClient( 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 = backupvault.DeleteBackupVaultRequest() + request = restore_template.RunRestoreTemplateRequest() 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_vault), "__call__" + type(client.transport.run_restore_template), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup_vault(request) + client.run_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5162,25 +4957,25 @@ def test_delete_backup_vault_field_headers(): @pytest.mark.asyncio -async def test_delete_backup_vault_field_headers_async(): +async def test_run_restore_template_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.DeleteBackupVaultRequest() + request = restore_template.RunRestoreTemplateRequest() 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_vault), "__call__" + type(client.transport.run_restore_template), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_backup_vault(request) + await client.run_restore_template(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5195,20 +4990,20 @@ async def test_delete_backup_vault_field_headers_async(): ) in kw["metadata"] -def test_delete_backup_vault_flattened(): +def test_run_restore_template_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_backup_vault), "__call__" + type(client.transport.run_restore_template), "__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_backup_vault( + client.run_restore_template( name="name_value", ) @@ -5221,7 +5016,7 @@ def test_delete_backup_vault_flattened(): assert arg == mock_val -def test_delete_backup_vault_flattened_error(): +def test_run_restore_template_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5229,21 +5024,21 @@ def test_delete_backup_vault_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_backup_vault( - backupvault.DeleteBackupVaultRequest(), + client.run_restore_template( + restore_template.RunRestoreTemplateRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_backup_vault_flattened_async(): +async def test_run_restore_template_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_backup_vault), "__call__" + type(client.transport.run_restore_template), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -5253,7 +5048,7 @@ async def test_delete_backup_vault_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_backup_vault( + response = await client.run_restore_template( name="name_value", ) @@ -5267,7 +5062,7 @@ async def test_delete_backup_vault_flattened_async(): @pytest.mark.asyncio -async def test_delete_backup_vault_flattened_error_async(): +async def test_run_restore_template_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5275,8 +5070,8 @@ async def test_delete_backup_vault_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.delete_backup_vault( - backupvault.DeleteBackupVaultRequest(), + await client.run_restore_template( + restore_template.RunRestoreTemplateRequest(), name="name_value", ) @@ -5284,11 +5079,11 @@ async def test_delete_backup_vault_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - backupvault.ListDataSourcesRequest(), + restore_template_execution.GetRestoreTemplateExecutionRequest(), {}, ], ) -def test_list_data_sources(request_type, transport: str = "grpc"): +def test_get_restore_template_execution(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5300,28 +5095,43 @@ def test_list_data_sources(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), "__call__" + type(client.transport.get_restore_template_execution), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.ListDataSourcesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + call.return_value = restore_template_execution.RestoreTemplateExecution( + name="name_value", + resource_type="resource_type_value", + type_=restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED, + phase=restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING, + state=restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING, ) - response = client.list_data_sources(request) + response = client.get_restore_template_execution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.ListDataSourcesRequest() + request = restore_template_execution.GetRestoreTemplateExecutionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourcesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, restore_template_execution.RestoreTemplateExecution) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert ( + response.type_ + == restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED + ) + assert ( + response.phase + == restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING + ) + assert ( + response.state + == restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING + ) -def test_list_data_sources_non_empty_request_with_auto_populated_field(): +def test_get_restore_template_execution_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 = BackupDRClient( @@ -5332,33 +5142,27 @@ def test_list_data_sources_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 = backupvault.ListDataSourcesRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = restore_template_execution.GetRestoreTemplateExecutionRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), "__call__" + type(client.transport.get_restore_template_execution), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_data_sources(request=request) + client.get_restore_template_execution(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListDataSourcesRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request_msg = restore_template_execution.GetRestoreTemplateExecutionRequest( + name="name_value", ) assert args[0] == request_msg -def test_list_data_sources_use_cached_wrapped_rpc(): +def test_get_restore_template_execution_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: @@ -5372,23 +5176,26 @@ def test_list_data_sources_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_data_sources in client._transport._wrapped_methods + assert ( + client._transport.get_restore_template_execution + 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_data_sources] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.get_restore_template_execution + ] = mock_rpc request = {} - client.list_data_sources(request) + client.get_restore_template_execution(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_sources(request) + client.get_restore_template_execution(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5396,7 +5203,7 @@ def test_list_data_sources_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_data_sources_async_use_cached_wrapped_rpc( +async def test_get_restore_template_execution_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5413,7 +5220,7 @@ async def test_list_data_sources_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_data_sources + client._client._transport.get_restore_template_execution in client._client._transport._wrapped_methods ) @@ -5421,16 +5228,16 @@ async def test_list_data_sources_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_data_sources + client._client._transport.get_restore_template_execution ] = mock_rpc request = {} - await client.list_data_sources(request) + await client.get_restore_template_execution(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_data_sources(request) + await client.get_restore_template_execution(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5441,11 +5248,13 @@ async def test_list_data_sources_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.ListDataSourcesRequest(), + restore_template_execution.GetRestoreTemplateExecutionRequest(), {}, ], ) -async def test_list_data_sources_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_restore_template_execution_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -5457,46 +5266,61 @@ async def test_list_data_sources_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.list_data_sources), "__call__" + type(client.transport.get_restore_template_execution), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListDataSourcesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + restore_template_execution.RestoreTemplateExecution( + name="name_value", + resource_type="resource_type_value", + type_=restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED, + phase=restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING, + state=restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING, ) ) - response = await client.list_data_sources(request) + response = await client.get_restore_template_execution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.ListDataSourcesRequest() + request = restore_template_execution.GetRestoreTemplateExecutionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourcesAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, restore_template_execution.RestoreTemplateExecution) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert ( + response.type_ + == restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED + ) + assert ( + response.phase + == restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING + ) + assert ( + response.state + == restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING + ) -def test_list_data_sources_field_headers(): +def test_get_restore_template_execution_field_headers(): client = BackupDRClient( 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 = backupvault.ListDataSourcesRequest() + request = restore_template_execution.GetRestoreTemplateExecutionRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), "__call__" + type(client.transport.get_restore_template_execution), "__call__" ) as call: - call.return_value = backupvault.ListDataSourcesResponse() - client.list_data_sources(request) + call.return_value = restore_template_execution.RestoreTemplateExecution() + client.get_restore_template_execution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5507,30 +5331,30 @@ def test_list_data_sources_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_data_sources_field_headers_async(): +async def test_get_restore_template_execution_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.ListDataSourcesRequest() + request = restore_template_execution.GetRestoreTemplateExecutionRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), "__call__" + type(client.transport.get_restore_template_execution), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListDataSourcesResponse() + restore_template_execution.RestoreTemplateExecution() ) - await client.list_data_sources(request) + await client.get_restore_template_execution(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5541,37 +5365,37 @@ async def test_list_data_sources_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_data_sources_flattened(): +def test_get_restore_template_execution_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), "__call__" + type(client.transport.get_restore_template_execution), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.ListDataSourcesResponse() + call.return_value = restore_template_execution.RestoreTemplateExecution() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_data_sources( - parent="parent_value", + client.get_restore_template_execution( + 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_data_sources_flattened_error(): +def test_get_restore_template_execution_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5579,45 +5403,45 @@ def test_list_data_sources_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_data_sources( - backupvault.ListDataSourcesRequest(), - parent="parent_value", + client.get_restore_template_execution( + restore_template_execution.GetRestoreTemplateExecutionRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_data_sources_flattened_async(): +async def test_get_restore_template_execution_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), "__call__" + type(client.transport.get_restore_template_execution), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.ListDataSourcesResponse() + call.return_value = restore_template_execution.RestoreTemplateExecution() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListDataSourcesResponse() + restore_template_execution.RestoreTemplateExecution() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_data_sources( - parent="parent_value", + response = await client.get_restore_template_execution( + 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_data_sources_flattened_error_async(): +async def test_get_restore_template_execution_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5625,58 +5449,423 @@ async def test_list_data_sources_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.list_data_sources( - backupvault.ListDataSourcesRequest(), - parent="parent_value", + await client.get_restore_template_execution( + restore_template_execution.GetRestoreTemplateExecutionRequest(), + name="name_value", ) -def test_list_data_sources_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + restore_template_execution.ListRestoreTemplateExecutionsRequest(), + {}, + ], +) +def test_list_restore_template_executions(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), "__call__" + type(client.transport.list_restore_template_executions), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), - backupvault.DataSource(), - ], - next_page_token="abc", - ), - backupvault.ListDataSourcesResponse( - data_sources=[], - next_page_token="def", - ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - ], - next_page_token="ghi", - ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), - ], - ), - RuntimeError, + # Designate an appropriate return value for the call. + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) + response = client.list_restore_template_executions(request) - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_data_sources(request={}, retry=retry, timeout=timeout) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_template_execution.ListRestoreTemplateExecutionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreTemplateExecutionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_restore_template_executions_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 = BackupDRClient( + 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest( + 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_restore_template_executions), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_restore_template_executions(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.ListRestoreTemplateExecutionsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_restore_template_executions_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 = BackupDRClient( + 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_restore_template_executions + 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_restore_template_executions + ] = mock_rpc + request = {} + client.list_restore_template_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_restore_template_executions(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_restore_template_executions_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 = BackupDRAsyncClient( + 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_restore_template_executions + 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_restore_template_executions + ] = mock_rpc + + request = {} + await client.list_restore_template_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_restore_template_executions(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", + [ + restore_template_execution.ListRestoreTemplateExecutionsRequest(), + {}, + ], +) +async def test_list_restore_template_executions_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + 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_restore_template_executions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_restore_template_executions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = restore_template_execution.ListRestoreTemplateExecutionsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreTemplateExecutionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_restore_template_executions_field_headers(): + client = BackupDRClient( + 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + client.list_restore_template_executions(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_restore_template_executions_field_headers_async(): + client = BackupDRAsyncClient( + 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 = restore_template_execution.ListRestoreTemplateExecutionsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + await client.list_restore_template_executions(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_restore_template_executions_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_restore_template_executions( + 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_restore_template_executions_flattened_error(): + client = BackupDRClient( + 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_restore_template_executions( + restore_template_execution.ListRestoreTemplateExecutionsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_restore_template_executions_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_restore_template_executions( + 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_restore_template_executions_flattened_error_async(): + client = BackupDRAsyncClient( + 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_restore_template_executions( + restore_template_execution.ListRestoreTemplateExecutionsRequest(), + parent="parent_value", + ) + + +def test_list_restore_template_executions_pager(transport_name: str = "grpc"): + client = BackupDRClient( + 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_restore_template_executions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="abc", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], + next_page_token="def", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + ], + next_page_token="ghi", + ), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_restore_template_executions( + request={}, retry=retry, timeout=timeout + ) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -5687,10 +5876,13 @@ def test_list_data_sources_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, backupvault.DataSource) for i in results) + assert all( + isinstance(i, restore_template_execution.RestoreTemplateExecution) + for i in results + ) -def test_list_data_sources_pages(transport_name: str = "grpc"): +def test_list_restore_template_executions_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -5698,82 +5890,82 @@ def test_list_data_sources_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), "__call__" + type(client.transport.list_restore_template_executions), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), - backupvault.DataSource(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="abc", ), - backupvault.ListDataSourcesResponse( - data_sources=[], + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], next_page_token="def", ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="ghi", ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], ), RuntimeError, ) - pages = list(client.list_data_sources(request={}).pages) + pages = list(client.list_restore_template_executions(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_data_sources_async_pager(): +async def test_list_restore_template_executions_async_pager(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), + type(client.transport.list_restore_template_executions), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), - backupvault.DataSource(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="abc", ), - backupvault.ListDataSourcesResponse( - data_sources=[], + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], next_page_token="def", ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="ghi", ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], ), RuntimeError, ) - async_pager = await client.list_data_sources( + async_pager = await client.list_restore_template_executions( request={}, ) assert async_pager.next_page_token == "abc" @@ -5784,51 +5976,56 @@ async def test_list_data_sources_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, backupvault.DataSource) for i in responses) + assert all( + isinstance(i, restore_template_execution.RestoreTemplateExecution) + for i in responses + ) @pytest.mark.asyncio -async def test_list_data_sources_async_pages(): +async def test_list_restore_template_executions_async_pages(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_sources), + type(client.transport.list_restore_template_executions), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), - backupvault.DataSource(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="abc", ), - backupvault.ListDataSourcesResponse( - data_sources=[], + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], next_page_token="def", ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="ghi", ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], ), RuntimeError, ) pages = [] - async for page_ in (await client.list_data_sources(request={})).pages: + async for page_ in ( + await client.list_restore_template_executions(request={}) + ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -5837,11 +6034,11 @@ async def test_list_data_sources_async_pages(): @pytest.mark.parametrize( "request_type", [ - backupvault.GetDataSourceRequest(), + restore_template_execution.TriggerRestoreCleanupRequest(), {}, ], ) -def test_get_data_source(request_type, transport: str = "grpc"): +def test_trigger_restore_cleanup(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5852,37 +6049,24 @@ def test_get_data_source(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.get_data_source), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.DataSource( - name="name_value", - state=backupvault.DataSource.State.CREATING, - backup_count=1278, - etag="etag_value", - total_stored_bytes=1946, - config_state=backupvault.BackupConfigState.ACTIVE, - backup_blocked_by_vault_access_restriction=True, - ) - response = client.get_data_source(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.trigger_restore_cleanup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.GetDataSourceRequest() + request = restore_template_execution.TriggerRestoreCleanupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupvault.DataSource) - assert response.name == "name_value" - assert response.state == backupvault.DataSource.State.CREATING - assert response.backup_count == 1278 - assert response.etag == "etag_value" - assert response.total_stored_bytes == 1946 - assert response.config_state == backupvault.BackupConfigState.ACTIVE - assert response.backup_blocked_by_vault_access_restriction is True + assert isinstance(response, future.Future) -def test_get_data_source_non_empty_request_with_auto_populated_field(): +def test_trigger_restore_cleanup_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 = BackupDRClient( @@ -5893,25 +6077,27 @@ def test_get_data_source_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 = backupvault.GetDataSourceRequest( + request = restore_template_execution.TriggerRestoreCleanupRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_data_source(request=request) + client.trigger_restore_cleanup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetDataSourceRequest( + request_msg = restore_template_execution.TriggerRestoreCleanupRequest( name="name_value", ) assert args[0] == request_msg -def test_get_data_source_use_cached_wrapped_rpc(): +def test_trigger_restore_cleanup_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: @@ -5925,21 +6111,31 @@ def test_get_data_source_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_data_source in client._transport._wrapped_methods + assert ( + client._transport.trigger_restore_cleanup + 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_data_source] = mock_rpc + client._transport._wrapped_methods[ + client._transport.trigger_restore_cleanup + ] = mock_rpc request = {} - client.get_data_source(request) + client.trigger_restore_cleanup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_source(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.trigger_restore_cleanup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5947,7 +6143,7 @@ def test_get_data_source_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_data_source_async_use_cached_wrapped_rpc( +async def test_trigger_restore_cleanup_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5964,7 +6160,7 @@ async def test_get_data_source_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_data_source + client._client._transport.trigger_restore_cleanup in client._client._transport._wrapped_methods ) @@ -5972,16 +6168,21 @@ async def test_get_data_source_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_data_source + client._client._transport.trigger_restore_cleanup ] = mock_rpc request = {} - await client.get_data_source(request) + await client.trigger_restore_cleanup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_data_source(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() + + await client.trigger_restore_cleanup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5992,11 +6193,13 @@ async def test_get_data_source_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.GetDataSourceRequest(), + restore_template_execution.TriggerRestoreCleanupRequest(), {}, ], ) -async def test_get_data_source_async(request_type, transport: str = "grpc_asyncio"): +async def test_trigger_restore_cleanup_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6007,53 +6210,42 @@ async def test_get_data_source_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.get_data_source), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.DataSource( - name="name_value", - state=backupvault.DataSource.State.CREATING, - backup_count=1278, - etag="etag_value", - total_stored_bytes=1946, - config_state=backupvault.BackupConfigState.ACTIVE, - backup_blocked_by_vault_access_restriction=True, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_data_source(request) + response = await client.trigger_restore_cleanup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.GetDataSourceRequest() + request = restore_template_execution.TriggerRestoreCleanupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupvault.DataSource) - assert response.name == "name_value" - assert response.state == backupvault.DataSource.State.CREATING - assert response.backup_count == 1278 - assert response.etag == "etag_value" - assert response.total_stored_bytes == 1946 - assert response.config_state == backupvault.BackupConfigState.ACTIVE - assert response.backup_blocked_by_vault_access_restriction is True + assert isinstance(response, future.Future) -def test_get_data_source_field_headers(): +def test_trigger_restore_cleanup_field_headers(): client = BackupDRClient( 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 = backupvault.GetDataSourceRequest() + request = restore_template_execution.TriggerRestoreCleanupRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: - call.return_value = backupvault.DataSource() - client.get_data_source(request) + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_restore_cleanup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6069,23 +6261,25 @@ def test_get_data_source_field_headers(): @pytest.mark.asyncio -async def test_get_data_source_field_headers_async(): +async def test_trigger_restore_cleanup_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.GetDataSourceRequest() + request = restore_template_execution.TriggerRestoreCleanupRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.DataSource() + operations_pb2.Operation(name="operations/op") ) - await client.get_data_source(request) + await client.trigger_restore_cleanup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6100,18 +6294,20 @@ async def test_get_data_source_field_headers_async(): ) in kw["metadata"] -def test_get_data_source_flattened(): +def test_trigger_restore_cleanup_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.DataSource() + 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.get_data_source( + client.trigger_restore_cleanup( name="name_value", ) @@ -6124,7 +6320,7 @@ def test_get_data_source_flattened(): assert arg == mock_val -def test_get_data_source_flattened_error(): +def test_trigger_restore_cleanup_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6132,29 +6328,31 @@ def test_get_data_source_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_source( - backupvault.GetDataSourceRequest(), + client.trigger_restore_cleanup( + restore_template_execution.TriggerRestoreCleanupRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_data_source_flattened_async(): +async def test_trigger_restore_cleanup_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.DataSource() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.DataSource() + 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.get_data_source( + response = await client.trigger_restore_cleanup( name="name_value", ) @@ -6168,7 +6366,7 @@ async def test_get_data_source_flattened_async(): @pytest.mark.asyncio -async def test_get_data_source_flattened_error_async(): +async def test_trigger_restore_cleanup_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6176,8 +6374,8 @@ async def test_get_data_source_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.get_data_source( - backupvault.GetDataSourceRequest(), + await client.trigger_restore_cleanup( + restore_template_execution.TriggerRestoreCleanupRequest(), name="name_value", ) @@ -6185,11 +6383,11 @@ async def test_get_data_source_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - backupvault.UpdateDataSourceRequest(), + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), {}, ], ) -def test_update_data_source(request_type, transport: str = "grpc"): +def test_create_restore_verification_plan(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6201,23 +6399,23 @@ def test_update_data_source(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_data_source), "__call__" + type(client.transport.create_restore_verification_plan), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_data_source(request) + response = client.create_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.UpdateDataSourceRequest() + request = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_data_source_non_empty_request_with_auto_populated_field(): +def test_create_restore_verification_plan_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 = BackupDRClient( @@ -6228,23 +6426,31 @@ def test_update_data_source_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 = backupvault.UpdateDataSourceRequest() + request = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_source), "__call__" + type(client.transport.create_restore_verification_plan), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_data_source(request=request) + client.create_restore_verification_plan(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateDataSourceRequest() + request_msg = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest( + parent="parent_value", + restore_verification_plan_id="restore_verification_plan_id_value", + ) + ) assert args[0] == request_msg -def test_update_data_source_use_cached_wrapped_rpc(): +def test_create_restore_verification_plan_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: @@ -6259,7 +6465,8 @@ def test_update_data_source_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_data_source in client._transport._wrapped_methods + client._transport.create_restore_verification_plan + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6267,11 +6474,11 @@ def test_update_data_source_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_data_source] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_restore_verification_plan + ] = mock_rpc request = {} - client.update_data_source(request) + client.create_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6281,7 +6488,7 @@ def test_update_data_source_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_data_source(request) + client.create_restore_verification_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6289,7 +6496,7 @@ def test_update_data_source_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_data_source_async_use_cached_wrapped_rpc( +async def test_create_restore_verification_plan_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6306,7 +6513,7 @@ async def test_update_data_source_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_data_source + client._client._transport.create_restore_verification_plan in client._client._transport._wrapped_methods ) @@ -6314,11 +6521,11 @@ async def test_update_data_source_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_data_source + client._client._transport.create_restore_verification_plan ] = mock_rpc request = {} - await client.update_data_source(request) + await client.create_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6328,7 +6535,7 @@ async def test_update_data_source_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_data_source(request) + await client.create_restore_verification_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6339,11 +6546,13 @@ async def test_update_data_source_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.UpdateDataSourceRequest(), + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), {}, ], ) -async def test_update_data_source_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_restore_verification_plan_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6355,41 +6564,41 @@ async def test_update_data_source_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_source), "__call__" + type(client.transport.create_restore_verification_plan), "__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.update_data_source(request) + response = await client.create_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.UpdateDataSourceRequest() + request = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_data_source_field_headers(): +def test_create_restore_verification_plan_field_headers(): client = BackupDRClient( 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 = backupvault.UpdateDataSourceRequest() + request = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() - request.data_source.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_data_source), "__call__" + type(client.transport.create_restore_verification_plan), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_data_source(request) + client.create_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6400,30 +6609,30 @@ def test_update_data_source_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_source.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_data_source_field_headers_async(): +async def test_create_restore_verification_plan_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.UpdateDataSourceRequest() + request = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() - request.data_source.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_data_source), "__call__" + type(client.transport.create_restore_verification_plan), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_data_source(request) + await client.create_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6434,53 +6643,49 @@ async def test_update_data_source_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "data_source.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_data_source_flattened(): +def test_create_restore_verification_plan_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_source), "__call__" + type(client.transport.create_restore_verification_plan), "__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.update_data_source( - data_source=backupvault.DataSource( - data_source_gcp_resource=backupvault.DataSourceGcpResource( - compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( - name="name_value" - ) - ) + client.create_restore_verification_plan( + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + restore_verification_plan_id="restore_verification_plan_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].data_source - mock_val = backupvault.DataSource( - data_source_gcp_resource=backupvault.DataSourceGcpResource( - compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( - name="name_value" - ) - ) + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].restore_verification_plan + mock_val = gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" ) assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].restore_verification_plan_id + mock_val = "restore_verification_plan_id_value" assert arg == mock_val -def test_update_data_source_flattened_error(): +def test_create_restore_verification_plan_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6488,28 +6693,25 @@ def test_update_data_source_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_data_source( - backupvault.UpdateDataSourceRequest(), - data_source=backupvault.DataSource( - data_source_gcp_resource=backupvault.DataSourceGcpResource( - compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( - name="name_value" - ) - ) + client.create_restore_verification_plan( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + restore_verification_plan_id="restore_verification_plan_id_value", ) @pytest.mark.asyncio -async def test_update_data_source_flattened_async(): +async def test_create_restore_verification_plan_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_data_source), "__call__" + type(client.transport.create_restore_verification_plan), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -6519,37 +6721,33 @@ async def test_update_data_source_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_data_source( - data_source=backupvault.DataSource( - data_source_gcp_resource=backupvault.DataSourceGcpResource( - compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( - name="name_value" - ) - ) + response = await client.create_restore_verification_plan( + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + restore_verification_plan_id="restore_verification_plan_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].data_source - mock_val = backupvault.DataSource( - data_source_gcp_resource=backupvault.DataSourceGcpResource( - compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( - name="name_value" - ) - ) + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].restore_verification_plan + mock_val = gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" ) assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].restore_verification_plan_id + mock_val = "restore_verification_plan_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_data_source_flattened_error_async(): +async def test_create_restore_verification_plan_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6557,27 +6755,26 @@ async def test_update_data_source_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_data_source( - backupvault.UpdateDataSourceRequest(), - data_source=backupvault.DataSource( - data_source_gcp_resource=backupvault.DataSourceGcpResource( - compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( - name="name_value" - ) - ) + await client.create_restore_verification_plan( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + restore_verification_plan_id="restore_verification_plan_id_value", ) @pytest.mark.parametrize( "request_type", [ - backupvault.ListBackupsRequest(), + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), {}, ], ) -def test_list_backups(request_type, transport: str = "grpc"): +def test_create_restore_verification_plan_association( + request_type, transport: str = "grpc" +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6588,27 +6785,24 @@ def test_list_backups(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.list_backups), "__call__") as call: + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_backups(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.ListBackupsRequest() + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() assert args[0] == 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"] + assert isinstance(response, future.Future) -def test_list_backups_non_empty_request_with_auto_populated_field(): +def test_create_restore_verification_plan_association_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 = BackupDRClient( @@ -6619,31 +6813,29 @@ def test_list_backups_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 = backupvault.ListBackupsRequest( + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_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: + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_backups(request=request) + client.create_restore_verification_plan_association(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListBackupsRequest( + request_msg = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + restore_verification_plan_association_id="restore_verification_plan_association_id_value", ) assert args[0] == request_msg -def test_list_backups_use_cached_wrapped_rpc(): +def test_create_restore_verification_plan_association_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: @@ -6657,21 +6849,31 @@ def test_list_backups_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_backups in client._transport._wrapped_methods + assert ( + client._transport.create_restore_verification_plan_association + 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 + client._transport._wrapped_methods[ + client._transport.create_restore_verification_plan_association + ] = mock_rpc request = {} - client.list_backups(request) + client.create_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backups(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.create_restore_verification_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6679,7 +6881,7 @@ def test_list_backups_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_backups_async_use_cached_wrapped_rpc( +async def test_create_restore_verification_plan_association_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6696,7 +6898,7 @@ async def test_list_backups_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_backups + client._client._transport.create_restore_verification_plan_association in client._client._transport._wrapped_methods ) @@ -6704,16 +6906,21 @@ async def test_list_backups_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_backups + client._client._transport.create_restore_verification_plan_association ] = mock_rpc request = {} - await client.list_backups(request) + await client.create_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_backups(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() + + await client.create_restore_verification_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6724,11 +6931,13 @@ async def test_list_backups_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.ListBackupsRequest(), + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), {}, ], ) -async def test_list_backups_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_restore_verification_plan_association_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6739,43 +6948,42 @@ async def test_list_backups_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.list_backups), "__call__") as call: + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_backups(request) + response = await client.create_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.ListBackupsRequest() + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() assert args[0] == request # 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"] + assert isinstance(response, future.Future) -def test_list_backups_field_headers(): +def test_create_restore_verification_plan_association_field_headers(): client = BackupDRClient( 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 = backupvault.ListBackupsRequest() + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() request.parent = "parent_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 = backupvault.ListBackupsResponse() - client.list_backups(request) + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6791,23 +6999,25 @@ def test_list_backups_field_headers(): @pytest.mark.asyncio -async def test_list_backups_field_headers_async(): +async def test_create_restore_verification_plan_association_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.ListBackupsRequest() + request = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() request.parent = "parent_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: + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListBackupsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_backups(request) + await client.create_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6822,19 +7032,25 @@ async def test_list_backups_field_headers_async(): ) in kw["metadata"] -def test_list_backups_flattened(): +def test_create_restore_verification_plan_association_flattened(): client = BackupDRClient( 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: + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.ListBackupsResponse() + 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.list_backups( + client.create_restore_verification_plan_association( parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + restore_template="restore_template_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_id_value", ) # Establish that the underlying call was made with the expected @@ -6844,9 +7060,17 @@ def test_list_backups_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].restore_verification_plan_association + mock_val = gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + restore_template="restore_template_value" + ) + assert arg == mock_val + arg = args[0].restore_verification_plan_association_id + mock_val = "restore_verification_plan_association_id_value" + assert arg == mock_val -def test_list_backups_flattened_error(): +def test_create_restore_verification_plan_association_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6854,30 +7078,40 @@ def test_list_backups_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backups( - backupvault.ListBackupsRequest(), + client.create_restore_verification_plan_association( + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + restore_template="restore_template_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_id_value", ) @pytest.mark.asyncio -async def test_list_backups_flattened_async(): +async def test_create_restore_verification_plan_association_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.ListBackupsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListBackupsResponse() + 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.list_backups( + response = await client.create_restore_verification_plan_association( parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + restore_template="restore_template_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_id_value", ) # Establish that the underlying call was made with the expected @@ -6887,10 +7121,18 @@ async def test_list_backups_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].restore_verification_plan_association + mock_val = gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + restore_template="restore_template_value" + ) + assert arg == mock_val + arg = args[0].restore_verification_plan_association_id + mock_val = "restore_verification_plan_association_id_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_list_backups_flattened_error_async(): +async def test_create_restore_verification_plan_association_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6898,215 +7140,26 @@ async def test_list_backups_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.list_backups( - backupvault.ListBackupsRequest(), + await client.create_restore_verification_plan_association( + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), parent="parent_value", - ) - - -def test_list_backups_pager(transport_name: str = "grpc"): - client = BackupDRClient( - 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_backups), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), - ], - next_page_token="abc", - ), - backupvault.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - ], - ), - RuntimeError, - ) - - 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) - - 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, backupvault.Backup) for i in results) - - -def test_list_backups_pages(transport_name: str = "grpc"): - client = BackupDRClient( - 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_backups), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), - ], - next_page_token="abc", - ), - backupvault.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.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 - - -@pytest.mark.asyncio -async def test_list_backups_async_pager(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = ( - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), - ], - next_page_token="abc", - ), - backupvault.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.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__}<") - - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, backupvault.Backup) for i in responses) - - -@pytest.mark.asyncio -async def test_list_backups_async_pages(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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 = ( - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), - ], - next_page_token="abc", - ), - backupvault.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - ], + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + restore_template="restore_template_value" ), - RuntimeError, + restore_verification_plan_association_id="restore_verification_plan_association_id_value", ) - 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 @pytest.mark.parametrize( "request_type", [ - backupvault.FetchBackupsForResourceTypeRequest(), + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), {}, ], ) -def test_fetch_backups_for_resource_type(request_type, transport: str = "grpc"): +def test_get_restore_verification_plan_association( + request_type, transport: str = "grpc" +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7118,26 +7171,39 @@ def test_fetch_backups_for_resource_type(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.get_restore_verification_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.FetchBackupsForResourceTypeResponse( - next_page_token="next_page_token_value", + call.return_value = restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value", + description="description_value", + state=restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING, + resource_type="resource_type_value", + restore_template="restore_template_value", ) - response = client.fetch_backups_for_resource_type(request) + response = client.get_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.FetchBackupsForResourceTypeRequest() + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchBackupsForResourceTypePager) - assert response.next_page_token == "next_page_token_value" + assert isinstance( + response, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING + ) + assert response.resource_type == "resource_type_value" -def test_fetch_backups_for_resource_type_non_empty_request_with_auto_populated_field(): +def test_get_restore_verification_plan_association_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 = BackupDRClient( @@ -7148,35 +7214,27 @@ def test_fetch_backups_for_resource_type_non_empty_request_with_auto_populated_f # 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 = backupvault.FetchBackupsForResourceTypeRequest( - parent="parent_value", - resource_type="resource_type_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.get_restore_verification_plan_association), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.fetch_backups_for_resource_type(request=request) + client.get_restore_verification_plan_association(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.FetchBackupsForResourceTypeRequest( - parent="parent_value", - resource_type="resource_type_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request_msg = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest( + name="name_value", ) assert args[0] == request_msg -def test_fetch_backups_for_resource_type_use_cached_wrapped_rpc(): +def test_get_restore_verification_plan_association_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: @@ -7191,7 +7249,7 @@ def test_fetch_backups_for_resource_type_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_backups_for_resource_type + client._transport.get_restore_verification_plan_association in client._transport._wrapped_methods ) @@ -7201,15 +7259,15 @@ def test_fetch_backups_for_resource_type_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_backups_for_resource_type + client._transport.get_restore_verification_plan_association ] = mock_rpc request = {} - client.fetch_backups_for_resource_type(request) + client.get_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_backups_for_resource_type(request) + client.get_restore_verification_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7217,7 +7275,7 @@ def test_fetch_backups_for_resource_type_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_fetch_backups_for_resource_type_async_use_cached_wrapped_rpc( +async def test_get_restore_verification_plan_association_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -7234,7 +7292,7 @@ async def test_fetch_backups_for_resource_type_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.fetch_backups_for_resource_type + client._client._transport.get_restore_verification_plan_association in client._client._transport._wrapped_methods ) @@ -7242,16 +7300,16 @@ async def test_fetch_backups_for_resource_type_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.fetch_backups_for_resource_type + client._client._transport.get_restore_verification_plan_association ] = mock_rpc request = {} - await client.fetch_backups_for_resource_type(request) + await client.get_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_backups_for_resource_type(request) + await client.get_restore_verification_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7262,11 +7320,11 @@ async def test_fetch_backups_for_resource_type_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.FetchBackupsForResourceTypeRequest(), + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), {}, ], ) -async def test_fetch_backups_for_resource_type_async( +async def test_get_restore_verification_plan_association_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -7280,44 +7338,58 @@ async def test_fetch_backups_for_resource_type_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.get_restore_verification_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchBackupsForResourceTypeResponse( - next_page_token="next_page_token_value", + restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value", + description="description_value", + state=restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING, + resource_type="resource_type_value", ) ) - response = await client.fetch_backups_for_resource_type(request) + response = await client.get_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.FetchBackupsForResourceTypeRequest() + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchBackupsForResourceTypeAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance( + response, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING + ) + assert response.resource_type == "resource_type_value" -def test_fetch_backups_for_resource_type_field_headers(): +def test_get_restore_verification_plan_association_field_headers(): client = BackupDRClient( 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 = backupvault.FetchBackupsForResourceTypeRequest() + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.get_restore_verification_plan_association), "__call__" ) as call: - call.return_value = backupvault.FetchBackupsForResourceTypeResponse() - client.fetch_backups_for_resource_type(request) + call.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + client.get_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7328,34 +7400,363 @@ def test_fetch_backups_for_resource_type_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_fetch_backups_for_resource_type_field_headers_async(): +async def test_get_restore_verification_plan_association_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.FetchBackupsForResourceTypeRequest() + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.get_restore_verification_plan_association), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchBackupsForResourceTypeResponse() + restore_verification_plan_association.RestoreVerificationPlanAssociation() ) - await client.fetch_backups_for_resource_type(request) + await client.get_restore_verification_plan_association(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_restore_verification_plan_association_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_restore_verification_plan_association( + 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_restore_verification_plan_association_flattened_error(): + client = BackupDRClient( + 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_restore_verification_plan_association( + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_restore_verification_plan_association_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_restore_verification_plan_association( + 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_restore_verification_plan_association_flattened_error_async(): + client = BackupDRAsyncClient( + 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_restore_verification_plan_association( + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), + {}, + ], +) +def test_list_restore_verification_plan_associations( + request_type, transport: str = "grpc" +): + client = BackupDRClient( + 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_restore_verification_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_restore_verification_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreVerificationPlanAssociationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_restore_verification_plan_associations_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 = BackupDRClient( + 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + 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_restore_verification_plan_associations), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_restore_verification_plan_associations(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_restore_verification_plan_associations_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 = BackupDRClient( + 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_restore_verification_plan_associations + 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_restore_verification_plan_associations + ] = mock_rpc + request = {} + client.list_restore_verification_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_restore_verification_plan_associations(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_restore_verification_plan_associations_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 = BackupDRAsyncClient( + 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_restore_verification_plan_associations + 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_restore_verification_plan_associations + ] = mock_rpc + + request = {} + await client.list_restore_verification_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_restore_verification_plan_associations(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", + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), + {}, + ], +) +async def test_list_restore_verification_plan_associations_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + 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_restore_verification_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_restore_verification_plan_associations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance( + response, pagers.ListRestoreVerificationPlanAssociationsAsyncPager + ) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_restore_verification_plan_associations_field_headers(): + client = BackupDRClient( + 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + client.list_restore_verification_plan_associations(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. @@ -7366,22 +7767,55 @@ async def test_fetch_backups_for_resource_type_field_headers_async(): ) in kw["metadata"] -def test_fetch_backups_for_resource_type_flattened(): +@pytest.mark.asyncio +async def test_list_restore_verification_plan_associations_field_headers_async(): + client = BackupDRAsyncClient( + 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + ) + await client.list_restore_verification_plan_associations(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_restore_verification_plan_associations_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.list_restore_verification_plan_associations), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.FetchBackupsForResourceTypeResponse() + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.fetch_backups_for_resource_type( + client.list_restore_verification_plan_associations( parent="parent_value", - resource_type="resource_type_value", ) # Establish that the underlying call was made with the expected @@ -7391,12 +7825,9 @@ def test_fetch_backups_for_resource_type_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].resource_type - mock_val = "resource_type_value" - assert arg == mock_val -def test_fetch_backups_for_resource_type_flattened_error(): +def test_list_restore_verification_plan_associations_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7404,34 +7835,32 @@ def test_fetch_backups_for_resource_type_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_backups_for_resource_type( - backupvault.FetchBackupsForResourceTypeRequest(), + client.list_restore_verification_plan_associations( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), parent="parent_value", - resource_type="resource_type_value", ) @pytest.mark.asyncio -async def test_fetch_backups_for_resource_type_flattened_async(): +async def test_list_restore_verification_plan_associations_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.list_restore_verification_plan_associations), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.FetchBackupsForResourceTypeResponse() + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchBackupsForResourceTypeResponse() + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.fetch_backups_for_resource_type( + response = await client.list_restore_verification_plan_associations( parent="parent_value", - resource_type="resource_type_value", ) # Establish that the underlying call was made with the expected @@ -7441,13 +7870,10 @@ async def test_fetch_backups_for_resource_type_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].resource_type - mock_val = "resource_type_value" - assert arg == mock_val @pytest.mark.asyncio -async def test_fetch_backups_for_resource_type_flattened_error_async(): +async def test_list_restore_verification_plan_associations_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -7455,14 +7881,15 @@ async def test_fetch_backups_for_resource_type_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.fetch_backups_for_resource_type( - backupvault.FetchBackupsForResourceTypeRequest(), + await client.list_restore_verification_plan_associations( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), parent="parent_value", - resource_type="resource_type_value", ) -def test_fetch_backups_for_resource_type_pager(transport_name: str = "grpc"): +def test_list_restore_verification_plan_associations_pager( + transport_name: str = "grpc", +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -7470,32 +7897,32 @@ def test_fetch_backups_for_resource_type_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.list_restore_verification_plan_associations), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="abc", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], next_page_token="def", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="ghi", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], ), RuntimeError, @@ -7507,7 +7934,7 @@ def test_fetch_backups_for_resource_type_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.fetch_backups_for_resource_type( + pager = client.list_restore_verification_plan_associations( request={}, retry=retry, timeout=timeout ) @@ -7520,10 +7947,18 @@ def test_fetch_backups_for_resource_type_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, backupvault.Backup) for i in results) + assert all( + isinstance( + i, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + for i in results + ) -def test_fetch_backups_for_resource_type_pages(transport_name: str = "grpc"): +def test_list_restore_verification_plan_associations_pages( + transport_name: str = "grpc", +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -7531,82 +7966,84 @@ def test_fetch_backups_for_resource_type_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" + type(client.transport.list_restore_verification_plan_associations), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="abc", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], next_page_token="def", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="ghi", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], ), RuntimeError, ) - pages = list(client.fetch_backups_for_resource_type(request={}).pages) + pages = list( + client.list_restore_verification_plan_associations(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_fetch_backups_for_resource_type_async_pager(): +async def test_list_restore_verification_plan_associations_async_pager(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), + type(client.transport.list_restore_verification_plan_associations), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="abc", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], next_page_token="def", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="ghi", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], ), RuntimeError, ) - async_pager = await client.fetch_backups_for_resource_type( + async_pager = await client.list_restore_verification_plan_associations( request={}, ) assert async_pager.next_page_token == "abc" @@ -7617,52 +8054,58 @@ async def test_fetch_backups_for_resource_type_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, backupvault.Backup) for i in responses) + assert all( + isinstance( + i, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + for i in responses + ) @pytest.mark.asyncio -async def test_fetch_backups_for_resource_type_async_pages(): +async def test_list_restore_verification_plan_associations_async_pages(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), + type(client.transport.list_restore_verification_plan_associations), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="abc", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], next_page_token="def", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="ghi", ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], ), RuntimeError, ) pages = [] async for page_ in ( - await client.fetch_backups_for_resource_type(request={}) + await client.list_restore_verification_plan_associations(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -7672,11 +8115,13 @@ async def test_fetch_backups_for_resource_type_async_pages(): @pytest.mark.parametrize( "request_type", [ - backupvault.GetBackupRequest(), + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), {}, ], ) -def test_get_backup(request_type, transport: str = "grpc"): +def test_delete_restore_verification_plan_association( + request_type, transport: str = "grpc" +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7687,46 +8132,24 @@ def test_get_backup(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.get_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.Backup( - name="name_value", - description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, - etag="etag_value", - state=backupvault.Backup.State.CREATING, - backup_type=backupvault.Backup.BackupType.SCHEDULED, - resource_size_bytes=2056, - satisfies_pzs=True, - satisfies_pzi=True, - kms_key_versions=["kms_key_versions_value"], - ) - response = client.get_backup(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.GetBackupRequest() + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupvault.Backup) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( - response.backup_retention_inheritance - == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION - ) - assert response.etag == "etag_value" - assert response.state == backupvault.Backup.State.CREATING - assert response.backup_type == backupvault.Backup.BackupType.SCHEDULED - assert response.resource_size_bytes == 2056 - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - assert response.kms_key_versions == ["kms_key_versions_value"] + assert isinstance(response, future.Future) -def test_get_backup_non_empty_request_with_auto_populated_field(): +def test_delete_restore_verification_plan_association_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 = BackupDRClient( @@ -7737,25 +8160,27 @@ def test_get_backup_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 = backupvault.GetBackupRequest( + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest( 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: + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_backup(request=request) + client.delete_restore_verification_plan_association(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetBackupRequest( + request_msg = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest( name="name_value", ) assert args[0] == request_msg -def test_get_backup_use_cached_wrapped_rpc(): +def test_delete_restore_verification_plan_association_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: @@ -7769,21 +8194,31 @@ def test_get_backup_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup in client._transport._wrapped_methods + assert ( + client._transport.delete_restore_verification_plan_association + 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 + client._transport._wrapped_methods[ + client._transport.delete_restore_verification_plan_association + ] = mock_rpc request = {} - client.get_backup(request) + client.delete_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup(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.delete_restore_verification_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7791,7 +8226,9 @@ def test_get_backup_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_delete_restore_verification_plan_association_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: @@ -7806,7 +8243,7 @@ async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_as # Ensure method has been cached assert ( - client._client._transport.get_backup + client._client._transport.delete_restore_verification_plan_association in client._client._transport._wrapped_methods ) @@ -7814,16 +8251,21 @@ async def test_get_backup_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.get_backup + client._client._transport.delete_restore_verification_plan_association ] = mock_rpc request = {} - await client.get_backup(request) + await client.delete_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_backup(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() + + await client.delete_restore_verification_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7834,11 +8276,13 @@ async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_as @pytest.mark.parametrize( "request_type", [ - backupvault.GetBackupRequest(), + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), {}, ], ) -async def test_get_backup_async(request_type, transport: str = "grpc_asyncio"): +async def test_delete_restore_verification_plan_association_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7849,62 +8293,42 @@ async def test_get_backup_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.get_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.Backup( - name="name_value", - description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, - etag="etag_value", - state=backupvault.Backup.State.CREATING, - backup_type=backupvault.Backup.BackupType.SCHEDULED, - resource_size_bytes=2056, - satisfies_pzs=True, - satisfies_pzi=True, - kms_key_versions=["kms_key_versions_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_backup(request) + response = await client.delete_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.GetBackupRequest() + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupvault.Backup) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( - response.backup_retention_inheritance - == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION - ) - assert response.etag == "etag_value" - assert response.state == backupvault.Backup.State.CREATING - assert response.backup_type == backupvault.Backup.BackupType.SCHEDULED - assert response.resource_size_bytes == 2056 - assert response.satisfies_pzs is True - assert response.satisfies_pzi is True - assert response.kms_key_versions == ["kms_key_versions_value"] + assert isinstance(response, future.Future) -def test_get_backup_field_headers(): +def test_delete_restore_verification_plan_association_field_headers(): client = BackupDRClient( 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 = backupvault.GetBackupRequest() + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() 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 = backupvault.Backup() - client.get_backup(request) + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7920,21 +8344,25 @@ def test_get_backup_field_headers(): @pytest.mark.asyncio -async def test_get_backup_field_headers_async(): +async def test_delete_restore_verification_plan_association_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.GetBackupRequest() + request = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() 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(backupvault.Backup()) - await client.get_backup(request) + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7949,18 +8377,20 @@ async def test_get_backup_field_headers_async(): ) in kw["metadata"] -def test_get_backup_flattened(): +def test_delete_restore_verification_plan_association_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.Backup() + 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.get_backup( + client.delete_restore_verification_plan_association( name="name_value", ) @@ -7973,7 +8403,7 @@ def test_get_backup_flattened(): assert arg == mock_val -def test_get_backup_flattened_error(): +def test_delete_restore_verification_plan_association_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7981,27 +8411,31 @@ def test_get_backup_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_backup( - backupvault.GetBackupRequest(), + client.delete_restore_verification_plan_association( + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_backup_flattened_async(): +async def test_delete_restore_verification_plan_association_flattened_async(): client = BackupDRAsyncClient( 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: + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupvault.Backup() + call.return_value = operations_pb2.Operation(name="operations/op") - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(backupvault.Backup()) + 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.get_backup( + response = await client.delete_restore_verification_plan_association( name="name_value", ) @@ -8015,7 +8449,7 @@ async def test_get_backup_flattened_async(): @pytest.mark.asyncio -async def test_get_backup_flattened_error_async(): +async def test_delete_restore_verification_plan_association_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8023,8 +8457,8 @@ async def test_get_backup_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.get_backup( - backupvault.GetBackupRequest(), + await client.delete_restore_verification_plan_association( + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), name="name_value", ) @@ -8032,11 +8466,11 @@ async def test_get_backup_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - backupvault.UpdateBackupRequest(), + restore_verification_plan_association.TriggerRestoreVerificationRequest(), {}, ], ) -def test_update_backup(request_type, transport: str = "grpc"): +def test_trigger_restore_verification(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8047,22 +8481,26 @@ def test_update_backup(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.update_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_backup(request) + response = client.trigger_restore_verification(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.UpdateBackupRequest() + request = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_backup_non_empty_request_with_auto_populated_field(): +def test_trigger_restore_verification_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 = BackupDRClient( @@ -8073,21 +8511,29 @@ def test_update_backup_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 = backupvault.UpdateBackupRequest() + request = restore_verification_plan_association.TriggerRestoreVerificationRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_backup(request=request) + client.trigger_restore_verification(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateBackupRequest() + request_msg = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest( + name="name_value", + ) + ) assert args[0] == request_msg -def test_update_backup_use_cached_wrapped_rpc(): +def test_trigger_restore_verification_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: @@ -8101,16 +8547,21 @@ def test_update_backup_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_backup in client._transport._wrapped_methods + assert ( + client._transport.trigger_restore_verification + 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_backup] = mock_rpc + client._transport._wrapped_methods[ + client._transport.trigger_restore_verification + ] = mock_rpc request = {} - client.update_backup(request) + client.trigger_restore_verification(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8120,7 +8571,7 @@ def test_update_backup_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_backup(request) + client.trigger_restore_verification(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8128,7 +8579,7 @@ def test_update_backup_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_backup_async_use_cached_wrapped_rpc( +async def test_trigger_restore_verification_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8145,7 +8596,7 @@ async def test_update_backup_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_backup + client._client._transport.trigger_restore_verification in client._client._transport._wrapped_methods ) @@ -8153,11 +8604,11 @@ async def test_update_backup_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_backup + client._client._transport.trigger_restore_verification ] = mock_rpc request = {} - await client.update_backup(request) + await client.trigger_restore_verification(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8167,7 +8618,7 @@ async def test_update_backup_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_backup(request) + await client.trigger_restore_verification(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8178,11 +8629,13 @@ async def test_update_backup_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.UpdateBackupRequest(), + restore_verification_plan_association.TriggerRestoreVerificationRequest(), {}, ], ) -async def test_update_backup_async(request_type, transport: str = "grpc_asyncio"): +async def test_trigger_restore_verification_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8193,38 +8646,44 @@ async def test_update_backup_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.update_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__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.update_backup(request) + response = await client.trigger_restore_verification(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.UpdateBackupRequest() + request = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_backup_field_headers(): +def test_trigger_restore_verification_field_headers(): client = BackupDRClient( 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 = backupvault.UpdateBackupRequest() + request = restore_verification_plan_association.TriggerRestoreVerificationRequest() - request.backup.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_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup(request) + client.trigger_restore_verification(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8235,28 +8694,30 @@ def test_update_backup_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_backup_field_headers_async(): +async def test_trigger_restore_verification_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.UpdateBackupRequest() + request = restore_verification_plan_association.TriggerRestoreVerificationRequest() - request.backup.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_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_backup(request) + await client.trigger_restore_verification(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8267,47 +8728,37 @@ async def test_update_backup_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_backup_flattened(): +def test_trigger_restore_verification_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__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.update_backup( - backup=backupvault.Backup( - compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( - description="description_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.trigger_restore_verification( + 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].backup - mock_val = backupvault.Backup( - compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( - description="description_value" - ) - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_backup_flattened_error(): +def test_trigger_restore_verification_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8315,25 +8766,22 @@ def test_update_backup_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_backup( - backupvault.UpdateBackupRequest(), - backup=backupvault.Backup( - compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( - description="description_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.trigger_restore_verification( + restore_verification_plan_association.TriggerRestoreVerificationRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_backup_flattened_async(): +async def test_trigger_restore_verification_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -8342,33 +8790,21 @@ async def test_update_backup_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_backup( - backup=backupvault.Backup( - compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( - description="description_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.trigger_restore_verification( + 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].backup - mock_val = backupvault.Backup( - compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( - description="description_value" - ) - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_backup_flattened_error_async(): +async def test_trigger_restore_verification_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8376,25 +8812,20 @@ async def test_update_backup_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_backup( - backupvault.UpdateBackupRequest(), - backup=backupvault.Backup( - compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( - description="description_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.trigger_restore_verification( + restore_verification_plan_association.TriggerRestoreVerificationRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - backupvault.DeleteBackupRequest(), + restore_verification_plan.GetRestoreVerificationPlanRequest(), {}, ], ) -def test_delete_backup(request_type, transport: str = "grpc"): +def test_get_restore_verification_plan(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8405,22 +8836,38 @@ def test_delete_backup(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.delete_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__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) + call.return_value = restore_verification_plan.RestoreVerificationPlan( + name="name_value", + description="description_value", + state=restore_verification_plan.RestoreVerificationPlan.State.CREATING, + schedule="schedule_value", + time_zone="time_zone_value", + ) + response = client.get_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.DeleteBackupRequest() + request = restore_verification_plan.GetRestoreVerificationPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, restore_verification_plan.RestoreVerificationPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan.RestoreVerificationPlan.State.CREATING + ) + assert response.schedule == "schedule_value" + assert response.time_zone == "time_zone_value" -def test_delete_backup_non_empty_request_with_auto_populated_field(): +def test_get_restore_verification_plan_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 = BackupDRClient( @@ -8431,25 +8878,27 @@ def test_delete_backup_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 = backupvault.DeleteBackupRequest( + request = restore_verification_plan.GetRestoreVerificationPlanRequest( 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: + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_backup(request=request) + client.get_restore_verification_plan(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.DeleteBackupRequest( + request_msg = restore_verification_plan.GetRestoreVerificationPlanRequest( name="name_value", ) assert args[0] == request_msg -def test_delete_backup_use_cached_wrapped_rpc(): +def test_get_restore_verification_plan_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: @@ -8463,26 +8912,26 @@ def test_delete_backup_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_backup in client._transport._wrapped_methods + assert ( + client._transport.get_restore_verification_plan + 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 + client._transport._wrapped_methods[ + client._transport.get_restore_verification_plan + ] = mock_rpc request = {} - client.delete_backup(request) + client.get_restore_verification_plan(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) + client.get_restore_verification_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8490,7 +8939,7 @@ def test_delete_backup_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_backup_async_use_cached_wrapped_rpc( +async def test_get_restore_verification_plan_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8507,7 +8956,7 @@ async def test_delete_backup_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_backup + client._client._transport.get_restore_verification_plan in client._client._transport._wrapped_methods ) @@ -8515,21 +8964,16 @@ async def test_delete_backup_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_backup + client._client._transport.get_restore_verification_plan ] = mock_rpc request = {} - await client.delete_backup(request) + await client.get_restore_verification_plan(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) + await client.get_restore_verification_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8540,11 +8984,13 @@ async def test_delete_backup_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.DeleteBackupRequest(), + restore_verification_plan.GetRestoreVerificationPlanRequest(), {}, ], ) -async def test_delete_backup_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_restore_verification_plan_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8555,38 +9001,56 @@ async def test_delete_backup_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.delete_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + restore_verification_plan.RestoreVerificationPlan( + name="name_value", + description="description_value", + state=restore_verification_plan.RestoreVerificationPlan.State.CREATING, + schedule="schedule_value", + time_zone="time_zone_value", + ) ) - response = await client.delete_backup(request) + response = await client.get_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.DeleteBackupRequest() + request = restore_verification_plan.GetRestoreVerificationPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, restore_verification_plan.RestoreVerificationPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan.RestoreVerificationPlan.State.CREATING + ) + assert response.schedule == "schedule_value" + assert response.time_zone == "time_zone_value" -def test_delete_backup_field_headers(): +def test_get_restore_verification_plan_field_headers(): client = BackupDRClient( 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 = backupvault.DeleteBackupRequest() + request = restore_verification_plan.GetRestoreVerificationPlanRequest() 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) + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: + call.return_value = restore_verification_plan.RestoreVerificationPlan() + client.get_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8602,23 +9066,25 @@ def test_delete_backup_field_headers(): @pytest.mark.asyncio -async def test_delete_backup_field_headers_async(): +async def test_get_restore_verification_plan_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.DeleteBackupRequest() + request = restore_verification_plan.GetRestoreVerificationPlanRequest() 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: + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + restore_verification_plan.RestoreVerificationPlan() ) - await client.delete_backup(request) + await client.get_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8633,18 +9099,20 @@ async def test_delete_backup_field_headers_async(): ) in kw["metadata"] -def test_delete_backup_flattened(): +def test_get_restore_verification_plan_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = restore_verification_plan.RestoreVerificationPlan() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_backup( + client.get_restore_verification_plan( name="name_value", ) @@ -8657,7 +9125,7 @@ def test_delete_backup_flattened(): assert arg == mock_val -def test_delete_backup_flattened_error(): +def test_get_restore_verification_plan_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8665,29 +9133,31 @@ def test_delete_backup_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_backup( - backupvault.DeleteBackupRequest(), + client.get_restore_verification_plan( + restore_verification_plan.GetRestoreVerificationPlanRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_backup_flattened_async(): +async def test_get_restore_verification_plan_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = restore_verification_plan.RestoreVerificationPlan() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + restore_verification_plan.RestoreVerificationPlan() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_backup( + response = await client.get_restore_verification_plan( name="name_value", ) @@ -8701,7 +9171,7 @@ async def test_delete_backup_flattened_async(): @pytest.mark.asyncio -async def test_delete_backup_flattened_error_async(): +async def test_get_restore_verification_plan_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8709,8 +9179,8 @@ async def test_delete_backup_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.delete_backup( - backupvault.DeleteBackupRequest(), + await client.get_restore_verification_plan( + restore_verification_plan.GetRestoreVerificationPlanRequest(), name="name_value", ) @@ -8718,11 +9188,11 @@ async def test_delete_backup_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - backupvault.RestoreBackupRequest(), + restore_verification_plan.ListRestoreVerificationPlansRequest(), {}, ], ) -def test_restore_backup(request_type, transport: str = "grpc"): +def test_list_restore_verification_plans(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8733,22 +9203,31 @@ def test_restore_backup(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.restore_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.restore_backup(request) + call.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = client.list_restore_verification_plans(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupvault.RestoreBackupRequest() + request = restore_verification_plan.ListRestoreVerificationPlansRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListRestoreVerificationPlansPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_restore_backup_non_empty_request_with_auto_populated_field(): +def test_list_restore_verification_plans_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 = BackupDRClient( @@ -8759,25 +9238,33 @@ def test_restore_backup_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 = backupvault.RestoreBackupRequest( - name="name_value", + request = restore_verification_plan.ListRestoreVerificationPlansRequest( + 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.restore_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.restore_backup(request=request) + client.list_restore_verification_plans(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupvault.RestoreBackupRequest( - name="name_value", + request_msg = restore_verification_plan.ListRestoreVerificationPlansRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) assert args[0] == request_msg -def test_restore_backup_use_cached_wrapped_rpc(): +def test_list_restore_verification_plans_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: @@ -8791,26 +9278,26 @@ def test_restore_backup_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.restore_backup in client._transport._wrapped_methods + assert ( + client._transport.list_restore_verification_plans + 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.restore_backup] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_restore_verification_plans + ] = mock_rpc request = {} - client.restore_backup(request) + client.list_restore_verification_plans(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.restore_backup(request) + client.list_restore_verification_plans(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8818,7 +9305,7 @@ def test_restore_backup_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_restore_backup_async_use_cached_wrapped_rpc( +async def test_list_restore_verification_plans_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8835,7 +9322,7 @@ async def test_restore_backup_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.restore_backup + client._client._transport.list_restore_verification_plans in client._client._transport._wrapped_methods ) @@ -8843,21 +9330,16 @@ async def test_restore_backup_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.restore_backup + client._client._transport.list_restore_verification_plans ] = mock_rpc request = {} - await client.restore_backup(request) + await client.list_restore_verification_plans(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.restore_backup(request) + await client.list_restore_verification_plans(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8868,11 +9350,13 @@ async def test_restore_backup_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupvault.RestoreBackupRequest(), + restore_verification_plan.ListRestoreVerificationPlansRequest(), {}, ], ) -async def test_restore_backup_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_restore_verification_plans_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8883,38 +9367,49 @@ async def test_restore_backup_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.restore_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + restore_verification_plan.ListRestoreVerificationPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.restore_backup(request) + response = await client.list_restore_verification_plans(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupvault.RestoreBackupRequest() + request = restore_verification_plan.ListRestoreVerificationPlansRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListRestoreVerificationPlansAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_restore_backup_field_headers(): +def test_list_restore_verification_plans_field_headers(): client = BackupDRClient( 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 = backupvault.RestoreBackupRequest() + request = restore_verification_plan.ListRestoreVerificationPlansRequest() - request.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.restore_backup), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.restore_backup(request) + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: + call.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) + client.list_restore_verification_plans(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8925,28 +9420,30 @@ def test_restore_backup_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_restore_backup_field_headers_async(): +async def test_list_restore_verification_plans_field_headers_async(): client = BackupDRAsyncClient( 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 = backupvault.RestoreBackupRequest() + request = restore_verification_plan.ListRestoreVerificationPlansRequest() - request.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.restore_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + restore_verification_plan.ListRestoreVerificationPlansResponse() ) - await client.restore_backup(request) + await client.list_restore_verification_plans(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8957,35 +9454,39 @@ async def test_restore_backup_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_restore_backup_flattened(): +def test_list_restore_verification_plans_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.restore_backup( - name="name_value", + client.list_restore_verification_plans( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_restore_backup_flattened_error(): +def test_list_restore_verification_plans_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8993,43 +9494,47 @@ def test_restore_backup_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.restore_backup( - backupvault.RestoreBackupRequest(), - name="name_value", + client.list_restore_verification_plans( + restore_verification_plan.ListRestoreVerificationPlansRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_restore_backup_flattened_async(): +async def test_list_restore_verification_plans_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + restore_verification_plan.ListRestoreVerificationPlansResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.restore_backup( - name="name_value", + response = await client.list_restore_verification_plans( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_restore_backup_flattened_error_async(): +async def test_list_restore_verification_plans_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9037,81 +9542,292 @@ async def test_restore_backup_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_backup( - backupvault.RestoreBackupRequest(), - name="name_value", + await client.list_restore_verification_plans( + restore_verification_plan.ListRestoreVerificationPlansRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - backupplan.CreateBackupPlanRequest(), - {}, - ], -) -def test_create_backup_plan(request_type, transport: str = "grpc"): +def test_list_restore_verification_plans_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" + type(client.transport.list_restore_verification_plans), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_backup_plan(request) + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), + RuntimeError, + ) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = backupplan.CreateBackupPlanRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_restore_verification_plans( + request={}, retry=retry, timeout=timeout + ) - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + 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__}<") -def test_create_backup_plan_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. + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, restore_verification_plan.RestoreVerificationPlan) + for i in results + ) + + +def test_list_restore_verification_plans_pages(transport_name: str = "grpc"): client = BackupDRClient( 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 = backupplan.CreateBackupPlanRequest( - parent="parent_value", - backup_plan_id="backup_plan_id_value", + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" + type(client.transport.list_restore_verification_plans), "__call__" ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.create_backup_plan(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.CreateBackupPlanRequest( - parent="parent_value", - backup_plan_id="backup_plan_id_value", + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), + RuntimeError, + ) + pages = list(client.list_restore_verification_plans(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_restore_verification_plans_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plans), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_restore_verification_plans( + 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, restore_verification_plan.RestoreVerificationPlan) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_restore_verification_plans_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plans), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_restore_verification_plans(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", + [ + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), + {}, + ], +) +def test_delete_restore_verification_plan(request_type, transport: str = "grpc"): + client = BackupDRClient( + 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_restore_verification_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_restore_verification_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_restore_verification_plan_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 = BackupDRClient( + 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 = restore_verification_plan.DeleteRestoreVerificationPlanRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_restore_verification_plan(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.DeleteRestoreVerificationPlanRequest( + name="name_value", ) assert args[0] == request_msg -def test_create_backup_plan_use_cached_wrapped_rpc(): +def test_delete_restore_verification_plan_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: @@ -9126,7 +9842,8 @@ def test_create_backup_plan_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_backup_plan in client._transport._wrapped_methods + client._transport.delete_restore_verification_plan + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -9134,11 +9851,11 @@ def test_create_backup_plan_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.create_backup_plan] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.delete_restore_verification_plan + ] = mock_rpc request = {} - client.create_backup_plan(request) + client.delete_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -9148,7 +9865,7 @@ def test_create_backup_plan_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_backup_plan(request) + client.delete_restore_verification_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9156,7 +9873,7 @@ def test_create_backup_plan_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_backup_plan_async_use_cached_wrapped_rpc( +async def test_delete_restore_verification_plan_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9173,7 +9890,7 @@ async def test_create_backup_plan_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_backup_plan + client._client._transport.delete_restore_verification_plan in client._client._transport._wrapped_methods ) @@ -9181,11 +9898,11 @@ async def test_create_backup_plan_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_backup_plan + client._client._transport.delete_restore_verification_plan ] = mock_rpc request = {} - await client.create_backup_plan(request) + await client.delete_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -9195,7 +9912,7 @@ async def test_create_backup_plan_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_backup_plan(request) + await client.delete_restore_verification_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9206,11 +9923,13 @@ async def test_create_backup_plan_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplan.CreateBackupPlanRequest(), + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), {}, ], ) -async def test_create_backup_plan_async(request_type, transport: str = "grpc_asyncio"): +async def test_delete_restore_verification_plan_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9222,41 +9941,41 @@ async def test_create_backup_plan_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" + type(client.transport.delete_restore_verification_plan), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_backup_plan(request) + response = await client.delete_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplan.CreateBackupPlanRequest() + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_backup_plan_field_headers(): +def test_delete_restore_verification_plan_field_headers(): client = BackupDRClient( 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 = backupplan.CreateBackupPlanRequest() + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" + type(client.transport.delete_restore_verification_plan), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup_plan(request) + client.delete_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9267,30 +9986,30 @@ def test_create_backup_plan_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_backup_plan_field_headers_async(): +async def test_delete_restore_verification_plan_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplan.CreateBackupPlanRequest() + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" + type(client.transport.delete_restore_verification_plan), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_backup_plan(request) + await client.delete_restore_verification_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9301,53 +10020,37 @@ async def test_create_backup_plan_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_backup_plan_flattened(): +def test_delete_restore_verification_plan_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" + type(client.transport.delete_restore_verification_plan), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_backup_plan( - parent="parent_value", - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - backup_plan_id="backup_plan_id_value", + client.delete_restore_verification_plan( + 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].backup_plan - mock_val = backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ) - assert arg == mock_val - arg = args[0].backup_plan_id - mock_val = "backup_plan_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_backup_plan_flattened_error(): +def test_delete_restore_verification_plan_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9355,27 +10058,21 @@ def test_create_backup_plan_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_backup_plan( - backupplan.CreateBackupPlanRequest(), - parent="parent_value", - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - backup_plan_id="backup_plan_id_value", + client.delete_restore_verification_plan( + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_backup_plan_flattened_async(): +async def test_delete_restore_verification_plan_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" + type(client.transport.delete_restore_verification_plan), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -9385,37 +10082,21 @@ async def test_create_backup_plan_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_backup_plan( - parent="parent_value", - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - backup_plan_id="backup_plan_id_value", + response = await client.delete_restore_verification_plan( + 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].backup_plan - mock_val = backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ) - assert arg == mock_val - arg = args[0].backup_plan_id - mock_val = "backup_plan_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_backup_plan_flattened_error_async(): +async def test_delete_restore_verification_plan_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9423,26 +10104,20 @@ async def test_create_backup_plan_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.create_backup_plan( - backupplan.CreateBackupPlanRequest(), - parent="parent_value", - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - backup_plan_id="backup_plan_id_value", + await client.delete_restore_verification_plan( + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - backupplan.UpdateBackupPlanRequest(), + backupvault.CreateBackupVaultRequest(), {}, ], ) -def test_update_backup_plan(request_type, transport: str = "grpc"): +def test_create_backup_vault(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9454,23 +10129,23 @@ def test_update_backup_plan(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_backup_plan), "__call__" + type(client.transport.create_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_backup_plan(request) + response = client.create_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplan.UpdateBackupPlanRequest() + request = backupvault.CreateBackupVaultRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_backup_plan_non_empty_request_with_auto_populated_field(): +def test_create_backup_vault_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 = BackupDRClient( @@ -9481,23 +10156,29 @@ def test_update_backup_plan_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 = backupplan.UpdateBackupPlanRequest() + request = backupvault.CreateBackupVaultRequest( + parent="parent_value", + backup_vault_id="backup_vault_id_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_plan), "__call__" + type(client.transport.create_backup_vault), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_backup_plan(request=request) + client.create_backup_vault(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplan.UpdateBackupPlanRequest() + request_msg = backupvault.CreateBackupVaultRequest( + parent="parent_value", + backup_vault_id="backup_vault_id_value", + ) assert args[0] == request_msg -def test_update_backup_plan_use_cached_wrapped_rpc(): +def test_create_backup_vault_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: @@ -9512,7 +10193,7 @@ def test_update_backup_plan_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_backup_plan in client._transport._wrapped_methods + client._transport.create_backup_vault in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -9520,11 +10201,11 @@ def test_update_backup_plan_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_backup_plan] = ( + client._transport._wrapped_methods[client._transport.create_backup_vault] = ( mock_rpc ) request = {} - client.update_backup_plan(request) + client.create_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -9534,7 +10215,7 @@ def test_update_backup_plan_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_backup_plan(request) + client.create_backup_vault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9542,7 +10223,7 @@ def test_update_backup_plan_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_backup_plan_async_use_cached_wrapped_rpc( +async def test_create_backup_vault_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9559,7 +10240,7 @@ async def test_update_backup_plan_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_backup_plan + client._client._transport.create_backup_vault in client._client._transport._wrapped_methods ) @@ -9567,11 +10248,11 @@ async def test_update_backup_plan_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_backup_plan + client._client._transport.create_backup_vault ] = mock_rpc request = {} - await client.update_backup_plan(request) + await client.create_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -9581,7 +10262,7 @@ async def test_update_backup_plan_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_backup_plan(request) + await client.create_backup_vault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9592,11 +10273,11 @@ async def test_update_backup_plan_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplan.UpdateBackupPlanRequest(), + backupvault.CreateBackupVaultRequest(), {}, ], ) -async def test_update_backup_plan_async(request_type, transport: str = "grpc_asyncio"): +async def test_create_backup_vault_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9608,41 +10289,41 @@ async def test_update_backup_plan_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_plan), "__call__" + type(client.transport.create_backup_vault), "__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.update_backup_plan(request) + response = await client.create_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplan.UpdateBackupPlanRequest() + request = backupvault.CreateBackupVaultRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_backup_plan_field_headers(): +def test_create_backup_vault_field_headers(): client = BackupDRClient( 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 = backupplan.UpdateBackupPlanRequest() + request = backupvault.CreateBackupVaultRequest() - request.backup_plan.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_backup_plan), "__call__" + type(client.transport.create_backup_vault), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup_plan(request) + client.create_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9653,30 +10334,30 @@ def test_update_backup_plan_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup_plan.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_backup_plan_field_headers_async(): +async def test_create_backup_vault_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplan.UpdateBackupPlanRequest() + request = backupvault.CreateBackupVaultRequest() - request.backup_plan.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_backup_plan), "__call__" + type(client.transport.create_backup_vault), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_backup_plan(request) + await client.create_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9687,49 +10368,45 @@ async def test_update_backup_plan_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup_plan.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_backup_plan_flattened(): +def test_create_backup_vault_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_plan), "__call__" + type(client.transport.create_backup_vault), "__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.update_backup_plan( - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_backup_vault( + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_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].backup_plan - mock_val = backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ) + 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].backup_vault + mock_val = backupvault.BackupVault(name="name_value") + assert arg == mock_val + arg = args[0].backup_vault_id + mock_val = "backup_vault_id_value" assert arg == mock_val -def test_update_backup_plan_flattened_error(): +def test_create_backup_vault_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9737,26 +10414,23 @@ def test_update_backup_plan_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_backup_plan( - backupplan.UpdateBackupPlanRequest(), - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_backup_vault( + backupvault.CreateBackupVaultRequest(), + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", ) @pytest.mark.asyncio -async def test_update_backup_plan_flattened_async(): +async def test_create_backup_vault_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_plan), "__call__" + type(client.transport.create_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -9766,33 +10440,29 @@ async def test_update_backup_plan_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_backup_plan( - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.create_backup_vault( + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_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].backup_plan - mock_val = backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ) + 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].backup_vault + mock_val = backupvault.BackupVault(name="name_value") + assert arg == mock_val + arg = args[0].backup_vault_id + mock_val = "backup_vault_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_backup_plan_flattened_error_async(): +async def test_create_backup_vault_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9800,25 +10470,22 @@ async def test_update_backup_plan_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_backup_plan( - backupplan.UpdateBackupPlanRequest(), - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.create_backup_vault( + backupvault.CreateBackupVaultRequest(), + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", ) @pytest.mark.parametrize( "request_type", [ - backupplan.GetBackupPlanRequest(), + backupvault.ListBackupVaultsRequest(), {}, ], ) -def test_get_backup_plan(request_type, transport: str = "grpc"): +def test_list_backup_vaults(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9829,47 +10496,29 @@ def test_get_backup_plan(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.get_backup_plan), "__call__") as call: + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.BackupPlan( - name="name_value", - description="description_value", - max_custom_on_demand_retention_days=3723, - state=backupplan.BackupPlan.State.CREATING, - resource_type="resource_type_value", - etag="etag_value", - backup_vault="backup_vault_value", - backup_vault_service_account="backup_vault_service_account_value", - log_retention_days=1929, - supported_resource_types=["supported_resource_types_value"], - revision_id="revision_id_value", - revision_name="revision_name_value", + call.return_value = backupvault.ListBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - response = client.get_backup_plan(request) + response = client.list_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplan.GetBackupPlanRequest() + request = backupvault.ListBackupVaultsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupplan.BackupPlan) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.max_custom_on_demand_retention_days == 3723 - assert response.state == backupplan.BackupPlan.State.CREATING - assert response.resource_type == "resource_type_value" - assert response.etag == "etag_value" - assert response.backup_vault == "backup_vault_value" - assert response.backup_vault_service_account == "backup_vault_service_account_value" - assert response.log_retention_days == 1929 - assert response.supported_resource_types == ["supported_resource_types_value"] - assert response.revision_id == "revision_id_value" - assert response.revision_name == "revision_name_value" + assert isinstance(response, pagers.ListBackupVaultsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_get_backup_plan_non_empty_request_with_auto_populated_field(): +def test_list_backup_vaults_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 = BackupDRClient( @@ -9880,25 +10529,33 @@ def test_get_backup_plan_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 = backupplan.GetBackupPlanRequest( - name="name_value", + request = backupvault.ListBackupVaultsRequest( + 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.get_backup_plan), "__call__") as call: + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_backup_plan(request=request) + client.list_backup_vaults(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplan.GetBackupPlanRequest( - name="name_value", + request_msg = backupvault.ListBackupVaultsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) assert args[0] == request_msg -def test_get_backup_plan_use_cached_wrapped_rpc(): +def test_list_backup_vaults_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: @@ -9912,21 +10569,25 @@ def test_get_backup_plan_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup_plan in client._transport._wrapped_methods + assert ( + client._transport.list_backup_vaults 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_plan] = mock_rpc + client._transport._wrapped_methods[client._transport.list_backup_vaults] = ( + mock_rpc + ) request = {} - client.get_backup_plan(request) + client.list_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup_plan(request) + client.list_backup_vaults(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9934,7 +10595,7 @@ def test_get_backup_plan_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_backup_plan_async_use_cached_wrapped_rpc( +async def test_list_backup_vaults_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9951,7 +10612,7 @@ async def test_get_backup_plan_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_backup_plan + client._client._transport.list_backup_vaults in client._client._transport._wrapped_methods ) @@ -9959,16 +10620,16 @@ async def test_get_backup_plan_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_backup_plan + client._client._transport.list_backup_vaults ] = mock_rpc request = {} - await client.get_backup_plan(request) + await client.list_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_backup_plan(request) + await client.list_backup_vaults(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9979,11 +10640,11 @@ async def test_get_backup_plan_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplan.GetBackupPlanRequest(), + backupvault.ListBackupVaultsRequest(), {}, ], ) -async def test_get_backup_plan_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_backup_vaults_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9994,63 +10655,47 @@ async def test_get_backup_plan_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.get_backup_plan), "__call__") as call: + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlan( - name="name_value", - description="description_value", - max_custom_on_demand_retention_days=3723, - state=backupplan.BackupPlan.State.CREATING, - resource_type="resource_type_value", - etag="etag_value", - backup_vault="backup_vault_value", - backup_vault_service_account="backup_vault_service_account_value", - log_retention_days=1929, - supported_resource_types=["supported_resource_types_value"], - revision_id="revision_id_value", - revision_name="revision_name_value", + backupvault.ListBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) ) - response = await client.get_backup_plan(request) + response = await client.list_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplan.GetBackupPlanRequest() + request = backupvault.ListBackupVaultsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupplan.BackupPlan) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.max_custom_on_demand_retention_days == 3723 - assert response.state == backupplan.BackupPlan.State.CREATING - assert response.resource_type == "resource_type_value" - assert response.etag == "etag_value" - assert response.backup_vault == "backup_vault_value" - assert response.backup_vault_service_account == "backup_vault_service_account_value" - assert response.log_retention_days == 1929 - assert response.supported_resource_types == ["supported_resource_types_value"] - assert response.revision_id == "revision_id_value" - assert response.revision_name == "revision_name_value" + assert isinstance(response, pagers.ListBackupVaultsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_get_backup_plan_field_headers(): +def test_list_backup_vaults_field_headers(): client = BackupDRClient( 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 = backupplan.GetBackupPlanRequest() + request = backupvault.ListBackupVaultsRequest() - request.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.get_backup_plan), "__call__") as call: - call.return_value = backupplan.BackupPlan() - client.get_backup_plan(request) + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + call.return_value = backupvault.ListBackupVaultsResponse() + client.list_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10061,28 +10706,30 @@ def test_get_backup_plan_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_backup_plan_field_headers_async(): +async def test_list_backup_vaults_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplan.GetBackupPlanRequest() + request = backupvault.ListBackupVaultsRequest() - request.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.get_backup_plan), "__call__") as call: + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlan() + backupvault.ListBackupVaultsResponse() ) - await client.get_backup_plan(request) + await client.list_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10093,35 +10740,37 @@ async def test_get_backup_plan_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_backup_plan_flattened(): +def test_list_backup_vaults_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.BackupPlan() + call.return_value = backupvault.ListBackupVaultsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_backup_plan( - name="name_value", + client.list_backup_vaults( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_backup_plan_flattened_error(): +def test_list_backup_vaults_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10129,43 +10778,45 @@ def test_get_backup_plan_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_backup_plan( - backupplan.GetBackupPlanRequest(), - name="name_value", + client.list_backup_vaults( + backupvault.ListBackupVaultsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_backup_plan_flattened_async(): +async def test_list_backup_vaults_flattened_async(): client = BackupDRAsyncClient( 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_plan), "__call__") as call: + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.BackupPlan() + call.return_value = backupvault.ListBackupVaultsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlan() + backupvault.ListBackupVaultsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_backup_plan( - name="name_value", + response = await client.list_backup_vaults( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_backup_plan_flattened_error_async(): +async def test_list_backup_vaults_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10173,20 +10824,223 @@ async def test_get_backup_plan_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.get_backup_plan( - backupplan.GetBackupPlanRequest(), - name="name_value", + await client.list_backup_vaults( + backupvault.ListBackupVaultsRequest(), + parent="parent_value", + ) + + +def test_list_backup_vaults_pager(transport_name: str = "grpc"): + client = BackupDRClient( + 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_backup_vaults), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backup_vaults(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, backupvault.BackupVault) for i in results) + + +def test_list_backup_vaults_pages(transport_name: str = "grpc"): + client = BackupDRClient( + 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_backup_vaults), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backup_vaults(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_backup_vaults_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backup_vaults( + 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, backupvault.BackupVault) for i in responses) + + +@pytest.mark.asyncio +async def test_list_backup_vaults_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in (await client.list_backup_vaults(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", [ - backupplan.ListBackupPlansRequest(), + backupvault.FetchUsableBackupVaultsRequest(), {}, ], ) -def test_list_backup_plans(request_type, transport: str = "grpc"): +def test_fetch_usable_backup_vaults(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10198,28 +11052,28 @@ def test_list_backup_plans(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" + type(client.transport.fetch_usable_backup_vaults), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.ListBackupPlansResponse( + call.return_value = backupvault.FetchUsableBackupVaultsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) - response = client.list_backup_plans(request) + response = client.fetch_usable_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplan.ListBackupPlansRequest() + request = backupvault.FetchUsableBackupVaultsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupPlansPager) + assert isinstance(response, pagers.FetchUsableBackupVaultsPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_backup_plans_non_empty_request_with_auto_populated_field(): +def test_fetch_usable_backup_vaults_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 = BackupDRClient( @@ -10230,7 +11084,7 @@ def test_list_backup_plans_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 = backupplan.ListBackupPlansRequest( + request = backupvault.FetchUsableBackupVaultsRequest( parent="parent_value", page_token="page_token_value", filter="filter_value", @@ -10239,15 +11093,15 @@ def test_list_backup_plans_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" + type(client.transport.fetch_usable_backup_vaults), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_backup_plans(request=request) + client.fetch_usable_backup_vaults(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplan.ListBackupPlansRequest( + request_msg = backupvault.FetchUsableBackupVaultsRequest( parent="parent_value", page_token="page_token_value", filter="filter_value", @@ -10256,7 +11110,7 @@ def test_list_backup_plans_non_empty_request_with_auto_populated_field(): assert args[0] == request_msg -def test_list_backup_plans_use_cached_wrapped_rpc(): +def test_fetch_usable_backup_vaults_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: @@ -10270,23 +11124,26 @@ def test_list_backup_plans_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_backup_plans in client._transport._wrapped_methods + assert ( + client._transport.fetch_usable_backup_vaults + 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_plans] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.fetch_usable_backup_vaults + ] = mock_rpc request = {} - client.list_backup_plans(request) + client.fetch_usable_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backup_plans(request) + client.fetch_usable_backup_vaults(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10294,7 +11151,7 @@ def test_list_backup_plans_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_backup_plans_async_use_cached_wrapped_rpc( +async def test_fetch_usable_backup_vaults_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10311,7 +11168,7 @@ async def test_list_backup_plans_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_backup_plans + client._client._transport.fetch_usable_backup_vaults in client._client._transport._wrapped_methods ) @@ -10319,16 +11176,16 @@ async def test_list_backup_plans_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_backup_plans + client._client._transport.fetch_usable_backup_vaults ] = mock_rpc request = {} - await client.list_backup_plans(request) + await client.fetch_usable_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_backup_plans(request) + await client.fetch_usable_backup_vaults(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10339,11 +11196,13 @@ async def test_list_backup_plans_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplan.ListBackupPlansRequest(), + backupvault.FetchUsableBackupVaultsRequest(), {}, ], ) -async def test_list_backup_plans_async(request_type, transport: str = "grpc_asyncio"): +async def test_fetch_usable_backup_vaults_async( + request_type, transport: str = "grpc_asyncio" +): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -10355,46 +11214,46 @@ async def test_list_backup_plans_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.list_backup_plans), "__call__" + type(client.transport.fetch_usable_backup_vaults), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlansResponse( + backupvault.FetchUsableBackupVaultsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) ) - response = await client.list_backup_plans(request) + response = await client.fetch_usable_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplan.ListBackupPlansRequest() + request = backupvault.FetchUsableBackupVaultsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupPlansAsyncPager) + assert isinstance(response, pagers.FetchUsableBackupVaultsAsyncPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_backup_plans_field_headers(): +def test_fetch_usable_backup_vaults_field_headers(): client = BackupDRClient( 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 = backupplan.ListBackupPlansRequest() + request = backupvault.FetchUsableBackupVaultsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" + type(client.transport.fetch_usable_backup_vaults), "__call__" ) as call: - call.return_value = backupplan.ListBackupPlansResponse() - client.list_backup_plans(request) + call.return_value = backupvault.FetchUsableBackupVaultsResponse() + client.fetch_usable_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10410,25 +11269,25 @@ def test_list_backup_plans_field_headers(): @pytest.mark.asyncio -async def test_list_backup_plans_field_headers_async(): +async def test_fetch_usable_backup_vaults_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplan.ListBackupPlansRequest() + request = backupvault.FetchUsableBackupVaultsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" + type(client.transport.fetch_usable_backup_vaults), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlansResponse() + backupvault.FetchUsableBackupVaultsResponse() ) - await client.list_backup_plans(request) + await client.fetch_usable_backup_vaults(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10443,20 +11302,20 @@ async def test_list_backup_plans_field_headers_async(): ) in kw["metadata"] -def test_list_backup_plans_flattened(): +def test_fetch_usable_backup_vaults_flattened(): client = BackupDRClient( 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_plans), "__call__" + type(client.transport.fetch_usable_backup_vaults), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.ListBackupPlansResponse() + call.return_value = backupvault.FetchUsableBackupVaultsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_backup_plans( + client.fetch_usable_backup_vaults( parent="parent_value", ) @@ -10469,7 +11328,7 @@ def test_list_backup_plans_flattened(): assert arg == mock_val -def test_list_backup_plans_flattened_error(): +def test_fetch_usable_backup_vaults_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10477,31 +11336,31 @@ def test_list_backup_plans_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backup_plans( - backupplan.ListBackupPlansRequest(), + client.fetch_usable_backup_vaults( + backupvault.FetchUsableBackupVaultsRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_backup_plans_flattened_async(): +async def test_fetch_usable_backup_vaults_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" + type(client.transport.fetch_usable_backup_vaults), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.ListBackupPlansResponse() + call.return_value = backupvault.FetchUsableBackupVaultsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlansResponse() + backupvault.FetchUsableBackupVaultsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_backup_plans( + response = await client.fetch_usable_backup_vaults( parent="parent_value", ) @@ -10515,7 +11374,7 @@ async def test_list_backup_plans_flattened_async(): @pytest.mark.asyncio -async def test_list_backup_plans_flattened_error_async(): +async def test_fetch_usable_backup_vaults_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10523,13 +11382,13 @@ async def test_list_backup_plans_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.list_backup_plans( - backupplan.ListBackupPlansRequest(), + await client.fetch_usable_backup_vaults( + backupvault.FetchUsableBackupVaultsRequest(), parent="parent_value", ) -def test_list_backup_plans_pager(transport_name: str = "grpc"): +def test_fetch_usable_backup_vaults_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -10537,32 +11396,32 @@ def test_list_backup_plans_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" + type(client.transport.fetch_usable_backup_vaults), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), ], next_page_token="abc", ), - backupplan.ListBackupPlansResponse( - backup_plans=[], + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], next_page_token="def", ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), ], next_page_token="ghi", ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), ], ), RuntimeError, @@ -10574,7 +11433,9 @@ def test_list_backup_plans_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_backup_plans(request={}, retry=retry, timeout=timeout) + pager = client.fetch_usable_backup_vaults( + request={}, retry=retry, timeout=timeout + ) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -10585,10 +11446,10 @@ def test_list_backup_plans_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, backupplan.BackupPlan) for i in results) + assert all(isinstance(i, backupvault.BackupVault) for i in results) -def test_list_backup_plans_pages(transport_name: str = "grpc"): +def test_fetch_usable_backup_vaults_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -10596,82 +11457,82 @@ def test_list_backup_plans_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" + type(client.transport.fetch_usable_backup_vaults), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), ], next_page_token="abc", ), - backupplan.ListBackupPlansResponse( - backup_plans=[], + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], next_page_token="def", ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), ], next_page_token="ghi", ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), - ], + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], ), RuntimeError, ) - pages = list(client.list_backup_plans(request={}).pages) + pages = list(client.fetch_usable_backup_vaults(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_backup_plans_async_pager(): +async def test_fetch_usable_backup_vaults_async_pager(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), + type(client.transport.fetch_usable_backup_vaults), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), ], next_page_token="abc", ), - backupplan.ListBackupPlansResponse( - backup_plans=[], + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], next_page_token="def", ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), ], next_page_token="ghi", ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), ], ), RuntimeError, ) - async_pager = await client.list_backup_plans( + async_pager = await client.fetch_usable_backup_vaults( request={}, ) assert async_pager.next_page_token == "abc" @@ -10682,51 +11543,51 @@ async def test_list_backup_plans_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, backupplan.BackupPlan) for i in responses) + assert all(isinstance(i, backupvault.BackupVault) for i in responses) @pytest.mark.asyncio -async def test_list_backup_plans_async_pages(): +async def test_fetch_usable_backup_vaults_async_pages(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plans), + type(client.transport.fetch_usable_backup_vaults), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), ], next_page_token="abc", ), - backupplan.ListBackupPlansResponse( - backup_plans=[], + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], next_page_token="def", ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), ], next_page_token="ghi", ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), ], ), RuntimeError, ) pages = [] - async for page_ in (await client.list_backup_plans(request={})).pages: + async for page_ in (await client.fetch_usable_backup_vaults(request={})).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -10735,11 +11596,11 @@ async def test_list_backup_plans_async_pages(): @pytest.mark.parametrize( "request_type", [ - backupplan.DeleteBackupPlanRequest(), + backupvault.GetBackupVaultRequest(), {}, ], ) -def test_delete_backup_plan(request_type, transport: str = "grpc"): +def test_get_backup_vault(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10750,24 +11611,51 @@ def test_delete_backup_plan(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.delete_backup_plan), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_backup_plan(request) + call.return_value = backupvault.BackupVault( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + deletable=True, + etag="etag_value", + state=backupvault.BackupVault.State.CREATING, + backup_count=1278, + service_account="service_account_value", + total_stored_bytes=1946, + uid="uid_value", + access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + ) + response = client.get_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplan.DeleteBackupPlanRequest() + request = backupvault.GetBackupVaultRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, backupvault.BackupVault) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.deletable is True + assert response.etag == "etag_value" + assert response.state == backupvault.BackupVault.State.CREATING + assert response.backup_count == 1278 + assert response.service_account == "service_account_value" + assert response.total_stored_bytes == 1946 + assert response.uid == "uid_value" + assert ( + response.access_restriction + == backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT + ) -def test_delete_backup_plan_non_empty_request_with_auto_populated_field(): +def test_get_backup_vault_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 = BackupDRClient( @@ -10778,27 +11666,25 @@ def test_delete_backup_plan_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 = backupplan.DeleteBackupPlanRequest( + request = backupvault.GetBackupVaultRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_backup_plan(request=request) + client.get_backup_vault(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplan.DeleteBackupPlanRequest( + request_msg = backupvault.GetBackupVaultRequest( name="name_value", ) assert args[0] == request_msg -def test_delete_backup_plan_use_cached_wrapped_rpc(): +def test_get_backup_vault_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: @@ -10812,30 +11698,23 @@ def test_delete_backup_plan_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_backup_plan in client._transport._wrapped_methods - ) + assert client._transport.get_backup_vault 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_plan] = ( + client._transport._wrapped_methods[client._transport.get_backup_vault] = ( mock_rpc ) request = {} - client.delete_backup_plan(request) + client.get_backup_vault(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_plan(request) + client.get_backup_vault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10843,7 +11722,7 @@ def test_delete_backup_plan_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_backup_plan_async_use_cached_wrapped_rpc( +async def test_get_backup_vault_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10860,7 +11739,7 @@ async def test_delete_backup_plan_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_backup_plan + client._client._transport.get_backup_vault in client._client._transport._wrapped_methods ) @@ -10868,21 +11747,16 @@ async def test_delete_backup_plan_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_backup_plan + client._client._transport.get_backup_vault ] = mock_rpc request = {} - await client.delete_backup_plan(request) + await client.get_backup_vault(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_plan(request) + await client.get_backup_vault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10893,11 +11767,11 @@ async def test_delete_backup_plan_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplan.DeleteBackupPlanRequest(), + backupvault.GetBackupVaultRequest(), {}, ], ) -async def test_delete_backup_plan_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_backup_vault_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -10908,42 +11782,67 @@ async def test_delete_backup_plan_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.delete_backup_plan), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupvault.BackupVault( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + deletable=True, + etag="etag_value", + state=backupvault.BackupVault.State.CREATING, + backup_count=1278, + service_account="service_account_value", + total_stored_bytes=1946, + uid="uid_value", + access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + ) ) - response = await client.delete_backup_plan(request) + response = await client.get_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplan.DeleteBackupPlanRequest() + request = backupvault.GetBackupVaultRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, backupvault.BackupVault) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.deletable is True + assert response.etag == "etag_value" + assert response.state == backupvault.BackupVault.State.CREATING + assert response.backup_count == 1278 + assert response.service_account == "service_account_value" + assert response.total_stored_bytes == 1946 + assert response.uid == "uid_value" + assert ( + response.access_restriction + == backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT + ) -def test_delete_backup_plan_field_headers(): +def test_get_backup_vault_field_headers(): client = BackupDRClient( 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 = backupplan.DeleteBackupPlanRequest() + request = backupvault.GetBackupVaultRequest() 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_plan), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup_plan(request) + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + call.return_value = backupvault.BackupVault() + client.get_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10959,25 +11858,23 @@ def test_delete_backup_plan_field_headers(): @pytest.mark.asyncio -async def test_delete_backup_plan_field_headers_async(): +async def test_get_backup_vault_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplan.DeleteBackupPlanRequest() + request = backupvault.GetBackupVaultRequest() 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_plan), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + backupvault.BackupVault() ) - await client.delete_backup_plan(request) + await client.get_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10992,20 +11889,18 @@ async def test_delete_backup_plan_field_headers_async(): ) in kw["metadata"] -def test_delete_backup_plan_flattened(): +def test_get_backup_vault_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupvault.BackupVault() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_backup_plan( + client.get_backup_vault( name="name_value", ) @@ -11018,7 +11913,7 @@ def test_delete_backup_plan_flattened(): assert arg == mock_val -def test_delete_backup_plan_flattened_error(): +def test_get_backup_vault_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11026,31 +11921,29 @@ def test_delete_backup_plan_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_backup_plan( - backupplan.DeleteBackupPlanRequest(), + client.get_backup_vault( + backupvault.GetBackupVaultRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_backup_plan_flattened_async(): +async def test_get_backup_vault_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupvault.BackupVault() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupvault.BackupVault() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_backup_plan( + response = await client.get_backup_vault( name="name_value", ) @@ -11064,7 +11957,7 @@ async def test_delete_backup_plan_flattened_async(): @pytest.mark.asyncio -async def test_delete_backup_plan_flattened_error_async(): +async def test_get_backup_vault_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11072,8 +11965,8 @@ async def test_delete_backup_plan_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.delete_backup_plan( - backupplan.DeleteBackupPlanRequest(), + await client.get_backup_vault( + backupvault.GetBackupVaultRequest(), name="name_value", ) @@ -11081,11 +11974,11 @@ async def test_delete_backup_plan_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - backupplan.GetBackupPlanRevisionRequest(), + backupvault.UpdateBackupVaultRequest(), {}, ], ) -def test_get_backup_plan_revision(request_type, transport: str = "grpc"): +def test_update_backup_vault(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11097,30 +11990,23 @@ def test_get_backup_plan_revision(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_revision), "__call__" + type(client.transport.update_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.BackupPlanRevision( - name="name_value", - revision_id="revision_id_value", - state=backupplan.BackupPlanRevision.State.CREATING, - ) - response = client.get_backup_plan_revision(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplan.GetBackupPlanRevisionRequest() + request = backupvault.UpdateBackupVaultRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupplan.BackupPlanRevision) - assert response.name == "name_value" - assert response.revision_id == "revision_id_value" - assert response.state == backupplan.BackupPlanRevision.State.CREATING + assert isinstance(response, future.Future) -def test_get_backup_plan_revision_non_empty_request_with_auto_populated_field(): +def test_update_backup_vault_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 = BackupDRClient( @@ -11131,27 +12017,23 @@ def test_get_backup_plan_revision_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 = backupplan.GetBackupPlanRevisionRequest( - name="name_value", - ) + request = backupvault.UpdateBackupVaultRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_revision), "__call__" + type(client.transport.update_backup_vault), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_backup_plan_revision(request=request) + client.update_backup_vault(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplan.GetBackupPlanRevisionRequest( - name="name_value", - ) + request_msg = backupvault.UpdateBackupVaultRequest() assert args[0] == request_msg -def test_get_backup_plan_revision_use_cached_wrapped_rpc(): +def test_update_backup_vault_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: @@ -11166,8 +12048,7 @@ def test_get_backup_plan_revision_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_backup_plan_revision - in client._transport._wrapped_methods + client._transport.update_backup_vault in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -11175,16 +12056,21 @@ def test_get_backup_plan_revision_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.get_backup_plan_revision - ] = mock_rpc + client._transport._wrapped_methods[client._transport.update_backup_vault] = ( + mock_rpc + ) request = {} - client.get_backup_plan_revision(request) + client.update_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup_plan_revision(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.update_backup_vault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11192,7 +12078,7 @@ def test_get_backup_plan_revision_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_backup_plan_revision_async_use_cached_wrapped_rpc( +async def test_update_backup_vault_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11209,7 +12095,7 @@ async def test_get_backup_plan_revision_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_backup_plan_revision + client._client._transport.update_backup_vault in client._client._transport._wrapped_methods ) @@ -11217,16 +12103,21 @@ async def test_get_backup_plan_revision_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_backup_plan_revision + client._client._transport.update_backup_vault ] = mock_rpc request = {} - await client.get_backup_plan_revision(request) + await client.update_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_backup_plan_revision(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() + + await client.update_backup_vault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11237,13 +12128,11 @@ async def test_get_backup_plan_revision_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplan.GetBackupPlanRevisionRequest(), + backupvault.UpdateBackupVaultRequest(), {}, ], ) -async def test_get_backup_plan_revision_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_update_backup_vault_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -11255,48 +12144,41 @@ async def test_get_backup_plan_revision_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_revision), "__call__" + type(client.transport.update_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlanRevision( - name="name_value", - revision_id="revision_id_value", - state=backupplan.BackupPlanRevision.State.CREATING, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_backup_plan_revision(request) + response = await client.update_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplan.GetBackupPlanRevisionRequest() + request = backupvault.UpdateBackupVaultRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupplan.BackupPlanRevision) - assert response.name == "name_value" - assert response.revision_id == "revision_id_value" - assert response.state == backupplan.BackupPlanRevision.State.CREATING + assert isinstance(response, future.Future) -def test_get_backup_plan_revision_field_headers(): +def test_update_backup_vault_field_headers(): client = BackupDRClient( 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 = backupplan.GetBackupPlanRevisionRequest() + request = backupvault.UpdateBackupVaultRequest() - request.name = "name_value" + request.backup_vault.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_revision), "__call__" + type(client.transport.update_backup_vault), "__call__" ) as call: - call.return_value = backupplan.BackupPlanRevision() - client.get_backup_plan_revision(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11307,30 +12189,30 @@ def test_get_backup_plan_revision_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "backup_vault.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_backup_plan_revision_field_headers_async(): +async def test_update_backup_vault_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplan.GetBackupPlanRevisionRequest() + request = backupvault.UpdateBackupVaultRequest() - request.name = "name_value" + request.backup_vault.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_revision), "__call__" + type(client.transport.update_backup_vault), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlanRevision() + operations_pb2.Operation(name="operations/op") ) - await client.get_backup_plan_revision(request) + await client.update_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11341,37 +12223,41 @@ async def test_get_backup_plan_revision_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "backup_vault.name=name_value", ) in kw["metadata"] -def test_get_backup_plan_revision_flattened(): +def test_update_backup_vault_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_revision), "__call__" + type(client.transport.update_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.BackupPlanRevision() + 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.get_backup_plan_revision( - name="name_value", + client.update_backup_vault( + backup_vault=backupvault.BackupVault(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].backup_vault + mock_val = backupvault.BackupVault(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_get_backup_plan_revision_flattened_error(): +def test_update_backup_vault_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11379,45 +12265,50 @@ def test_get_backup_plan_revision_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_backup_plan_revision( - backupplan.GetBackupPlanRevisionRequest(), - name="name_value", + client.update_backup_vault( + backupvault.UpdateBackupVaultRequest(), + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_get_backup_plan_revision_flattened_async(): +async def test_update_backup_vault_flattened_async(): client = BackupDRAsyncClient( 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_plan_revision), "__call__" + type(client.transport.update_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.BackupPlanRevision() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlanRevision() + 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.get_backup_plan_revision( - name="name_value", + response = await client.update_backup_vault( + backup_vault=backupvault.BackupVault(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].backup_vault + mock_val = backupvault.BackupVault(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_get_backup_plan_revision_flattened_error_async(): +async def test_update_backup_vault_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11425,20 +12316,21 @@ async def test_get_backup_plan_revision_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.get_backup_plan_revision( - backupplan.GetBackupPlanRevisionRequest(), - name="name_value", + await client.update_backup_vault( + backupvault.UpdateBackupVaultRequest(), + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - backupplan.ListBackupPlanRevisionsRequest(), + backupvault.DeleteBackupVaultRequest(), {}, ], ) -def test_list_backup_plan_revisions(request_type, transport: str = "grpc"): +def test_delete_backup_vault(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11450,28 +12342,23 @@ def test_list_backup_plan_revisions(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plan_revisions), "__call__" + type(client.transport.delete_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.ListBackupPlanRevisionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_backup_plan_revisions(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplan.ListBackupPlanRevisionsRequest() + request = backupvault.DeleteBackupVaultRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupPlanRevisionsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_backup_plan_revisions_non_empty_request_with_auto_populated_field(): +def test_delete_backup_vault_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 = BackupDRClient( @@ -11482,29 +12369,29 @@ def test_list_backup_plan_revisions_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 = backupplan.ListBackupPlanRevisionsRequest( - parent="parent_value", - page_token="page_token_value", + request = backupvault.DeleteBackupVaultRequest( + name="name_value", + etag="etag_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plan_revisions), "__call__" + type(client.transport.delete_backup_vault), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_backup_plan_revisions(request=request) + client.delete_backup_vault(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplan.ListBackupPlanRevisionsRequest( - parent="parent_value", - page_token="page_token_value", + request_msg = backupvault.DeleteBackupVaultRequest( + name="name_value", + etag="etag_value", ) assert args[0] == request_msg -def test_list_backup_plan_revisions_use_cached_wrapped_rpc(): +def test_delete_backup_vault_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: @@ -11519,8 +12406,7 @@ def test_list_backup_plan_revisions_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_backup_plan_revisions - in client._transport._wrapped_methods + client._transport.delete_backup_vault in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -11528,16 +12414,21 @@ def test_list_backup_plan_revisions_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_backup_plan_revisions - ] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_backup_vault] = ( + mock_rpc + ) request = {} - client.list_backup_plan_revisions(request) + client.delete_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backup_plan_revisions(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.delete_backup_vault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11545,7 +12436,7 @@ def test_list_backup_plan_revisions_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_backup_plan_revisions_async_use_cached_wrapped_rpc( +async def test_delete_backup_vault_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11562,7 +12453,7 @@ async def test_list_backup_plan_revisions_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_backup_plan_revisions + client._client._transport.delete_backup_vault in client._client._transport._wrapped_methods ) @@ -11570,16 +12461,21 @@ async def test_list_backup_plan_revisions_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_backup_plan_revisions + client._client._transport.delete_backup_vault ] = mock_rpc request = {} - await client.list_backup_plan_revisions(request) + await client.delete_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_backup_plan_revisions(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() + + await client.delete_backup_vault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11590,13 +12486,11 @@ async def test_list_backup_plan_revisions_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplan.ListBackupPlanRevisionsRequest(), + backupvault.DeleteBackupVaultRequest(), {}, ], ) -async def test_list_backup_plan_revisions_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_delete_backup_vault_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -11608,46 +12502,41 @@ async def test_list_backup_plan_revisions_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plan_revisions), "__call__" + type(client.transport.delete_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlanRevisionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_backup_plan_revisions(request) + response = await client.delete_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplan.ListBackupPlanRevisionsRequest() + request = backupvault.DeleteBackupVaultRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupPlanRevisionsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_backup_plan_revisions_field_headers(): +def test_delete_backup_vault_field_headers(): client = BackupDRClient( 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 = backupplan.ListBackupPlanRevisionsRequest() + request = backupvault.DeleteBackupVaultRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plan_revisions), "__call__" + type(client.transport.delete_backup_vault), "__call__" ) as call: - call.return_value = backupplan.ListBackupPlanRevisionsResponse() - client.list_backup_plan_revisions(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11658,30 +12547,30 @@ def test_list_backup_plan_revisions_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_backup_plan_revisions_field_headers_async(): +async def test_delete_backup_vault_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplan.ListBackupPlanRevisionsRequest() + request = backupvault.DeleteBackupVaultRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plan_revisions), "__call__" + type(client.transport.delete_backup_vault), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlanRevisionsResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_backup_plan_revisions(request) + await client.delete_backup_vault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11692,37 +12581,37 @@ async def test_list_backup_plan_revisions_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_backup_plan_revisions_flattened(): +def test_delete_backup_vault_flattened(): client = BackupDRClient( 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_plan_revisions), "__call__" + type(client.transport.delete_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.ListBackupPlanRevisionsResponse() + 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.list_backup_plan_revisions( - parent="parent_value", + client.delete_backup_vault( + 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_backup_plan_revisions_flattened_error(): +def test_delete_backup_vault_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11730,45 +12619,45 @@ def test_list_backup_plan_revisions_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backup_plan_revisions( - backupplan.ListBackupPlanRevisionsRequest(), - parent="parent_value", + client.delete_backup_vault( + backupvault.DeleteBackupVaultRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_backup_plan_revisions_flattened_async(): +async def test_delete_backup_vault_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plan_revisions), "__call__" + type(client.transport.delete_backup_vault), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplan.ListBackupPlanRevisionsResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlanRevisionsResponse() + 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.list_backup_plan_revisions( - parent="parent_value", + response = await client.delete_backup_vault( + 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_backup_plan_revisions_flattened_error_async(): +async def test_delete_backup_vault_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11776,225 +12665,20 @@ async def test_list_backup_plan_revisions_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.list_backup_plan_revisions( - backupplan.ListBackupPlanRevisionsRequest(), - parent="parent_value", - ) - - -def test_list_backup_plan_revisions_pager(transport_name: str = "grpc"): - client = BackupDRClient( - 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_backup_plan_revisions), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - next_page_token="abc", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[], - next_page_token="def", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - ], - next_page_token="ghi", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_backup_plan_revisions( - 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, backupplan.BackupPlanRevision) for i in results) - - -def test_list_backup_plan_revisions_pages(transport_name: str = "grpc"): - client = BackupDRClient( - 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_backup_plan_revisions), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - next_page_token="abc", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[], - next_page_token="def", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - ], - next_page_token="ghi", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - ), - RuntimeError, - ) - pages = list(client.list_backup_plan_revisions(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_backup_plan_revisions_async_pager(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_revisions), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - next_page_token="abc", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[], - next_page_token="def", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - ], - next_page_token="ghi", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_backup_plan_revisions( - 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, backupplan.BackupPlanRevision) for i in responses) - - -@pytest.mark.asyncio -async def test_list_backup_plan_revisions_async_pages(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_revisions), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - next_page_token="abc", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[], - next_page_token="def", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - ], - next_page_token="ghi", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - ), - RuntimeError, + await client.delete_backup_vault( + backupvault.DeleteBackupVaultRequest(), + name="name_value", ) - pages = [] - async for page_ in (await client.list_backup_plan_revisions(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", [ - backupplanassociation.CreateBackupPlanAssociationRequest(), + backupvault.ListDataSourcesRequest(), {}, ], ) -def test_create_backup_plan_association(request_type, transport: str = "grpc"): +def test_list_data_sources(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12006,23 +12690,28 @@ def test_create_backup_plan_association(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_backup_plan_association), "__call__" + type(client.transport.list_data_sources), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_backup_plan_association(request) + call.return_value = backupvault.ListDataSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_data_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplanassociation.CreateBackupPlanAssociationRequest() + request = backupvault.ListDataSourcesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListDataSourcesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_create_backup_plan_association_non_empty_request_with_auto_populated_field(): +def test_list_data_sources_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 = BackupDRClient( @@ -12033,29 +12722,33 @@ def test_create_backup_plan_association_non_empty_request_with_auto_populated_fi # 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 = backupplanassociation.CreateBackupPlanAssociationRequest( + request = backupvault.ListDataSourcesRequest( parent="parent_value", - backup_plan_association_id="backup_plan_association_id_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.create_backup_plan_association), "__call__" + type(client.transport.list_data_sources), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_backup_plan_association(request=request) + client.list_data_sources(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.CreateBackupPlanAssociationRequest( + request_msg = backupvault.ListDataSourcesRequest( parent="parent_value", - backup_plan_association_id="backup_plan_association_id_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) assert args[0] == request_msg -def test_create_backup_plan_association_use_cached_wrapped_rpc(): +def test_list_data_sources_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: @@ -12069,31 +12762,23 @@ def test_create_backup_plan_association_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_backup_plan_association - in client._transport._wrapped_methods - ) + assert client._transport.list_data_sources 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_backup_plan_association - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_data_sources] = ( + mock_rpc + ) request = {} - client.create_backup_plan_association(request) + client.list_data_sources(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.create_backup_plan_association(request) + client.list_data_sources(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12101,7 +12786,7 @@ def test_create_backup_plan_association_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_backup_plan_association_async_use_cached_wrapped_rpc( +async def test_list_data_sources_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -12118,7 +12803,7 @@ async def test_create_backup_plan_association_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_backup_plan_association + client._client._transport.list_data_sources in client._client._transport._wrapped_methods ) @@ -12126,21 +12811,16 @@ async def test_create_backup_plan_association_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_backup_plan_association + client._client._transport.list_data_sources ] = mock_rpc request = {} - await client.create_backup_plan_association(request) + await client.list_data_sources(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.create_backup_plan_association(request) + await client.list_data_sources(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12151,13 +12831,11 @@ async def test_create_backup_plan_association_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplanassociation.CreateBackupPlanAssociationRequest(), + backupvault.ListDataSourcesRequest(), {}, ], ) -async def test_create_backup_plan_association_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_list_data_sources_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -12169,41 +12847,46 @@ async def test_create_backup_plan_association_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan_association), "__call__" + type(client.transport.list_data_sources), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupvault.ListDataSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.create_backup_plan_association(request) + response = await client.list_data_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplanassociation.CreateBackupPlanAssociationRequest() + request = backupvault.ListDataSourcesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListDataSourcesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_create_backup_plan_association_field_headers(): +def test_list_data_sources_field_headers(): client = BackupDRClient( 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 = backupplanassociation.CreateBackupPlanAssociationRequest() + request = backupvault.ListDataSourcesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan_association), "__call__" + type(client.transport.list_data_sources), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup_plan_association(request) + call.return_value = backupvault.ListDataSourcesResponse() + client.list_data_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12219,25 +12902,25 @@ def test_create_backup_plan_association_field_headers(): @pytest.mark.asyncio -async def test_create_backup_plan_association_field_headers_async(): +async def test_list_data_sources_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplanassociation.CreateBackupPlanAssociationRequest() + request = backupvault.ListDataSourcesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan_association), "__call__" + type(client.transport.list_data_sources), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + backupvault.ListDataSourcesResponse() ) - await client.create_backup_plan_association(request) + await client.list_data_sources(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12252,27 +12935,21 @@ async def test_create_backup_plan_association_field_headers_async(): ) in kw["metadata"] -def test_create_backup_plan_association_flattened(): +def test_list_data_sources_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan_association), "__call__" + type(client.transport.list_data_sources), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupvault.ListDataSourcesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_backup_plan_association( + client.list_data_sources( parent="parent_value", - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - backup_plan_association_id="backup_plan_association_id_value", ) # Establish that the underlying call was made with the expected @@ -12282,19 +12959,9 @@ def test_create_backup_plan_association_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].backup_plan_association - mock_val = backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ) - assert arg == mock_val - arg = args[0].backup_plan_association_id - mock_val = "backup_plan_association_id_value" - assert arg == mock_val -def test_create_backup_plan_association_flattened_error(): +def test_list_data_sources_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12302,44 +12969,32 @@ def test_create_backup_plan_association_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_backup_plan_association( - backupplanassociation.CreateBackupPlanAssociationRequest(), + client.list_data_sources( + backupvault.ListDataSourcesRequest(), parent="parent_value", - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - backup_plan_association_id="backup_plan_association_id_value", ) @pytest.mark.asyncio -async def test_create_backup_plan_association_flattened_async(): +async def test_list_data_sources_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_backup_plan_association), "__call__" + type(client.transport.list_data_sources), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupvault.ListDataSourcesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupvault.ListDataSourcesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_backup_plan_association( + response = await client.list_data_sources( parent="parent_value", - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - backup_plan_association_id="backup_plan_association_id_value", ) # Establish that the underlying call was made with the expected @@ -12349,20 +13004,10 @@ async def test_create_backup_plan_association_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].backup_plan_association - mock_val = backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ) - assert arg == mock_val - arg = args[0].backup_plan_association_id - mock_val = "backup_plan_association_id_value" - assert arg == mock_val @pytest.mark.asyncio -async def test_create_backup_plan_association_flattened_error_async(): +async def test_list_data_sources_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12370,54 +13015,264 @@ async def test_create_backup_plan_association_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.create_backup_plan_association( - backupplanassociation.CreateBackupPlanAssociationRequest(), + await client.list_data_sources( + backupvault.ListDataSourcesRequest(), parent="parent_value", - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - backup_plan_association_id="backup_plan_association_id_value", ) -@pytest.mark.parametrize( - "request_type", - [ - backupplanassociation.UpdateBackupPlanAssociationRequest(), - {}, - ], -) -def test_update_backup_plan_association(request_type, transport: str = "grpc"): +def test_list_data_sources_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_backup_plan_association), "__call__" + type(client.transport.list_data_sources), "__call__" ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_data_sources(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, backupvault.DataSource) for i in results) + + +def test_list_data_sources_pages(transport_name: str = "grpc"): + client = BackupDRClient( + 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_data_sources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_sources(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_data_sources_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_sources( + 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, backupvault.DataSource) for i in responses) + + +@pytest.mark.asyncio +async def test_list_data_sources_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_data_sources(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", + [ + backupvault.GetDataSourceRequest(), + {}, + ], +) +def test_get_data_source(request_type, transport: str = "grpc"): + client = BackupDRClient( + 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_data_source), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_backup_plan_association(request) + call.return_value = backupvault.DataSource( + name="name_value", + state=backupvault.DataSource.State.CREATING, + backup_count=1278, + etag="etag_value", + total_stored_bytes=1946, + config_state=backupvault.BackupConfigState.ACTIVE, + backup_blocked_by_vault_access_restriction=True, + ) + response = client.get_data_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplanassociation.UpdateBackupPlanAssociationRequest() + request = backupvault.GetDataSourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, backupvault.DataSource) + assert response.name == "name_value" + assert response.state == backupvault.DataSource.State.CREATING + assert response.backup_count == 1278 + assert response.etag == "etag_value" + assert response.total_stored_bytes == 1946 + assert response.config_state == backupvault.BackupConfigState.ACTIVE + assert response.backup_blocked_by_vault_access_restriction is True -def test_update_backup_plan_association_non_empty_request_with_auto_populated_field(): +def test_get_data_source_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 = BackupDRClient( @@ -12428,23 +13283,25 @@ def test_update_backup_plan_association_non_empty_request_with_auto_populated_fi # 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 = backupplanassociation.UpdateBackupPlanAssociationRequest() + request = backupvault.GetDataSourceRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan_association), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_backup_plan_association(request=request) + client.get_data_source(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() + request_msg = backupvault.GetDataSourceRequest( + name="name_value", + ) assert args[0] == request_msg -def test_update_backup_plan_association_use_cached_wrapped_rpc(): +def test_get_data_source_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: @@ -12458,31 +13315,21 @@ def test_update_backup_plan_association_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_backup_plan_association - in client._transport._wrapped_methods - ) + assert client._transport.get_data_source 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_backup_plan_association - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_data_source] = mock_rpc request = {} - client.update_backup_plan_association(request) + client.get_data_source(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.update_backup_plan_association(request) + client.get_data_source(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12490,7 +13337,7 @@ def test_update_backup_plan_association_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_backup_plan_association_async_use_cached_wrapped_rpc( +async def test_get_data_source_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -12507,7 +13354,7 @@ async def test_update_backup_plan_association_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_backup_plan_association + client._client._transport.get_data_source in client._client._transport._wrapped_methods ) @@ -12515,21 +13362,16 @@ async def test_update_backup_plan_association_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_backup_plan_association + client._client._transport.get_data_source ] = mock_rpc request = {} - await client.update_backup_plan_association(request) + await client.get_data_source(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.update_backup_plan_association(request) + await client.get_data_source(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12540,13 +13382,11 @@ async def test_update_backup_plan_association_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplanassociation.UpdateBackupPlanAssociationRequest(), + backupvault.GetDataSourceRequest(), {}, ], ) -async def test_update_backup_plan_association_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_get_data_source_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -12557,42 +13397,53 @@ async def test_update_backup_plan_association_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan_association), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupvault.DataSource( + name="name_value", + state=backupvault.DataSource.State.CREATING, + backup_count=1278, + etag="etag_value", + total_stored_bytes=1946, + config_state=backupvault.BackupConfigState.ACTIVE, + backup_blocked_by_vault_access_restriction=True, + ) ) - response = await client.update_backup_plan_association(request) + response = await client.get_data_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplanassociation.UpdateBackupPlanAssociationRequest() + request = backupvault.GetDataSourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, backupvault.DataSource) + assert response.name == "name_value" + assert response.state == backupvault.DataSource.State.CREATING + assert response.backup_count == 1278 + assert response.etag == "etag_value" + assert response.total_stored_bytes == 1946 + assert response.config_state == backupvault.BackupConfigState.ACTIVE + assert response.backup_blocked_by_vault_access_restriction is True -def test_update_backup_plan_association_field_headers(): +def test_get_data_source_field_headers(): client = BackupDRClient( 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 = backupplanassociation.UpdateBackupPlanAssociationRequest() + request = backupvault.GetDataSourceRequest() - request.backup_plan_association.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_backup_plan_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup_plan_association(request) + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + call.return_value = backupvault.DataSource() + client.get_data_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12603,30 +13454,28 @@ def test_update_backup_plan_association_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup_plan_association.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_backup_plan_association_field_headers_async(): +async def test_get_data_source_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplanassociation.UpdateBackupPlanAssociationRequest() + request = backupvault.GetDataSourceRequest() - request.backup_plan_association.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_backup_plan_association), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + backupvault.DataSource() ) - await client.update_backup_plan_association(request) + await client.get_data_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12637,49 +13486,35 @@ async def test_update_backup_plan_association_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup_plan_association.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_backup_plan_association_flattened(): +def test_get_data_source_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan_association), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupvault.DataSource() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_backup_plan_association( - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_data_source( + 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].backup_plan_association - mock_val = backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_backup_plan_association_flattened_error(): +def test_get_data_source_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12687,62 +13522,43 @@ def test_update_backup_plan_association_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_backup_plan_association( - backupplanassociation.UpdateBackupPlanAssociationRequest(), - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_data_source( + backupvault.GetDataSourceRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_backup_plan_association_flattened_async(): +async def test_get_data_source_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan_association), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupvault.DataSource() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupvault.DataSource() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_backup_plan_association( - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.get_data_source( + 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].backup_plan_association - mock_val = backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ) - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_backup_plan_association_flattened_error_async(): +async def test_get_data_source_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12750,25 +13566,20 @@ async def test_update_backup_plan_association_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_backup_plan_association( - backupplanassociation.UpdateBackupPlanAssociationRequest(), - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.get_data_source( + backupvault.GetDataSourceRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - backupplanassociation.GetBackupPlanAssociationRequest(), + backupvault.UpdateDataSourceRequest(), {}, ], ) -def test_get_backup_plan_association(request_type, transport: str = "grpc"): +def test_update_data_source(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12780,45 +13591,23 @@ def test_get_backup_plan_association(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" + type(client.transport.update_data_source), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplanassociation.BackupPlanAssociation( - name="name_value", - resource_type="resource_type_value", - resource="resource_value", - backup_plan="backup_plan_value", - state=backupplanassociation.BackupPlanAssociation.State.CREATING, - data_source="data_source_value", - backup_plan_revision_id="backup_plan_revision_id_value", - backup_plan_revision_name="backup_plan_revision_name_value", - auto_protection_policy_binding="auto_protection_policy_binding_value", - ) - response = client.get_backup_plan_association(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_data_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplanassociation.GetBackupPlanAssociationRequest() + request = backupvault.UpdateDataSourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupplanassociation.BackupPlanAssociation) - assert response.name == "name_value" - assert response.resource_type == "resource_type_value" - assert response.resource == "resource_value" - assert response.backup_plan == "backup_plan_value" - assert response.state == backupplanassociation.BackupPlanAssociation.State.CREATING - assert response.data_source == "data_source_value" - assert response.backup_plan_revision_id == "backup_plan_revision_id_value" - assert response.backup_plan_revision_name == "backup_plan_revision_name_value" - assert ( - response.auto_protection_policy_binding - == "auto_protection_policy_binding_value" - ) + assert isinstance(response, future.Future) -def test_get_backup_plan_association_non_empty_request_with_auto_populated_field(): +def test_update_data_source_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 = BackupDRClient( @@ -12829,27 +13618,23 @@ def test_get_backup_plan_association_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 = backupplanassociation.GetBackupPlanAssociationRequest( - name="name_value", - ) + request = backupvault.UpdateDataSourceRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" + type(client.transport.update_data_source), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_backup_plan_association(request=request) + client.update_data_source(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.GetBackupPlanAssociationRequest( - name="name_value", - ) + request_msg = backupvault.UpdateDataSourceRequest() assert args[0] == request_msg -def test_get_backup_plan_association_use_cached_wrapped_rpc(): +def test_update_data_source_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: @@ -12864,8 +13649,7 @@ def test_get_backup_plan_association_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_backup_plan_association - in client._transport._wrapped_methods + client._transport.update_data_source in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -12873,16 +13657,21 @@ def test_get_backup_plan_association_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.get_backup_plan_association - ] = mock_rpc + client._transport._wrapped_methods[client._transport.update_data_source] = ( + mock_rpc + ) request = {} - client.get_backup_plan_association(request) + client.update_data_source(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup_plan_association(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.update_data_source(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12890,7 +13679,7 @@ def test_get_backup_plan_association_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_backup_plan_association_async_use_cached_wrapped_rpc( +async def test_update_data_source_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -12907,7 +13696,7 @@ async def test_get_backup_plan_association_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_backup_plan_association + client._client._transport.update_data_source in client._client._transport._wrapped_methods ) @@ -12915,16 +13704,21 @@ async def test_get_backup_plan_association_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_backup_plan_association + client._client._transport.update_data_source ] = mock_rpc request = {} - await client.get_backup_plan_association(request) + await client.update_data_source(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_backup_plan_association(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() + + await client.update_data_source(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12935,13 +13729,11 @@ async def test_get_backup_plan_association_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplanassociation.GetBackupPlanAssociationRequest(), + backupvault.UpdateDataSourceRequest(), {}, ], ) -async def test_get_backup_plan_association_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_update_data_source_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -12953,63 +13745,41 @@ async def test_get_backup_plan_association_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" + type(client.transport.update_data_source), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.BackupPlanAssociation( - name="name_value", - resource_type="resource_type_value", - resource="resource_value", - backup_plan="backup_plan_value", - state=backupplanassociation.BackupPlanAssociation.State.CREATING, - data_source="data_source_value", - backup_plan_revision_id="backup_plan_revision_id_value", - backup_plan_revision_name="backup_plan_revision_name_value", - auto_protection_policy_binding="auto_protection_policy_binding_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_backup_plan_association(request) + response = await client.update_data_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplanassociation.GetBackupPlanAssociationRequest() + request = backupvault.UpdateDataSourceRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, backupplanassociation.BackupPlanAssociation) - assert response.name == "name_value" - assert response.resource_type == "resource_type_value" - assert response.resource == "resource_value" - assert response.backup_plan == "backup_plan_value" - assert response.state == backupplanassociation.BackupPlanAssociation.State.CREATING - assert response.data_source == "data_source_value" - assert response.backup_plan_revision_id == "backup_plan_revision_id_value" - assert response.backup_plan_revision_name == "backup_plan_revision_name_value" - assert ( - response.auto_protection_policy_binding - == "auto_protection_policy_binding_value" - ) + assert isinstance(response, future.Future) -def test_get_backup_plan_association_field_headers(): +def test_update_data_source_field_headers(): client = BackupDRClient( 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 = backupplanassociation.GetBackupPlanAssociationRequest() + request = backupvault.UpdateDataSourceRequest() - request.name = "name_value" + request.data_source.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" + type(client.transport.update_data_source), "__call__" ) as call: - call.return_value = backupplanassociation.BackupPlanAssociation() - client.get_backup_plan_association(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_data_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13020,30 +13790,30 @@ def test_get_backup_plan_association_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "data_source.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_backup_plan_association_field_headers_async(): +async def test_update_data_source_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplanassociation.GetBackupPlanAssociationRequest() + request = backupvault.UpdateDataSourceRequest() - request.name = "name_value" + request.data_source.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" + type(client.transport.update_data_source), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.BackupPlanAssociation() + operations_pb2.Operation(name="operations/op") ) - await client.get_backup_plan_association(request) + await client.update_data_source(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13054,37 +13824,53 @@ async def test_get_backup_plan_association_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "data_source.name=name_value", ) in kw["metadata"] -def test_get_backup_plan_association_flattened(): +def test_update_data_source_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" + type(client.transport.update_data_source), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplanassociation.BackupPlanAssociation() + 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.get_backup_plan_association( - name="name_value", + client.update_data_source( + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + 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].data_source + mock_val = backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + 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_get_backup_plan_association_flattened_error(): +def test_update_data_source_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -13092,45 +13878,68 @@ def test_get_backup_plan_association_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_backup_plan_association( - backupplanassociation.GetBackupPlanAssociationRequest(), - name="name_value", + client.update_data_source( + backupvault.UpdateDataSourceRequest(), + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_get_backup_plan_association_flattened_async(): +async def test_update_data_source_flattened_async(): client = BackupDRAsyncClient( 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_plan_association), "__call__" + type(client.transport.update_data_source), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = backupplanassociation.BackupPlanAssociation() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.BackupPlanAssociation() + 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.get_backup_plan_association( - name="name_value", + response = await client.update_data_source( + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + 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].data_source + mock_val = backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + 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_get_backup_plan_association_flattened_error_async(): +async def test_update_data_source_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -13138,20 +13947,27 @@ async def test_get_backup_plan_association_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.get_backup_plan_association( - backupplanassociation.GetBackupPlanAssociationRequest(), - name="name_value", + await client.update_data_source( + backupvault.UpdateDataSourceRequest(), + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - backupplanassociation.ListBackupPlanAssociationsRequest(), + backupvault.ListBackupsRequest(), {}, ], ) -def test_list_backup_plan_associations(request_type, transport: str = "grpc"): +def test_list_backups(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13162,29 +13978,27 @@ def test_list_backup_plan_associations(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.list_backup_plan_associations), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse( + call.return_value = backupvault.ListBackupsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) - response = client.list_backup_plan_associations(request) + response = client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplanassociation.ListBackupPlanAssociationsRequest() + request = backupvault.ListBackupsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupPlanAssociationsPager) + assert isinstance(response, pagers.ListBackupsPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_backup_plan_associations_non_empty_request_with_auto_populated_field(): +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 = BackupDRClient( @@ -13195,31 +14009,31 @@ def test_list_backup_plan_associations_non_empty_request_with_auto_populated_fie # 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 = backupplanassociation.ListBackupPlanAssociationsRequest( + request = backupvault.ListBackupsRequest( 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_backup_plan_associations), "__call__" - ) as call: + 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_backup_plan_associations(request=request) + client.list_backups(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.ListBackupPlanAssociationsRequest( + request_msg = backupvault.ListBackupsRequest( parent="parent_value", page_token="page_token_value", filter="filter_value", + order_by="order_by_value", ) assert args[0] == request_msg -def test_list_backup_plan_associations_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: @@ -13233,26 +14047,21 @@ def test_list_backup_plan_associations_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_backup_plan_associations - 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.list_backup_plan_associations - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_backups] = mock_rpc request = {} - client.list_backup_plan_associations(request) + client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backup_plan_associations(request) + client.list_backups(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13260,7 +14069,7 @@ def test_list_backup_plan_associations_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_backup_plan_associations_async_use_cached_wrapped_rpc( +async def test_list_backups_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -13277,7 +14086,7 @@ async def test_list_backup_plan_associations_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_backup_plan_associations + client._client._transport.list_backups in client._client._transport._wrapped_methods ) @@ -13285,16 +14094,16 @@ async def test_list_backup_plan_associations_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_backup_plan_associations + client._client._transport.list_backups ] = mock_rpc request = {} - await client.list_backup_plan_associations(request) + await client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_backup_plan_associations(request) + await client.list_backups(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13305,13 +14114,11 @@ async def test_list_backup_plan_associations_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplanassociation.ListBackupPlanAssociationsRequest(), + backupvault.ListBackupsRequest(), {}, ], ) -async def test_list_backup_plan_associations_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_list_backups_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13322,47 +14129,43 @@ async def test_list_backup_plan_associations_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_associations), "__call__" - ) as call: + 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( - backupplanassociation.ListBackupPlanAssociationsResponse( + backupvault.ListBackupsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) ) - response = await client.list_backup_plan_associations(request) + response = await client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplanassociation.ListBackupPlanAssociationsRequest() + request = backupvault.ListBackupsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupPlanAssociationsAsyncPager) + assert isinstance(response, pagers.ListBackupsAsyncPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_backup_plan_associations_field_headers(): +def test_list_backups_field_headers(): client = BackupDRClient( 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 = backupplanassociation.ListBackupPlanAssociationsRequest() + request = backupvault.ListBackupsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_associations), "__call__" - ) as call: - call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() - client.list_backup_plan_associations(request) + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value = backupvault.ListBackupsResponse() + client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13378,25 +14181,23 @@ def test_list_backup_plan_associations_field_headers(): @pytest.mark.asyncio -async def test_list_backup_plan_associations_field_headers_async(): +async def test_list_backups_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplanassociation.ListBackupPlanAssociationsRequest() + request = backupvault.ListBackupsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_associations), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.ListBackupPlanAssociationsResponse() + backupvault.ListBackupsResponse() ) - await client.list_backup_plan_associations(request) + await client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13411,20 +14212,18 @@ async def test_list_backup_plan_associations_field_headers_async(): ) in kw["metadata"] -def test_list_backup_plan_associations_flattened(): +def test_list_backups_flattened(): client = BackupDRClient( 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_plan_associations), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + call.return_value = backupvault.ListBackupsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_backup_plan_associations( + client.list_backups( parent="parent_value", ) @@ -13437,7 +14236,7 @@ def test_list_backup_plan_associations_flattened(): assert arg == mock_val -def test_list_backup_plan_associations_flattened_error(): +def test_list_backups_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -13445,31 +14244,29 @@ def test_list_backup_plan_associations_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backup_plan_associations( - backupplanassociation.ListBackupPlanAssociationsRequest(), + client.list_backups( + backupvault.ListBackupsRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_backup_plan_associations_flattened_async(): +async def test_list_backups_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_associations), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + call.return_value = backupvault.ListBackupsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.ListBackupPlanAssociationsResponse() + backupvault.ListBackupsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_backup_plan_associations( + response = await client.list_backups( parent="parent_value", ) @@ -13483,7 +14280,7 @@ async def test_list_backup_plan_associations_flattened_async(): @pytest.mark.asyncio -async def test_list_backup_plan_associations_flattened_error_async(): +async def test_list_backups_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -13491,46 +14288,44 @@ async def test_list_backup_plan_associations_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.list_backup_plan_associations( - backupplanassociation.ListBackupPlanAssociationsRequest(), + await client.list_backups( + backupvault.ListBackupsRequest(), parent="parent_value", ) -def test_list_backup_plan_associations_pager(transport_name: str = "grpc"): +def test_list_backups_pager(transport_name: str = "grpc"): client = BackupDRClient( 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_backup_plan_associations), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), ], next_page_token="abc", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[], + backupvault.ListBackupsResponse( + backups=[], next_page_token="def", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), ], next_page_token="ghi", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), ], ), RuntimeError, @@ -13542,9 +14337,7 @@ def test_list_backup_plan_associations_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_backup_plan_associations( - request={}, retry=retry, timeout=timeout - ) + pager = client.list_backups(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -13555,95 +14348,89 @@ def test_list_backup_plan_associations_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results - ) + assert all(isinstance(i, backupvault.Backup) for i in results) -def test_list_backup_plan_associations_pages(transport_name: str = "grpc"): +def test_list_backups_pages(transport_name: str = "grpc"): client = BackupDRClient( 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_backup_plan_associations), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), ], next_page_token="abc", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[], + backupvault.ListBackupsResponse( + backups=[], next_page_token="def", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), ], next_page_token="ghi", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), ], ), RuntimeError, ) - pages = list(client.list_backup_plan_associations(request={}).pages) + pages = list(client.list_backups(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_backup_plan_associations_async_pager(): +async def test_list_backups_async_pager(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plan_associations), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), ], next_page_token="abc", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[], + backupvault.ListBackupsResponse( + backups=[], next_page_token="def", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), ], next_page_token="ghi", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), ], ), RuntimeError, ) - async_pager = await client.list_backup_plan_associations( + async_pager = await client.list_backups( request={}, ) assert async_pager.next_page_token == "abc" @@ -13654,56 +14441,49 @@ async def test_list_backup_plan_associations_async_pager(): responses.append(response) assert len(responses) == 6 - assert all( - isinstance(i, backupplanassociation.BackupPlanAssociation) - for i in responses - ) + assert all(isinstance(i, backupvault.Backup) for i in responses) @pytest.mark.asyncio -async def test_list_backup_plan_associations_async_pages(): +async def test_list_backups_async_pages(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_backup_plan_associations), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), ], next_page_token="abc", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[], + backupvault.ListBackupsResponse( + backups=[], next_page_token="def", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), ], next_page_token="ghi", ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), ], ), RuntimeError, ) pages = [] - async for page_ in ( - await client.list_backup_plan_associations(request={}) - ).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 @@ -13712,13 +14492,11 @@ async def test_list_backup_plan_associations_async_pages(): @pytest.mark.parametrize( "request_type", [ - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + backupvault.FetchBackupsForResourceTypeRequest(), {}, ], ) -def test_fetch_backup_plan_associations_for_resource_type( - request_type, transport: str = "grpc" -): +def test_fetch_backups_for_resource_type(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13730,31 +14508,26 @@ def test_fetch_backup_plan_associations_for_resource_type( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", + type(client.transport.fetch_backups_for_resource_type), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - next_page_token="next_page_token_value", - ) + call.return_value = backupvault.FetchBackupsForResourceTypeResponse( + next_page_token="next_page_token_value", ) - response = client.fetch_backup_plan_associations_for_resource_type(request) + response = client.fetch_backups_for_resource_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() - ) + request = backupvault.FetchBackupsForResourceTypeRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchBackupPlanAssociationsForResourceTypePager) + assert isinstance(response, pagers.FetchBackupsForResourceTypePager) assert response.next_page_token == "next_page_token_value" -def test_fetch_backup_plan_associations_for_resource_type_non_empty_request_with_auto_populated_field(): +def test_fetch_backups_for_resource_type_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 = BackupDRClient( @@ -13765,7 +14538,7 @@ def test_fetch_backup_plan_associations_for_resource_type_non_empty_request_with # 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 = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( + request = backupvault.FetchBackupsForResourceTypeRequest( parent="parent_value", resource_type="resource_type_value", page_token="page_token_value", @@ -13775,28 +14548,25 @@ def test_fetch_backup_plan_associations_for_resource_type_non_empty_request_with # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", + type(client.transport.fetch_backups_for_resource_type), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.fetch_backup_plan_associations_for_resource_type(request=request) + client.fetch_backups_for_resource_type(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( - parent="parent_value", - resource_type="resource_type_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", - ) + request_msg = backupvault.FetchBackupsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) assert args[0] == request_msg -def test_fetch_backup_plan_associations_for_resource_type_use_cached_wrapped_rpc(): +def test_fetch_backups_for_resource_type_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: @@ -13811,7 +14581,7 @@ def test_fetch_backup_plan_associations_for_resource_type_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._transport.fetch_backup_plan_associations_for_resource_type + client._transport.fetch_backups_for_resource_type in client._transport._wrapped_methods ) @@ -13821,15 +14591,15 @@ def test_fetch_backup_plan_associations_for_resource_type_use_cached_wrapped_rpc "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_backup_plan_associations_for_resource_type + client._transport.fetch_backups_for_resource_type ] = mock_rpc request = {} - client.fetch_backup_plan_associations_for_resource_type(request) + client.fetch_backups_for_resource_type(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_backup_plan_associations_for_resource_type(request) + client.fetch_backups_for_resource_type(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13837,7 +14607,7 @@ def test_fetch_backup_plan_associations_for_resource_type_use_cached_wrapped_rpc @pytest.mark.asyncio -async def test_fetch_backup_plan_associations_for_resource_type_async_use_cached_wrapped_rpc( +async def test_fetch_backups_for_resource_type_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -13854,7 +14624,7 @@ async def test_fetch_backup_plan_associations_for_resource_type_async_use_cached # Ensure method has been cached assert ( - client._client._transport.fetch_backup_plan_associations_for_resource_type + client._client._transport.fetch_backups_for_resource_type in client._client._transport._wrapped_methods ) @@ -13862,16 +14632,16 @@ async def test_fetch_backup_plan_associations_for_resource_type_async_use_cached mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.fetch_backup_plan_associations_for_resource_type + client._client._transport.fetch_backups_for_resource_type ] = mock_rpc request = {} - await client.fetch_backup_plan_associations_for_resource_type(request) + await client.fetch_backups_for_resource_type(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_backup_plan_associations_for_resource_type(request) + await client.fetch_backups_for_resource_type(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13882,11 +14652,11 @@ async def test_fetch_backup_plan_associations_for_resource_type_async_use_cached @pytest.mark.parametrize( "request_type", [ - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + backupvault.FetchBackupsForResourceTypeRequest(), {}, ], ) -async def test_fetch_backup_plan_associations_for_resource_type_async( +async def test_fetch_backups_for_resource_type_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -13900,54 +14670,44 @@ async def test_fetch_backup_plan_associations_for_resource_type_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", + type(client.transport.fetch_backups_for_resource_type), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backupvault.FetchBackupsForResourceTypeResponse( next_page_token="next_page_token_value", ) ) - response = await client.fetch_backup_plan_associations_for_resource_type( - request - ) + response = await client.fetch_backups_for_resource_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() - ) + request = backupvault.FetchBackupsForResourceTypeRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance( - response, pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager - ) + assert isinstance(response, pagers.FetchBackupsForResourceTypeAsyncPager) assert response.next_page_token == "next_page_token_value" -def test_fetch_backup_plan_associations_for_resource_type_field_headers(): +def test_fetch_backups_for_resource_type_field_headers(): client = BackupDRClient( 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 = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + request = backupvault.FetchBackupsForResourceTypeRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", + type(client.transport.fetch_backups_for_resource_type), "__call__" ) as call: - call.return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - ) - client.fetch_backup_plan_associations_for_resource_type(request) + call.return_value = backupvault.FetchBackupsForResourceTypeResponse() + client.fetch_backups_for_resource_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13963,26 +14723,25 @@ def test_fetch_backup_plan_associations_for_resource_type_field_headers(): @pytest.mark.asyncio -async def test_fetch_backup_plan_associations_for_resource_type_field_headers_async(): +async def test_fetch_backups_for_resource_type_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + request = backupvault.FetchBackupsForResourceTypeRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", + type(client.transport.fetch_backups_for_resource_type), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + backupvault.FetchBackupsForResourceTypeResponse() ) - await client.fetch_backup_plan_associations_for_resource_type(request) + await client.fetch_backups_for_resource_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13997,23 +14756,20 @@ async def test_fetch_backup_plan_associations_for_resource_type_field_headers_as ) in kw["metadata"] -def test_fetch_backup_plan_associations_for_resource_type_flattened(): +def test_fetch_backups_for_resource_type_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", + type(client.transport.fetch_backups_for_resource_type), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - ) + call.return_value = backupvault.FetchBackupsForResourceTypeResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.fetch_backup_plan_associations_for_resource_type( + client.fetch_backups_for_resource_type( parent="parent_value", resource_type="resource_type_value", ) @@ -14030,7 +14786,7 @@ def test_fetch_backup_plan_associations_for_resource_type_flattened(): assert arg == mock_val -def test_fetch_backup_plan_associations_for_resource_type_flattened_error(): +def test_fetch_backups_for_resource_type_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -14038,35 +14794,32 @@ def test_fetch_backup_plan_associations_for_resource_type_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_backup_plan_associations_for_resource_type( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + client.fetch_backups_for_resource_type( + backupvault.FetchBackupsForResourceTypeRequest(), parent="parent_value", resource_type="resource_type_value", ) @pytest.mark.asyncio -async def test_fetch_backup_plan_associations_for_resource_type_flattened_async(): +async def test_fetch_backups_for_resource_type_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", + type(client.transport.fetch_backups_for_resource_type), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - ) + call.return_value = backupvault.FetchBackupsForResourceTypeResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + backupvault.FetchBackupsForResourceTypeResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.fetch_backup_plan_associations_for_resource_type( + response = await client.fetch_backups_for_resource_type( parent="parent_value", resource_type="resource_type_value", ) @@ -14084,7 +14837,7 @@ async def test_fetch_backup_plan_associations_for_resource_type_flattened_async( @pytest.mark.asyncio -async def test_fetch_backup_plan_associations_for_resource_type_flattened_error_async(): +async def test_fetch_backups_for_resource_type_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -14092,16 +14845,14 @@ async def test_fetch_backup_plan_associations_for_resource_type_flattened_error_ # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.fetch_backup_plan_associations_for_resource_type( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + await client.fetch_backups_for_resource_type( + backupvault.FetchBackupsForResourceTypeRequest(), parent="parent_value", resource_type="resource_type_value", ) -def test_fetch_backup_plan_associations_for_resource_type_pager( - transport_name: str = "grpc", -): +def test_fetch_backups_for_resource_type_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -14109,33 +14860,32 @@ def test_fetch_backup_plan_associations_for_resource_type_pager( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", + type(client.transport.fetch_backups_for_resource_type), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), ], next_page_token="abc", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[], + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], next_page_token="def", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), ], next_page_token="ghi", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), ], ), RuntimeError, @@ -14147,7 +14897,7 @@ def test_fetch_backup_plan_associations_for_resource_type_pager( expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.fetch_backup_plan_associations_for_resource_type( + pager = client.fetch_backups_for_resource_type( request={}, retry=retry, timeout=timeout ) @@ -14160,14 +14910,10 @@ def test_fetch_backup_plan_associations_for_resource_type_pager( results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results - ) + assert all(isinstance(i, backupvault.Backup) for i in results) -def test_fetch_backup_plan_associations_for_resource_type_pages( - transport_name: str = "grpc", -): +def test_fetch_backups_for_resource_type_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -14175,85 +14921,82 @@ def test_fetch_backup_plan_associations_for_resource_type_pages( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", + type(client.transport.fetch_backups_for_resource_type), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), ], next_page_token="abc", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[], + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], next_page_token="def", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), ], next_page_token="ghi", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), ], ), RuntimeError, ) - pages = list( - client.fetch_backup_plan_associations_for_resource_type(request={}).pages - ) + pages = list(client.fetch_backups_for_resource_type(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_fetch_backup_plan_associations_for_resource_type_async_pager(): +async def test_fetch_backups_for_resource_type_async_pager(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), + type(client.transport.fetch_backups_for_resource_type), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), ], next_page_token="abc", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[], + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], next_page_token="def", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), ], next_page_token="ghi", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), ], ), RuntimeError, ) - async_pager = await client.fetch_backup_plan_associations_for_resource_type( + async_pager = await client.fetch_backups_for_resource_type( request={}, ) assert async_pager.next_page_token == "abc" @@ -14264,55 +15007,52 @@ async def test_fetch_backup_plan_associations_for_resource_type_async_pager(): responses.append(response) assert len(responses) == 6 - assert all( - isinstance(i, backupplanassociation.BackupPlanAssociation) - for i in responses - ) + assert all(isinstance(i, backupvault.Backup) for i in responses) @pytest.mark.asyncio -async def test_fetch_backup_plan_associations_for_resource_type_async_pages(): +async def test_fetch_backups_for_resource_type_async_pages(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), + type(client.transport.fetch_backups_for_resource_type), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), ], next_page_token="abc", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[], + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], next_page_token="def", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), ], next_page_token="ghi", ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), ], ), RuntimeError, ) pages = [] async for page_ in ( - await client.fetch_backup_plan_associations_for_resource_type(request={}) + await client.fetch_backups_for_resource_type(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -14322,11 +15062,11 @@ async def test_fetch_backup_plan_associations_for_resource_type_async_pages(): @pytest.mark.parametrize( "request_type", [ - backupplanassociation.DeleteBackupPlanAssociationRequest(), + backupvault.GetBackupRequest(), {}, ], ) -def test_delete_backup_plan_association(request_type, transport: str = "grpc"): +def test_get_backup(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14337,24 +15077,46 @@ def test_delete_backup_plan_association(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.delete_backup_plan_association), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_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_plan_association(request) + call.return_value = backupvault.Backup( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + etag="etag_value", + state=backupvault.Backup.State.CREATING, + backup_type=backupvault.Backup.BackupType.SCHEDULED, + resource_size_bytes=2056, + satisfies_pzs=True, + satisfies_pzi=True, + kms_key_versions=["kms_key_versions_value"], + ) + response = client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplanassociation.DeleteBackupPlanAssociationRequest() + request = backupvault.GetBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, backupvault.Backup) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.etag == "etag_value" + assert response.state == backupvault.Backup.State.CREATING + assert response.backup_type == backupvault.Backup.BackupType.SCHEDULED + assert response.resource_size_bytes == 2056 + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.kms_key_versions == ["kms_key_versions_value"] -def test_delete_backup_plan_association_non_empty_request_with_auto_populated_field(): +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 = BackupDRClient( @@ -14365,29 +15127,25 @@ def test_delete_backup_plan_association_non_empty_request_with_auto_populated_fi # 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 = backupplanassociation.DeleteBackupPlanAssociationRequest( + request = backupvault.GetBackupRequest( name="name_value", - auto_protection_policy_binding="auto_protection_policy_binding_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan_association), "__call__" - ) as call: + 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.delete_backup_plan_association(request=request) + client.get_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest( + request_msg = backupvault.GetBackupRequest( name="name_value", - auto_protection_policy_binding="auto_protection_policy_binding_value", ) assert args[0] == request_msg -def test_delete_backup_plan_association_use_cached_wrapped_rpc(): +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: @@ -14401,31 +15159,21 @@ def test_delete_backup_plan_association_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_backup_plan_association - in client._transport._wrapped_methods - ) + 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.delete_backup_plan_association - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_backup] = mock_rpc request = {} - client.delete_backup_plan_association(request) + client.get_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_plan_association(request) + client.get_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14433,9 +15181,7 @@ def test_delete_backup_plan_association_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_backup_plan_association_async_use_cached_wrapped_rpc( - transport: str = "grpc_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: @@ -14450,7 +15196,7 @@ async def test_delete_backup_plan_association_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_backup_plan_association + client._client._transport.get_backup in client._client._transport._wrapped_methods ) @@ -14458,21 +15204,16 @@ async def test_delete_backup_plan_association_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_backup_plan_association + client._client._transport.get_backup ] = mock_rpc request = {} - await client.delete_backup_plan_association(request) + await client.get_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_plan_association(request) + await client.get_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14483,13 +15224,11 @@ async def test_delete_backup_plan_association_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplanassociation.DeleteBackupPlanAssociationRequest(), + backupvault.GetBackupRequest(), {}, ], ) -async def test_delete_backup_plan_association_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_get_backup_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -14500,42 +15239,62 @@ async def test_delete_backup_plan_association_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan_association), "__call__" - ) as call: + 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( - operations_pb2.Operation(name="operations/spam") + backupvault.Backup( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + etag="etag_value", + state=backupvault.Backup.State.CREATING, + backup_type=backupvault.Backup.BackupType.SCHEDULED, + resource_size_bytes=2056, + satisfies_pzs=True, + satisfies_pzi=True, + kms_key_versions=["kms_key_versions_value"], + ) ) - response = await client.delete_backup_plan_association(request) + 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 = backupplanassociation.DeleteBackupPlanAssociationRequest() + request = backupvault.GetBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, backupvault.Backup) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.backup_retention_inheritance + == backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION + ) + assert response.etag == "etag_value" + assert response.state == backupvault.Backup.State.CREATING + assert response.backup_type == backupvault.Backup.BackupType.SCHEDULED + assert response.resource_size_bytes == 2056 + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.kms_key_versions == ["kms_key_versions_value"] -def test_delete_backup_plan_association_field_headers(): +def test_get_backup_field_headers(): client = BackupDRClient( 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 = backupplanassociation.DeleteBackupPlanAssociationRequest() + request = backupvault.GetBackupRequest() 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_plan_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup_plan_association(request) + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = backupvault.Backup() + client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -14551,25 +15310,21 @@ def test_delete_backup_plan_association_field_headers(): @pytest.mark.asyncio -async def test_delete_backup_plan_association_field_headers_async(): +async def test_get_backup_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplanassociation.DeleteBackupPlanAssociationRequest() + request = backupvault.GetBackupRequest() 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_plan_association), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.delete_backup_plan_association(request) + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(backupvault.Backup()) + await client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -14584,20 +15339,18 @@ async def test_delete_backup_plan_association_field_headers_async(): ) in kw["metadata"] -def test_delete_backup_plan_association_flattened(): +def test_get_backup_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan_association), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupvault.Backup() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_backup_plan_association( + client.get_backup( name="name_value", ) @@ -14610,7 +15363,7 @@ def test_delete_backup_plan_association_flattened(): assert arg == mock_val -def test_delete_backup_plan_association_flattened_error(): +def test_get_backup_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -14618,31 +15371,27 @@ def test_delete_backup_plan_association_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_backup_plan_association( - backupplanassociation.DeleteBackupPlanAssociationRequest(), + client.get_backup( + backupvault.GetBackupRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_backup_plan_association_flattened_async(): +async def test_get_backup_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan_association), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupvault.Backup() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(backupvault.Backup()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_backup_plan_association( + response = await client.get_backup( name="name_value", ) @@ -14656,7 +15405,7 @@ async def test_delete_backup_plan_association_flattened_async(): @pytest.mark.asyncio -async def test_delete_backup_plan_association_flattened_error_async(): +async def test_get_backup_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -14664,8 +15413,8 @@ async def test_delete_backup_plan_association_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.delete_backup_plan_association( - backupplanassociation.DeleteBackupPlanAssociationRequest(), + await client.get_backup( + backupvault.GetBackupRequest(), name="name_value", ) @@ -14673,11 +15422,11 @@ async def test_delete_backup_plan_association_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - backupplanassociation.TriggerBackupRequest(), + backupvault.UpdateBackupRequest(), {}, ], ) -def test_trigger_backup(request_type, transport: str = "grpc"): +def test_update_backup(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14688,22 +15437,22 @@ def test_trigger_backup(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.trigger_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.trigger_backup(request) + response = client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = backupplanassociation.TriggerBackupRequest() + request = backupvault.UpdateBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_trigger_backup_non_empty_request_with_auto_populated_field(): +def test_update_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 = BackupDRClient( @@ -14714,27 +15463,21 @@ def test_trigger_backup_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 = backupplanassociation.TriggerBackupRequest( - name="name_value", - rule_id="rule_id_value", - ) + request = backupvault.UpdateBackupRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.trigger_backup(request=request) + client.update_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.TriggerBackupRequest( - name="name_value", - rule_id="rule_id_value", - ) + request_msg = backupvault.UpdateBackupRequest() assert args[0] == request_msg -def test_trigger_backup_use_cached_wrapped_rpc(): +def test_update_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: @@ -14748,16 +15491,16 @@ def test_trigger_backup_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.trigger_backup in client._transport._wrapped_methods + assert client._transport.update_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.trigger_backup] = mock_rpc + client._transport._wrapped_methods[client._transport.update_backup] = mock_rpc request = {} - client.trigger_backup(request) + client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -14767,7 +15510,7 @@ def test_trigger_backup_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.trigger_backup(request) + client.update_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14775,7 +15518,7 @@ def test_trigger_backup_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_trigger_backup_async_use_cached_wrapped_rpc( +async def test_update_backup_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -14792,7 +15535,7 @@ async def test_trigger_backup_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.trigger_backup + client._client._transport.update_backup in client._client._transport._wrapped_methods ) @@ -14800,11 +15543,11 @@ async def test_trigger_backup_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.trigger_backup + client._client._transport.update_backup ] = mock_rpc request = {} - await client.trigger_backup(request) + await client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -14814,7 +15557,7 @@ async def test_trigger_backup_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.trigger_backup(request) + await client.update_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -14825,11 +15568,11 @@ async def test_trigger_backup_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupplanassociation.TriggerBackupRequest(), + backupvault.UpdateBackupRequest(), {}, ], ) -async def test_trigger_backup_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_backup_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -14840,38 +15583,38 @@ async def test_trigger_backup_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.trigger_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_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.trigger_backup(request) + response = await client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupplanassociation.TriggerBackupRequest() + request = backupvault.UpdateBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_trigger_backup_field_headers(): +def test_update_backup_field_headers(): client = BackupDRClient( 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 = backupplanassociation.TriggerBackupRequest() + request = backupvault.UpdateBackupRequest() - request.name = "name_value" + request.backup.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.trigger_backup(request) + client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -14882,28 +15625,28 @@ def test_trigger_backup_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "backup.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_trigger_backup_field_headers_async(): +async def test_update_backup_field_headers_async(): client = BackupDRAsyncClient( 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 = backupplanassociation.TriggerBackupRequest() + request = backupvault.UpdateBackupRequest() - request.name = "name_value" + request.backup.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.trigger_backup(request) + await client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -14914,39 +15657,47 @@ async def test_trigger_backup_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "backup.name=name_value", ) in kw["metadata"] -def test_trigger_backup_flattened(): +def test_update_backup_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__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.trigger_backup( - name="name_value", - rule_id="rule_id_value", + client.update_backup( + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_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].backup + mock_val = backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ) assert arg == mock_val - arg = args[0].rule_id - mock_val = "rule_id_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_trigger_backup_flattened_error(): +def test_update_backup_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -14954,21 +15705,25 @@ def test_trigger_backup_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.trigger_backup( - backupplanassociation.TriggerBackupRequest(), - name="name_value", - rule_id="rule_id_value", + client.update_backup( + backupvault.UpdateBackupRequest(), + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_trigger_backup_flattened_async(): +async def test_update_backup_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -14977,25 +15732,33 @@ async def test_trigger_backup_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.trigger_backup( - name="name_value", - rule_id="rule_id_value", + response = await client.update_backup( + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_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].backup + mock_val = backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ) assert arg == mock_val - arg = args[0].rule_id - mock_val = "rule_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_trigger_backup_flattened_error_async(): +async def test_update_backup_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -15003,21 +15766,25 @@ async def test_trigger_backup_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.trigger_backup( - backupplanassociation.TriggerBackupRequest(), - name="name_value", - rule_id="rule_id_value", + await client.update_backup( + backupvault.UpdateBackupRequest(), + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - datasourcereference.GetDataSourceReferenceRequest(), + backupvault.DeleteBackupRequest(), {}, ], ) -def test_get_data_source_reference(request_type, transport: str = "grpc"): +def test_delete_backup(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15028,37 +15795,22 @@ def test_get_data_source_reference(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.get_data_source_reference), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = datasourcereference.DataSourceReference( - name="name_value", - data_source="data_source_value", - data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, - data_source_backup_count=2535, - total_stored_bytes=1946, - ) - response = client.get_data_source_reference(request) + 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 = datasourcereference.GetDataSourceReferenceRequest() + request = backupvault.DeleteBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, datasourcereference.DataSourceReference) - assert response.name == "name_value" - assert response.data_source == "data_source_value" - assert ( - response.data_source_backup_config_state == backupvault.BackupConfigState.ACTIVE - ) - assert response.data_source_backup_count == 2535 - assert response.total_stored_bytes == 1946 + assert isinstance(response, future.Future) -def test_get_data_source_reference_non_empty_request_with_auto_populated_field(): +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 = BackupDRClient( @@ -15069,27 +15821,25 @@ def test_get_data_source_reference_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 = datasourcereference.GetDataSourceReferenceRequest( + request = backupvault.DeleteBackupRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" - ) as call: + 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.get_data_source_reference(request=request) + client.delete_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = datasourcereference.GetDataSourceReferenceRequest( + request_msg = backupvault.DeleteBackupRequest( name="name_value", ) assert args[0] == request_msg -def test_get_data_source_reference_use_cached_wrapped_rpc(): +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: @@ -15103,26 +15853,26 @@ def test_get_data_source_reference_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_data_source_reference - in client._transport._wrapped_methods - ) + 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.get_data_source_reference - ] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_backup] = mock_rpc request = {} - client.get_data_source_reference(request) + client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_source_reference(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.delete_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15130,7 +15880,7 @@ def test_get_data_source_reference_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_data_source_reference_async_use_cached_wrapped_rpc( +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, @@ -15147,7 +15897,7 @@ async def test_get_data_source_reference_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_data_source_reference + client._client._transport.delete_backup in client._client._transport._wrapped_methods ) @@ -15155,16 +15905,21 @@ async def test_get_data_source_reference_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_data_source_reference + client._client._transport.delete_backup ] = mock_rpc request = {} - await client.get_data_source_reference(request) + await client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_data_source_reference(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() + + await client.delete_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15175,13 +15930,11 @@ async def test_get_data_source_reference_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - datasourcereference.GetDataSourceReferenceRequest(), + backupvault.DeleteBackupRequest(), {}, ], ) -async def test_get_data_source_reference_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_delete_backup_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -15192,55 +15945,38 @@ async def test_get_data_source_reference_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" - ) as call: + 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( - datasourcereference.DataSourceReference( - name="name_value", - data_source="data_source_value", - data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, - data_source_backup_count=2535, - total_stored_bytes=1946, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_data_source_reference(request) + response = await client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = datasourcereference.GetDataSourceReferenceRequest() + request = backupvault.DeleteBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, datasourcereference.DataSourceReference) - assert response.name == "name_value" - assert response.data_source == "data_source_value" - assert ( - response.data_source_backup_config_state == backupvault.BackupConfigState.ACTIVE - ) - assert response.data_source_backup_count == 2535 - assert response.total_stored_bytes == 1946 + assert isinstance(response, future.Future) -def test_get_data_source_reference_field_headers(): +def test_delete_backup_field_headers(): client = BackupDRClient( 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 = datasourcereference.GetDataSourceReferenceRequest() + request = backupvault.DeleteBackupRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" - ) as call: - call.return_value = datasourcereference.DataSourceReference() - client.get_data_source_reference(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 @@ -15256,25 +15992,23 @@ def test_get_data_source_reference_field_headers(): @pytest.mark.asyncio -async def test_get_data_source_reference_field_headers_async(): +async def test_delete_backup_field_headers_async(): client = BackupDRAsyncClient( 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 = datasourcereference.GetDataSourceReferenceRequest() + request = backupvault.DeleteBackupRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.DataSourceReference() + operations_pb2.Operation(name="operations/op") ) - await client.get_data_source_reference(request) + await client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -15289,20 +16023,18 @@ async def test_get_data_source_reference_field_headers_async(): ) in kw["metadata"] -def test_get_data_source_reference_flattened(): +def test_delete_backup_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = datasourcereference.DataSourceReference() + 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.get_data_source_reference( + client.delete_backup( name="name_value", ) @@ -15315,7 +16047,7 @@ def test_get_data_source_reference_flattened(): assert arg == mock_val -def test_get_data_source_reference_flattened_error(): +def test_delete_backup_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -15323,31 +16055,29 @@ def test_get_data_source_reference_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_data_source_reference( - datasourcereference.GetDataSourceReferenceRequest(), + client.delete_backup( + backupvault.DeleteBackupRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_data_source_reference_flattened_async(): +async def test_delete_backup_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = datasourcereference.DataSourceReference() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.DataSourceReference() + 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.get_data_source_reference( + response = await client.delete_backup( name="name_value", ) @@ -15361,7 +16091,7 @@ async def test_get_data_source_reference_flattened_async(): @pytest.mark.asyncio -async def test_get_data_source_reference_flattened_error_async(): +async def test_delete_backup_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -15369,8 +16099,8 @@ async def test_get_data_source_reference_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.get_data_source_reference( - datasourcereference.GetDataSourceReferenceRequest(), + await client.delete_backup( + backupvault.DeleteBackupRequest(), name="name_value", ) @@ -15378,11 +16108,11 @@ async def test_get_data_source_reference_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - datasourcereference.ListDataSourceReferencesRequest(), + backupvault.RestoreBackupRequest(), {}, ], ) -def test_list_data_source_references(request_type, transport: str = "grpc"): +def test_restore_backup(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15393,29 +16123,22 @@ def test_list_data_source_references(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.list_data_source_references), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = datasourcereference.ListDataSourceReferencesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_data_source_references(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.restore_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = datasourcereference.ListDataSourceReferencesRequest() + request = backupvault.RestoreBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourceReferencesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_data_source_references_non_empty_request_with_auto_populated_field(): +def test_restore_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 = BackupDRClient( @@ -15426,33 +16149,25 @@ def test_list_data_source_references_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 = datasourcereference.ListDataSourceReferencesRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = backupvault.RestoreBackupRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_data_source_references(request=request) + client.restore_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = datasourcereference.ListDataSourceReferencesRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request_msg = backupvault.RestoreBackupRequest( + name="name_value", ) assert args[0] == request_msg -def test_list_data_source_references_use_cached_wrapped_rpc(): +def test_restore_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: @@ -15466,26 +16181,26 @@ def test_list_data_source_references_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_data_source_references - in client._transport._wrapped_methods - ) + assert client._transport.restore_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.list_data_source_references - ] = mock_rpc + client._transport._wrapped_methods[client._transport.restore_backup] = mock_rpc request = {} - client.list_data_source_references(request) + client.restore_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_source_references(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.restore_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15493,7 +16208,7 @@ def test_list_data_source_references_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_data_source_references_async_use_cached_wrapped_rpc( +async def test_restore_backup_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -15510,7 +16225,7 @@ async def test_list_data_source_references_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_data_source_references + client._client._transport.restore_backup in client._client._transport._wrapped_methods ) @@ -15518,16 +16233,21 @@ async def test_list_data_source_references_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_data_source_references + client._client._transport.restore_backup ] = mock_rpc request = {} - await client.list_data_source_references(request) + await client.restore_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_data_source_references(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() + + await client.restore_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -15538,13 +16258,11 @@ async def test_list_data_source_references_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - datasourcereference.ListDataSourceReferencesRequest(), + backupvault.RestoreBackupRequest(), {}, ], ) -async def test_list_data_source_references_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_restore_backup_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -15555,47 +16273,38 @@ async def test_list_data_source_references_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.ListDataSourceReferencesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_data_source_references(request) + response = await client.restore_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = datasourcereference.ListDataSourceReferencesRequest() + request = backupvault.RestoreBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListDataSourceReferencesAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) -def test_list_data_source_references_field_headers(): +def test_restore_backup_field_headers(): client = BackupDRClient( 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 = datasourcereference.ListDataSourceReferencesRequest() + request = backupvault.RestoreBackupRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" - ) as call: - call.return_value = datasourcereference.ListDataSourceReferencesResponse() - client.list_data_source_references(request) + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.restore_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -15606,30 +16315,28 @@ def test_list_data_source_references_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_data_source_references_field_headers_async(): +async def test_restore_backup_field_headers_async(): client = BackupDRAsyncClient( 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 = datasourcereference.ListDataSourceReferencesRequest() + request = backupvault.RestoreBackupRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.ListDataSourceReferencesResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_data_source_references(request) + await client.restore_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -15640,37 +16347,35 @@ async def test_list_data_source_references_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_data_source_references_flattened(): +def test_restore_backup_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = datasourcereference.ListDataSourceReferencesResponse() + 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.list_data_source_references( - parent="parent_value", + client.restore_backup( + 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_data_source_references_flattened_error(): +def test_restore_backup_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -15678,45 +16383,43 @@ def test_list_data_source_references_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_data_source_references( - datasourcereference.ListDataSourceReferencesRequest(), - parent="parent_value", + client.restore_backup( + backupvault.RestoreBackupRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_data_source_references_flattened_async(): +async def test_restore_backup_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = datasourcereference.ListDataSourceReferencesResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.ListDataSourceReferencesResponse() + 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.list_data_source_references( - parent="parent_value", + response = await client.restore_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] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_data_source_references_flattened_error_async(): +async def test_restore_backup_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -15724,265 +16427,48 @@ async def test_list_data_source_references_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.list_data_source_references( - datasourcereference.ListDataSourceReferencesRequest(), - parent="parent_value", + await client.restore_backup( + backupvault.RestoreBackupRequest(), + name="name_value", ) -def test_list_data_source_references_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + backupplan.CreateBackupPlanRequest(), + {}, + ], +) +def test_create_backup_plan(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" + type(client.transport.create_backup_plan), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_data_source_references( - request={}, retry=retry, timeout=timeout - ) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_backup_plan(request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplan.CreateBackupPlanRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, datasourcereference.DataSourceReference) for i in results - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_list_data_source_references_pages(transport_name: str = "grpc"): - client = BackupDRClient( - 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_data_source_references), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - RuntimeError, - ) - pages = list(client.list_data_source_references(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_data_source_references_async_pager(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_data_source_references( - 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, datasourcereference.DataSourceReference) for i in responses - ) - - -@pytest.mark.asyncio -async def test_list_data_source_references_async_pages(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_data_source_references(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", - [ - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), - {}, - ], -) -def test_fetch_data_source_references_for_resource_type( - request_type, transport: str = "grpc" -): - client = BackupDRClient( - 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.fetch_data_source_references_for_resource_type), - "__call__", - ) as call: - # Designate an appropriate return value for the call. - call.return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - next_page_token="next_page_token_value", - ) - ) - response = client.fetch_data_source_references_for_resource_type(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchDataSourceReferencesForResourceTypePager) - assert response.next_page_token == "next_page_token_value" - - -def test_fetch_data_source_references_for_resource_type_non_empty_request_with_auto_populated_field(): +def test_create_backup_plan_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 = BackupDRClient( @@ -15993,38 +16479,29 @@ def test_fetch_data_source_references_for_resource_type_non_empty_request_with_a # 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 = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest( + request = backupplan.CreateBackupPlanRequest( parent="parent_value", - resource_type="resource_type_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + backup_plan_id="backup_plan_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", + type(client.transport.create_backup_plan), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.fetch_data_source_references_for_resource_type(request=request) + client.create_backup_plan(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest( - parent="parent_value", - resource_type="resource_type_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", - ) + request_msg = backupplan.CreateBackupPlanRequest( + parent="parent_value", + backup_plan_id="backup_plan_id_value", ) assert args[0] == request_msg -def test_fetch_data_source_references_for_resource_type_use_cached_wrapped_rpc(): +def test_create_backup_plan_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: @@ -16039,8 +16516,7 @@ def test_fetch_data_source_references_for_resource_type_use_cached_wrapped_rpc() # Ensure method has been cached assert ( - client._transport.fetch_data_source_references_for_resource_type - in client._transport._wrapped_methods + client._transport.create_backup_plan in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -16048,16 +16524,21 @@ def test_fetch_data_source_references_for_resource_type_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.fetch_data_source_references_for_resource_type - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_backup_plan] = ( + mock_rpc + ) request = {} - client.fetch_data_source_references_for_resource_type(request) + client.create_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_data_source_references_for_resource_type(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.create_backup_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16065,7 +16546,7 @@ def test_fetch_data_source_references_for_resource_type_use_cached_wrapped_rpc() @pytest.mark.asyncio -async def test_fetch_data_source_references_for_resource_type_async_use_cached_wrapped_rpc( +async def test_create_backup_plan_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -16082,7 +16563,7 @@ async def test_fetch_data_source_references_for_resource_type_async_use_cached_w # Ensure method has been cached assert ( - client._client._transport.fetch_data_source_references_for_resource_type + client._client._transport.create_backup_plan in client._client._transport._wrapped_methods ) @@ -16090,16 +16571,21 @@ async def test_fetch_data_source_references_for_resource_type_async_use_cached_w mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.fetch_data_source_references_for_resource_type + client._client._transport.create_backup_plan ] = mock_rpc request = {} - await client.fetch_data_source_references_for_resource_type(request) + await client.create_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_data_source_references_for_resource_type(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() + + await client.create_backup_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16110,13 +16596,11 @@ async def test_fetch_data_source_references_for_resource_type_async_use_cached_w @pytest.mark.parametrize( "request_type", [ - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + backupplan.CreateBackupPlanRequest(), {}, ], ) -async def test_fetch_data_source_references_for_resource_type_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_create_backup_plan_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -16128,50 +16612,41 @@ async def test_fetch_data_source_references_for_resource_type_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", + type(client.transport.create_backup_plan), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - next_page_token="next_page_token_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.fetch_data_source_references_for_resource_type(request) + response = await client.create_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + request = backupplan.CreateBackupPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance( - response, pagers.FetchDataSourceReferencesForResourceTypeAsyncPager - ) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_fetch_data_source_references_for_resource_type_field_headers(): +def test_create_backup_plan_field_headers(): client = BackupDRClient( 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 = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + request = backupplan.CreateBackupPlanRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", + type(client.transport.create_backup_plan), "__call__" ) as call: - call.return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() - ) - client.fetch_data_source_references_for_resource_type(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -16187,26 +16662,25 @@ def test_fetch_data_source_references_for_resource_type_field_headers(): @pytest.mark.asyncio -async def test_fetch_data_source_references_for_resource_type_field_headers_async(): +async def test_create_backup_plan_field_headers_async(): client = BackupDRAsyncClient( 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 = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + request = backupplan.CreateBackupPlanRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", + type(client.transport.create_backup_plan), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + operations_pb2.Operation(name="operations/op") ) - await client.fetch_data_source_references_for_resource_type(request) + await client.create_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -16221,25 +16695,27 @@ async def test_fetch_data_source_references_for_resource_type_field_headers_asyn ) in kw["metadata"] -def test_fetch_data_source_references_for_resource_type_flattened(): +def test_create_backup_plan_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", + type(client.transport.create_backup_plan), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() - ) + 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.fetch_data_source_references_for_resource_type( + client.create_backup_plan( parent="parent_value", - resource_type="resource_type_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", ) # Establish that the underlying call was made with the expected @@ -16249,12 +16725,19 @@ def test_fetch_data_source_references_for_resource_type_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].resource_type - mock_val = "resource_type_value" + arg = args[0].backup_plan + mock_val = backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ) + assert arg == mock_val + arg = args[0].backup_plan_id + mock_val = "backup_plan_id_value" assert arg == mock_val -def test_fetch_data_source_references_for_resource_type_flattened_error(): +def test_create_backup_plan_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -16262,37 +16745,44 @@ def test_fetch_data_source_references_for_resource_type_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_data_source_references_for_resource_type( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + client.create_backup_plan( + backupplan.CreateBackupPlanRequest(), parent="parent_value", - resource_type="resource_type_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", ) @pytest.mark.asyncio -async def test_fetch_data_source_references_for_resource_type_flattened_async(): +async def test_create_backup_plan_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", + type(client.transport.create_backup_plan), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() - ) + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + 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.fetch_data_source_references_for_resource_type( + response = await client.create_backup_plan( parent="parent_value", - resource_type="resource_type_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", ) # Establish that the underlying call was made with the expected @@ -16302,13 +16792,20 @@ async def test_fetch_data_source_references_for_resource_type_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].resource_type - mock_val = "resource_type_value" + arg = args[0].backup_plan + mock_val = backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ) + assert arg == mock_val + arg = args[0].backup_plan_id + mock_val = "backup_plan_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_fetch_data_source_references_for_resource_type_flattened_error_async(): +async def test_create_backup_plan_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -16316,303 +16813,81 @@ async def test_fetch_data_source_references_for_resource_type_flattened_error_as # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.fetch_data_source_references_for_resource_type( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + await client.create_backup_plan( + backupplan.CreateBackupPlanRequest(), parent="parent_value", - resource_type="resource_type_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", ) -def test_fetch_data_source_references_for_resource_type_pager( - transport_name: str = "grpc", -): +@pytest.mark.parametrize( + "request_type", + [ + backupplan.UpdateBackupPlanRequest(), + {}, + ], +) +def test_update_backup_plan(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", + type(client.transport.update_backup_plan), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.fetch_data_source_references_for_resource_type( - request={}, retry=retry, timeout=timeout - ) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_backup_plan(request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplan.UpdateBackupPlanRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, datasourcereference.DataSourceReference) for i in results - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_fetch_data_source_references_for_resource_type_pages( - transport_name: str = "grpc", -): +def test_update_backup_plan_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + 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 = backupplan.UpdateBackupPlanRequest() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", + type(client.transport.update_backup_plan), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - RuntimeError, - ) - pages = list( - client.fetch_data_source_references_for_resource_type(request={}).pages + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.update_backup_plan(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.UpdateBackupPlanRequest() + assert args[0] == request_msg -@pytest.mark.asyncio -async def test_fetch_data_source_references_for_resource_type_async_pager(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - RuntimeError, - ) - async_pager = await client.fetch_data_source_references_for_resource_type( - 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, datasourcereference.DataSourceReference) for i in responses - ) - - -@pytest.mark.asyncio -async def test_fetch_data_source_references_for_resource_type_async_pages(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.fetch_data_source_references_for_resource_type(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", - [ - backupdr.InitializeServiceRequest(), - {}, - ], -) -def test_initialize_service(request_type, transport: str = "grpc"): - client = BackupDRClient( - 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.initialize_service), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.initialize_service(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = backupdr.InitializeServiceRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_initialize_service_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 = BackupDRClient( - 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 = backupdr.InitializeServiceRequest( - name="name_value", - resource_type="resource_type_value", - backup_plan_location="backup_plan_location_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.initialize_service), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.initialize_service(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.InitializeServiceRequest( - name="name_value", - resource_type="resource_type_value", - backup_plan_location="backup_plan_location_value", - ) - assert args[0] == request_msg - - -def test_initialize_service_use_cached_wrapped_rpc(): +def test_update_backup_plan_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: @@ -16627,7 +16902,7 @@ def test_initialize_service_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.initialize_service in client._transport._wrapped_methods + client._transport.update_backup_plan in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -16635,11 +16910,11 @@ def test_initialize_service_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.initialize_service] = ( + client._transport._wrapped_methods[client._transport.update_backup_plan] = ( mock_rpc ) request = {} - client.initialize_service(request) + client.update_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -16649,7 +16924,7 @@ def test_initialize_service_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.initialize_service(request) + client.update_backup_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16657,7 +16932,7 @@ def test_initialize_service_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_initialize_service_async_use_cached_wrapped_rpc( +async def test_update_backup_plan_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -16674,7 +16949,7 @@ async def test_initialize_service_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.initialize_service + client._client._transport.update_backup_plan in client._client._transport._wrapped_methods ) @@ -16682,11 +16957,11 @@ async def test_initialize_service_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.initialize_service + client._client._transport.update_backup_plan ] = mock_rpc request = {} - await client.initialize_service(request) + await client.update_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -16696,7 +16971,7 @@ async def test_initialize_service_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.initialize_service(request) + await client.update_backup_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16707,11 +16982,11 @@ async def test_initialize_service_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - backupdr.InitializeServiceRequest(), + backupplan.UpdateBackupPlanRequest(), {}, ], ) -async def test_initialize_service_async(request_type, transport: str = "grpc_asyncio"): +async def test_update_backup_plan_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -16723,41 +16998,41 @@ async def test_initialize_service_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.initialize_service), "__call__" + type(client.transport.update_backup_plan), "__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.initialize_service(request) + response = await client.update_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = backupdr.InitializeServiceRequest() + request = backupplan.UpdateBackupPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_initialize_service_field_headers(): +def test_update_backup_plan_field_headers(): client = BackupDRClient( 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 = backupdr.InitializeServiceRequest() + request = backupplan.UpdateBackupPlanRequest() - request.name = "name_value" + request.backup_plan.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.initialize_service), "__call__" + type(client.transport.update_backup_plan), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.initialize_service(request) + client.update_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -16768,30 +17043,30 @@ def test_initialize_service_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "backup_plan.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_initialize_service_field_headers_async(): +async def test_update_backup_plan_field_headers_async(): client = BackupDRAsyncClient( 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 = backupdr.InitializeServiceRequest() + request = backupplan.UpdateBackupPlanRequest() - request.name = "name_value" + request.backup_plan.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.initialize_service), "__call__" + type(client.transport.update_backup_plan), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.initialize_service(request) + await client.update_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -16802,18 +17077,138 @@ async def test_initialize_service_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "backup_plan.name=name_value", ) in kw["metadata"] +def test_update_backup_plan_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__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.update_backup_plan( + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + 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].backup_plan + mock_val = backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ) + 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_backup_plan_flattened_error(): + client = BackupDRClient( + 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_backup_plan( + backupplan.UpdateBackupPlanRequest(), + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_backup_plan_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__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.update_backup_plan( + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + 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].backup_plan + mock_val = backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ) + 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_backup_plan_flattened_error_async(): + client = BackupDRAsyncClient( + 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_backup_plan( + backupplan.UpdateBackupPlanRequest(), + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + backupplan.GetBackupPlanRequest(), {}, ], ) -def test_create_auto_protection_policy(request_type, transport: str = "grpc"): +def test_get_backup_plan(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16824,24 +17219,47 @@ def test_create_auto_protection_policy(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.create_auto_protection_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_auto_protection_policy(request) + call.return_value = backupplan.BackupPlan( + name="name_value", + description="description_value", + max_custom_on_demand_retention_days=3723, + state=backupplan.BackupPlan.State.CREATING, + resource_type="resource_type_value", + etag="etag_value", + backup_vault="backup_vault_value", + backup_vault_service_account="backup_vault_service_account_value", + log_retention_days=1929, + supported_resource_types=["supported_resource_types_value"], + revision_id="revision_id_value", + revision_name="revision_name_value", + ) + response = client.get_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + request = backupplan.GetBackupPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, backupplan.BackupPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.max_custom_on_demand_retention_days == 3723 + assert response.state == backupplan.BackupPlan.State.CREATING + assert response.resource_type == "resource_type_value" + assert response.etag == "etag_value" + assert response.backup_vault == "backup_vault_value" + assert response.backup_vault_service_account == "backup_vault_service_account_value" + assert response.log_retention_days == 1929 + assert response.supported_resource_types == ["supported_resource_types_value"] + assert response.revision_id == "revision_id_value" + assert response.revision_name == "revision_name_value" -def test_create_auto_protection_policy_non_empty_request_with_auto_populated_field(): +def test_get_backup_plan_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 = BackupDRClient( @@ -16852,29 +17270,25 @@ def test_create_auto_protection_policy_non_empty_request_with_auto_populated_fie # 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest( - parent="parent_value", - auto_protection_policy_id="auto_protection_policy_id_value", + request = backupplan.GetBackupPlanRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_auto_protection_policy(request=request) + client.get_backup_plan(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest( - parent="parent_value", - auto_protection_policy_id="auto_protection_policy_id_value", + request_msg = backupplan.GetBackupPlanRequest( + name="name_value", ) assert args[0] == request_msg -def test_create_auto_protection_policy_use_cached_wrapped_rpc(): +def test_get_backup_plan_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: @@ -16888,31 +17302,21 @@ def test_create_auto_protection_policy_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_auto_protection_policy - in client._transport._wrapped_methods - ) + assert client._transport.get_backup_plan 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_auto_protection_policy - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_backup_plan] = mock_rpc request = {} - client.create_auto_protection_policy(request) + client.get_backup_plan(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.create_auto_protection_policy(request) + client.get_backup_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16920,7 +17324,7 @@ def test_create_auto_protection_policy_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_auto_protection_policy_async_use_cached_wrapped_rpc( +async def test_get_backup_plan_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -16937,7 +17341,7 @@ async def test_create_auto_protection_policy_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_auto_protection_policy + client._client._transport.get_backup_plan in client._client._transport._wrapped_methods ) @@ -16945,21 +17349,16 @@ async def test_create_auto_protection_policy_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_auto_protection_policy + client._client._transport.get_backup_plan ] = mock_rpc request = {} - await client.create_auto_protection_policy(request) + await client.get_backup_plan(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.create_auto_protection_policy(request) + await client.get_backup_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -16970,13 +17369,11 @@ async def test_create_auto_protection_policy_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + backupplan.GetBackupPlanRequest(), {}, ], ) -async def test_create_auto_protection_policy_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_get_backup_plan_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -16987,42 +17384,63 @@ async def test_create_auto_protection_policy_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupplan.BackupPlan( + name="name_value", + description="description_value", + max_custom_on_demand_retention_days=3723, + state=backupplan.BackupPlan.State.CREATING, + resource_type="resource_type_value", + etag="etag_value", + backup_vault="backup_vault_value", + backup_vault_service_account="backup_vault_service_account_value", + log_retention_days=1929, + supported_resource_types=["supported_resource_types_value"], + revision_id="revision_id_value", + revision_name="revision_name_value", + ) ) - response = await client.create_auto_protection_policy(request) + response = await client.get_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + request = backupplan.GetBackupPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, backupplan.BackupPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.max_custom_on_demand_retention_days == 3723 + assert response.state == backupplan.BackupPlan.State.CREATING + assert response.resource_type == "resource_type_value" + assert response.etag == "etag_value" + assert response.backup_vault == "backup_vault_value" + assert response.backup_vault_service_account == "backup_vault_service_account_value" + assert response.log_retention_days == 1929 + assert response.supported_resource_types == ["supported_resource_types_value"] + assert response.revision_id == "revision_id_value" + assert response.revision_name == "revision_name_value" -def test_create_auto_protection_policy_field_headers(): +def test_get_backup_plan_field_headers(): client = BackupDRClient( 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + request = backupplan.GetBackupPlanRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_auto_protection_policy(request) + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + call.return_value = backupplan.BackupPlan() + client.get_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -17033,30 +17451,28 @@ def test_create_auto_protection_policy_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_auto_protection_policy_field_headers_async(): +async def test_get_backup_plan_field_headers_async(): client = BackupDRAsyncClient( 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + request = backupplan.GetBackupPlanRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + backupplan.BackupPlan() ) - await client.create_auto_protection_policy(request) + await client.get_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -17067,47 +17483,35 @@ async def test_create_auto_protection_policy_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_auto_protection_policy_flattened(): +def test_get_backup_plan_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupplan.BackupPlan() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_auto_protection_policy( - parent="parent_value", - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - auto_protection_policy_id="auto_protection_policy_id_value", + client.get_backup_plan( + 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].auto_protection_policy - mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") - assert arg == mock_val - arg = args[0].auto_protection_policy_id - mock_val = "auto_protection_policy_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_create_auto_protection_policy_flattened_error(): +def test_get_backup_plan_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -17115,59 +17519,43 @@ def test_create_auto_protection_policy_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_auto_protection_policy( - autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), - parent="parent_value", - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - auto_protection_policy_id="auto_protection_policy_id_value", + client.get_backup_plan( + backupplan.GetBackupPlanRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_create_auto_protection_policy_flattened_async(): +async def test_get_backup_plan_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy), "__call__" - ) as call: + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupplan.BackupPlan() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupplan.BackupPlan() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_auto_protection_policy( - parent="parent_value", - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - auto_protection_policy_id="auto_protection_policy_id_value", + response = await client.get_backup_plan( + 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].auto_protection_policy - mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") - assert arg == mock_val - arg = args[0].auto_protection_policy_id - mock_val = "auto_protection_policy_id_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_auto_protection_policy_flattened_error_async(): +async def test_get_backup_plan_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -17175,24 +17563,20 @@ async def test_create_auto_protection_policy_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.create_auto_protection_policy( - autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), - parent="parent_value", - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - auto_protection_policy_id="auto_protection_policy_id_value", + await client.get_backup_plan( + backupplan.GetBackupPlanRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + backupplan.ListBackupPlansRequest(), {}, ], ) -def test_list_auto_protection_policies(request_type, transport: str = "grpc"): +def test_list_backup_plans(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17204,28 +17588,28 @@ def test_list_auto_protection_policies(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" + type(client.transport.list_backup_plans), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + call.return_value = backupplan.ListBackupPlansResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) - response = client.list_auto_protection_policies(request) + response = client.list_backup_plans(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + request = backupplan.ListBackupPlansRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAutoProtectionPoliciesPager) + assert isinstance(response, pagers.ListBackupPlansPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_auto_protection_policies_non_empty_request_with_auto_populated_field(): +def test_list_backup_plans_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 = BackupDRClient( @@ -17236,7 +17620,7 @@ def test_list_auto_protection_policies_non_empty_request_with_auto_populated_fie # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest( + request = backupplan.ListBackupPlansRequest( parent="parent_value", page_token="page_token_value", filter="filter_value", @@ -17245,15 +17629,15 @@ def test_list_auto_protection_policies_non_empty_request_with_auto_populated_fie # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" + type(client.transport.list_backup_plans), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_auto_protection_policies(request=request) + client.list_backup_plans(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest( + request_msg = backupplan.ListBackupPlansRequest( parent="parent_value", page_token="page_token_value", filter="filter_value", @@ -17262,7 +17646,7 @@ def test_list_auto_protection_policies_non_empty_request_with_auto_populated_fie assert args[0] == request_msg -def test_list_auto_protection_policies_use_cached_wrapped_rpc(): +def test_list_backup_plans_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: @@ -17276,26 +17660,23 @@ def test_list_auto_protection_policies_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_auto_protection_policies - in client._transport._wrapped_methods - ) + assert client._transport.list_backup_plans 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_auto_protection_policies - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_backup_plans] = ( + mock_rpc + ) request = {} - client.list_auto_protection_policies(request) + client.list_backup_plans(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_auto_protection_policies(request) + client.list_backup_plans(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17303,7 +17684,7 @@ def test_list_auto_protection_policies_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_auto_protection_policies_async_use_cached_wrapped_rpc( +async def test_list_backup_plans_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -17320,7 +17701,7 @@ async def test_list_auto_protection_policies_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_auto_protection_policies + client._client._transport.list_backup_plans in client._client._transport._wrapped_methods ) @@ -17328,16 +17709,16 @@ async def test_list_auto_protection_policies_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_auto_protection_policies + client._client._transport.list_backup_plans ] = mock_rpc request = {} - await client.list_auto_protection_policies(request) + await client.list_backup_plans(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_auto_protection_policies(request) + await client.list_backup_plans(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17348,13 +17729,11 @@ async def test_list_auto_protection_policies_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + backupplan.ListBackupPlansRequest(), {}, ], ) -async def test_list_auto_protection_policies_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_list_backup_plans_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -17366,46 +17745,46 @@ async def test_list_auto_protection_policies_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" + type(client.transport.list_backup_plans), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + backupplan.ListBackupPlansResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) ) - response = await client.list_auto_protection_policies(request) + response = await client.list_backup_plans(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + request = backupplan.ListBackupPlansRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAutoProtectionPoliciesAsyncPager) + assert isinstance(response, pagers.ListBackupPlansAsyncPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_auto_protection_policies_field_headers(): +def test_list_backup_plans_field_headers(): client = BackupDRClient( 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + request = backupplan.ListBackupPlansRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" + type(client.transport.list_backup_plans), "__call__" ) as call: - call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() - client.list_auto_protection_policies(request) + call.return_value = backupplan.ListBackupPlansResponse() + client.list_backup_plans(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -17421,25 +17800,25 @@ def test_list_auto_protection_policies_field_headers(): @pytest.mark.asyncio -async def test_list_auto_protection_policies_field_headers_async(): +async def test_list_backup_plans_field_headers_async(): client = BackupDRAsyncClient( 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + request = backupplan.ListBackupPlansRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" + type(client.transport.list_backup_plans), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + backupplan.ListBackupPlansResponse() ) - await client.list_auto_protection_policies(request) + await client.list_backup_plans(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -17454,20 +17833,20 @@ async def test_list_auto_protection_policies_field_headers_async(): ) in kw["metadata"] -def test_list_auto_protection_policies_flattened(): +def test_list_backup_plans_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" + type(client.transport.list_backup_plans), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + call.return_value = backupplan.ListBackupPlansResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_auto_protection_policies( + client.list_backup_plans( parent="parent_value", ) @@ -17480,7 +17859,7 @@ def test_list_auto_protection_policies_flattened(): assert arg == mock_val -def test_list_auto_protection_policies_flattened_error(): +def test_list_backup_plans_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -17488,31 +17867,31 @@ def test_list_auto_protection_policies_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_auto_protection_policies( - autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + client.list_backup_plans( + backupplan.ListBackupPlansRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_auto_protection_policies_flattened_async(): +async def test_list_backup_plans_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" + type(client.transport.list_backup_plans), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + call.return_value = backupplan.ListBackupPlansResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + backupplan.ListBackupPlansResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_auto_protection_policies( + response = await client.list_backup_plans( parent="parent_value", ) @@ -17526,7 +17905,7 @@ async def test_list_auto_protection_policies_flattened_async(): @pytest.mark.asyncio -async def test_list_auto_protection_policies_flattened_error_async(): +async def test_list_backup_plans_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -17534,13 +17913,13 @@ async def test_list_auto_protection_policies_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.list_auto_protection_policies( - autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + await client.list_backup_plans( + backupplan.ListBackupPlansRequest(), parent="parent_value", ) -def test_list_auto_protection_policies_pager(transport_name: str = "grpc"): +def test_list_backup_plans_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -17548,32 +17927,32 @@ def test_list_auto_protection_policies_pager(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" + type(client.transport.list_backup_plans), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), ], next_page_token="abc", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[], + backupplan.ListBackupPlansResponse( + backup_plans=[], next_page_token="def", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), ], next_page_token="ghi", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), ], ), RuntimeError, @@ -17585,9 +17964,7 @@ def test_list_auto_protection_policies_pager(transport_name: str = "grpc"): expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_auto_protection_policies( - request={}, retry=retry, timeout=timeout - ) + pager = client.list_backup_plans(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -17598,12 +17975,10 @@ def test_list_auto_protection_policies_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all( - isinstance(i, autoprotectionpolicy.AutoProtectionPolicy) for i in results - ) + assert all(isinstance(i, backupplan.BackupPlan) for i in results) -def test_list_auto_protection_policies_pages(transport_name: str = "grpc"): +def test_list_backup_plans_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -17611,82 +17986,82 @@ def test_list_auto_protection_policies_pages(transport_name: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" + type(client.transport.list_backup_plans), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), ], next_page_token="abc", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[], + backupplan.ListBackupPlansResponse( + backup_plans=[], next_page_token="def", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), ], next_page_token="ghi", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), ], ), RuntimeError, ) - pages = list(client.list_auto_protection_policies(request={}).pages) + pages = list(client.list_backup_plans(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_auto_protection_policies_async_pager(): +async def test_list_backup_plans_async_pager(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), + type(client.transport.list_backup_plans), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), ], next_page_token="abc", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[], + backupplan.ListBackupPlansResponse( + backup_plans=[], next_page_token="def", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), ], next_page_token="ghi", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), ], ), RuntimeError, ) - async_pager = await client.list_auto_protection_policies( + async_pager = await client.list_backup_plans( request={}, ) assert async_pager.next_page_token == "abc" @@ -17697,55 +18072,51 @@ async def test_list_auto_protection_policies_async_pager(): responses.append(response) assert len(responses) == 6 - assert all( - isinstance(i, autoprotectionpolicy.AutoProtectionPolicy) for i in responses - ) + assert all(isinstance(i, backupplan.BackupPlan) for i in responses) @pytest.mark.asyncio -async def test_list_auto_protection_policies_async_pages(): +async def test_list_backup_plans_async_pages(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policies), + type(client.transport.list_backup_plans), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), ], next_page_token="abc", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[], + backupplan.ListBackupPlansResponse( + backup_plans=[], next_page_token="def", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), ], next_page_token="ghi", ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), ], ), RuntimeError, ) pages = [] - async for page_ in ( - await client.list_auto_protection_policies(request={}) - ).pages: + async for page_ in (await client.list_backup_plans(request={})).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -17754,11 +18125,11 @@ async def test_list_auto_protection_policies_async_pages(): @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + backupplan.DeleteBackupPlanRequest(), {}, ], ) -def test_get_auto_protection_policy(request_type, transport: str = "grpc"): +def test_delete_backup_plan(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -17770,32 +18141,23 @@ def test_get_auto_protection_policy(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy), "__call__" + type(client.transport.delete_backup_plan), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = autoprotectionpolicy.AutoProtectionPolicy( - name="name_value", - description="description_value", - state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, - etag="etag_value", - ) - response = client.get_auto_protection_policy(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + request = backupplan.DeleteBackupPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, autoprotectionpolicy.AutoProtectionPolicy) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING - assert response.etag == "etag_value" + assert isinstance(response, future.Future) -def test_get_auto_protection_policy_non_empty_request_with_auto_populated_field(): +def test_delete_backup_plan_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 = BackupDRClient( @@ -17806,27 +18168,27 @@ def test_get_auto_protection_policy_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 = autoprotectionpolicy.GetAutoProtectionPolicyRequest( + request = backupplan.DeleteBackupPlanRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy), "__call__" + type(client.transport.delete_backup_plan), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_auto_protection_policy(request=request) + client.delete_backup_plan(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest( + request_msg = backupplan.DeleteBackupPlanRequest( name="name_value", ) assert args[0] == request_msg -def test_get_auto_protection_policy_use_cached_wrapped_rpc(): +def test_delete_backup_plan_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: @@ -17841,8 +18203,7 @@ def test_get_auto_protection_policy_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_auto_protection_policy - in client._transport._wrapped_methods + client._transport.delete_backup_plan in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -17850,16 +18211,21 @@ def test_get_auto_protection_policy_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.get_auto_protection_policy - ] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_backup_plan] = ( + mock_rpc + ) request = {} - client.get_auto_protection_policy(request) + client.delete_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_auto_protection_policy(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.delete_backup_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17867,7 +18233,7 @@ def test_get_auto_protection_policy_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_auto_protection_policy_async_use_cached_wrapped_rpc( +async def test_delete_backup_plan_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -17884,7 +18250,7 @@ async def test_get_auto_protection_policy_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_auto_protection_policy + client._client._transport.delete_backup_plan in client._client._transport._wrapped_methods ) @@ -17892,16 +18258,21 @@ async def test_get_auto_protection_policy_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_auto_protection_policy + client._client._transport.delete_backup_plan ] = mock_rpc request = {} - await client.get_auto_protection_policy(request) + await client.delete_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_auto_protection_policy(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() + + await client.delete_backup_plan(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -17912,13 +18283,11 @@ async def test_get_auto_protection_policy_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + backupplan.DeleteBackupPlanRequest(), {}, ], ) -async def test_get_auto_protection_policy_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_delete_backup_plan_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -17930,50 +18299,41 @@ async def test_get_auto_protection_policy_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy), "__call__" + type(client.transport.delete_backup_plan), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicy.AutoProtectionPolicy( - name="name_value", - description="description_value", - state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, - etag="etag_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_auto_protection_policy(request) + response = await client.delete_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + request = backupplan.DeleteBackupPlanRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, autoprotectionpolicy.AutoProtectionPolicy) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING - assert response.etag == "etag_value" + assert isinstance(response, future.Future) -def test_get_auto_protection_policy_field_headers(): +def test_delete_backup_plan_field_headers(): client = BackupDRClient( 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 = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + request = backupplan.DeleteBackupPlanRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy), "__call__" + type(client.transport.delete_backup_plan), "__call__" ) as call: - call.return_value = autoprotectionpolicy.AutoProtectionPolicy() - client.get_auto_protection_policy(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -17989,25 +18349,25 @@ def test_get_auto_protection_policy_field_headers(): @pytest.mark.asyncio -async def test_get_auto_protection_policy_field_headers_async(): +async def test_delete_backup_plan_field_headers_async(): client = BackupDRAsyncClient( 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 = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + request = backupplan.DeleteBackupPlanRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy), "__call__" + type(client.transport.delete_backup_plan), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicy.AutoProtectionPolicy() + operations_pb2.Operation(name="operations/op") ) - await client.get_auto_protection_policy(request) + await client.delete_backup_plan(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -18022,20 +18382,20 @@ async def test_get_auto_protection_policy_field_headers_async(): ) in kw["metadata"] -def test_get_auto_protection_policy_flattened(): +def test_delete_backup_plan_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy), "__call__" + type(client.transport.delete_backup_plan), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + 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.get_auto_protection_policy( + client.delete_backup_plan( name="name_value", ) @@ -18048,7 +18408,7 @@ def test_get_auto_protection_policy_flattened(): assert arg == mock_val -def test_get_auto_protection_policy_flattened_error(): +def test_delete_backup_plan_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -18056,31 +18416,31 @@ def test_get_auto_protection_policy_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_auto_protection_policy( - autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + client.delete_backup_plan( + backupplan.DeleteBackupPlanRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_auto_protection_policy_flattened_async(): +async def test_delete_backup_plan_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy), "__call__" + type(client.transport.delete_backup_plan), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicy.AutoProtectionPolicy() + 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.get_auto_protection_policy( + response = await client.delete_backup_plan( name="name_value", ) @@ -18094,7 +18454,7 @@ async def test_get_auto_protection_policy_flattened_async(): @pytest.mark.asyncio -async def test_get_auto_protection_policy_flattened_error_async(): +async def test_delete_backup_plan_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -18102,8 +18462,8 @@ async def test_get_auto_protection_policy_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.get_auto_protection_policy( - autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + await client.delete_backup_plan( + backupplan.DeleteBackupPlanRequest(), name="name_value", ) @@ -18111,11 +18471,11 @@ async def test_get_auto_protection_policy_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + backupplan.GetBackupPlanRevisionRequest(), {}, ], ) -def test_update_auto_protection_policy(request_type, transport: str = "grpc"): +def test_get_backup_plan_revision(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18127,23 +18487,30 @@ def test_update_auto_protection_policy(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_auto_protection_policy), "__call__" + type(client.transport.get_backup_plan_revision), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_auto_protection_policy(request) + call.return_value = backupplan.BackupPlanRevision( + name="name_value", + revision_id="revision_id_value", + state=backupplan.BackupPlanRevision.State.CREATING, + ) + response = client.get_backup_plan_revision(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + request = backupplan.GetBackupPlanRevisionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_update_auto_protection_policy_non_empty_request_with_auto_populated_field(): + assert isinstance(response, backupplan.BackupPlanRevision) + assert response.name == "name_value" + assert response.revision_id == "revision_id_value" + assert response.state == backupplan.BackupPlanRevision.State.CREATING + + +def test_get_backup_plan_revision_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 = BackupDRClient( @@ -18154,23 +18521,27 @@ def test_update_auto_protection_policy_non_empty_request_with_auto_populated_fie # 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 = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + request = backupplan.GetBackupPlanRevisionRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_auto_protection_policy), "__call__" + type(client.transport.get_backup_plan_revision), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_auto_protection_policy(request=request) + client.get_backup_plan_revision(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + request_msg = backupplan.GetBackupPlanRevisionRequest( + name="name_value", + ) assert args[0] == request_msg -def test_update_auto_protection_policy_use_cached_wrapped_rpc(): +def test_get_backup_plan_revision_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: @@ -18185,7 +18556,7 @@ def test_update_auto_protection_policy_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_auto_protection_policy + client._transport.get_backup_plan_revision in client._transport._wrapped_methods ) @@ -18195,20 +18566,15 @@ def test_update_auto_protection_policy_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_auto_protection_policy + client._transport.get_backup_plan_revision ] = mock_rpc request = {} - client.update_auto_protection_policy(request) + client.get_backup_plan_revision(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.update_auto_protection_policy(request) + client.get_backup_plan_revision(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18216,7 +18582,7 @@ def test_update_auto_protection_policy_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_auto_protection_policy_async_use_cached_wrapped_rpc( +async def test_get_backup_plan_revision_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -18233,7 +18599,7 @@ async def test_update_auto_protection_policy_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_auto_protection_policy + client._client._transport.get_backup_plan_revision in client._client._transport._wrapped_methods ) @@ -18241,21 +18607,16 @@ async def test_update_auto_protection_policy_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_auto_protection_policy + client._client._transport.get_backup_plan_revision ] = mock_rpc request = {} - await client.update_auto_protection_policy(request) + await client.get_backup_plan_revision(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.update_auto_protection_policy(request) + await client.get_backup_plan_revision(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18266,11 +18627,11 @@ async def test_update_auto_protection_policy_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + backupplan.GetBackupPlanRevisionRequest(), {}, ], ) -async def test_update_auto_protection_policy_async( +async def test_get_backup_plan_revision_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -18284,41 +18645,48 @@ async def test_update_auto_protection_policy_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_auto_protection_policy), "__call__" + type(client.transport.get_backup_plan_revision), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupplan.BackupPlanRevision( + name="name_value", + revision_id="revision_id_value", + state=backupplan.BackupPlanRevision.State.CREATING, + ) ) - response = await client.update_auto_protection_policy(request) + response = await client.get_backup_plan_revision(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + request = backupplan.GetBackupPlanRevisionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, backupplan.BackupPlanRevision) + assert response.name == "name_value" + assert response.revision_id == "revision_id_value" + assert response.state == backupplan.BackupPlanRevision.State.CREATING -def test_update_auto_protection_policy_field_headers(): +def test_get_backup_plan_revision_field_headers(): client = BackupDRClient( 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 = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + request = backupplan.GetBackupPlanRevisionRequest() - request.auto_protection_policy.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_auto_protection_policy), "__call__" + type(client.transport.get_backup_plan_revision), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_auto_protection_policy(request) + call.return_value = backupplan.BackupPlanRevision() + client.get_backup_plan_revision(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -18329,30 +18697,30 @@ def test_update_auto_protection_policy_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "auto_protection_policy.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_auto_protection_policy_field_headers_async(): +async def test_get_backup_plan_revision_field_headers_async(): client = BackupDRAsyncClient( 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 = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + request = backupplan.GetBackupPlanRevisionRequest() - request.auto_protection_policy.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_auto_protection_policy), "__call__" + type(client.transport.get_backup_plan_revision), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + backupplan.BackupPlanRevision() ) - await client.update_auto_protection_policy(request) + await client.get_backup_plan_revision(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -18363,43 +18731,37 @@ async def test_update_auto_protection_policy_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "auto_protection_policy.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_auto_protection_policy_flattened(): +def test_get_backup_plan_revision_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_auto_protection_policy), "__call__" + type(client.transport.get_backup_plan_revision), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupplan.BackupPlanRevision() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_auto_protection_policy( - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_backup_plan_revision( + 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].auto_protection_policy - mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_auto_protection_policy_flattened_error(): +def test_get_backup_plan_revision_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -18407,54 +18769,45 @@ def test_update_auto_protection_policy_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_auto_protection_policy( - autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_backup_plan_revision( + backupplan.GetBackupPlanRevisionRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_auto_protection_policy_flattened_async(): +async def test_get_backup_plan_revision_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_auto_protection_policy), "__call__" + type(client.transport.get_backup_plan_revision), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupplan.BackupPlanRevision() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupplan.BackupPlanRevision() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_auto_protection_policy( - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.get_backup_plan_revision( + 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].auto_protection_policy - mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_auto_protection_policy_flattened_error_async(): +async def test_get_backup_plan_revision_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -18462,23 +18815,20 @@ async def test_update_auto_protection_policy_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_auto_protection_policy( - autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.get_backup_plan_revision( + backupplan.GetBackupPlanRevisionRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + backupplan.ListBackupPlanRevisionsRequest(), {}, ], ) -def test_delete_auto_protection_policy(request_type, transport: str = "grpc"): +def test_list_backup_plan_revisions(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18490,23 +18840,28 @@ def test_delete_auto_protection_policy(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_auto_protection_policy), "__call__" + type(client.transport.list_backup_plan_revisions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_auto_protection_policy(request) + call.return_value = backupplan.ListBackupPlanRevisionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_backup_plan_revisions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + request = backupplan.ListBackupPlanRevisionsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListBackupPlanRevisionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_delete_auto_protection_policy_non_empty_request_with_auto_populated_field(): +def test_list_backup_plan_revisions_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 = BackupDRClient( @@ -18517,29 +18872,29 @@ def test_delete_auto_protection_policy_non_empty_request_with_auto_populated_fie # 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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest( - name="name_value", - etag="etag_value", + request = backupplan.ListBackupPlanRevisionsRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_auto_protection_policy), "__call__" + type(client.transport.list_backup_plan_revisions), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_auto_protection_policy(request=request) + client.list_backup_plan_revisions(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest( - name="name_value", - etag="etag_value", + request_msg = backupplan.ListBackupPlanRevisionsRequest( + parent="parent_value", + page_token="page_token_value", ) assert args[0] == request_msg -def test_delete_auto_protection_policy_use_cached_wrapped_rpc(): +def test_list_backup_plan_revisions_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: @@ -18554,7 +18909,7 @@ def test_delete_auto_protection_policy_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_auto_protection_policy + client._transport.list_backup_plan_revisions in client._transport._wrapped_methods ) @@ -18564,20 +18919,15 @@ def test_delete_auto_protection_policy_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_auto_protection_policy + client._transport.list_backup_plan_revisions ] = mock_rpc request = {} - client.delete_auto_protection_policy(request) + client.list_backup_plan_revisions(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_auto_protection_policy(request) + client.list_backup_plan_revisions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18585,7 +18935,7 @@ def test_delete_auto_protection_policy_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_auto_protection_policy_async_use_cached_wrapped_rpc( +async def test_list_backup_plan_revisions_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -18602,7 +18952,7 @@ async def test_delete_auto_protection_policy_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_auto_protection_policy + client._client._transport.list_backup_plan_revisions in client._client._transport._wrapped_methods ) @@ -18610,21 +18960,16 @@ async def test_delete_auto_protection_policy_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_auto_protection_policy + client._client._transport.list_backup_plan_revisions ] = mock_rpc request = {} - await client.delete_auto_protection_policy(request) + await client.list_backup_plan_revisions(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_auto_protection_policy(request) + await client.list_backup_plan_revisions(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18635,11 +18980,11 @@ async def test_delete_auto_protection_policy_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + backupplan.ListBackupPlanRevisionsRequest(), {}, ], ) -async def test_delete_auto_protection_policy_async( +async def test_list_backup_plan_revisions_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -18653,41 +18998,46 @@ async def test_delete_auto_protection_policy_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_auto_protection_policy), "__call__" + type(client.transport.list_backup_plan_revisions), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupplan.ListBackupPlanRevisionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.delete_auto_protection_policy(request) + response = await client.list_backup_plan_revisions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + request = backupplan.ListBackupPlanRevisionsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListBackupPlanRevisionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_delete_auto_protection_policy_field_headers(): +def test_list_backup_plan_revisions_field_headers(): client = BackupDRClient( 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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + request = backupplan.ListBackupPlanRevisionsRequest() - request.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.delete_auto_protection_policy), "__call__" + type(client.transport.list_backup_plan_revisions), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_auto_protection_policy(request) + call.return_value = backupplan.ListBackupPlanRevisionsResponse() + client.list_backup_plan_revisions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -18698,30 +19048,30 @@ def test_delete_auto_protection_policy_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_auto_protection_policy_field_headers_async(): +async def test_list_backup_plan_revisions_field_headers_async(): client = BackupDRAsyncClient( 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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + request = backupplan.ListBackupPlanRevisionsRequest() - request.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.delete_auto_protection_policy), "__call__" + type(client.transport.list_backup_plan_revisions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + backupplan.ListBackupPlanRevisionsResponse() ) - await client.delete_auto_protection_policy(request) + await client.list_backup_plan_revisions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -18732,37 +19082,37 @@ async def test_delete_auto_protection_policy_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_delete_auto_protection_policy_flattened(): +def test_list_backup_plan_revisions_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_auto_protection_policy), "__call__" + type(client.transport.list_backup_plan_revisions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupplan.ListBackupPlanRevisionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_auto_protection_policy( - name="name_value", + client.list_backup_plan_revisions( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_delete_auto_protection_policy_flattened_error(): +def test_list_backup_plan_revisions_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -18770,45 +19120,45 @@ def test_delete_auto_protection_policy_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_auto_protection_policy( - autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), - name="name_value", + client.list_backup_plan_revisions( + backupplan.ListBackupPlanRevisionsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_delete_auto_protection_policy_flattened_async(): +async def test_list_backup_plan_revisions_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_auto_protection_policy), "__call__" + type(client.transport.list_backup_plan_revisions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = backupplan.ListBackupPlanRevisionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupplan.ListBackupPlanRevisionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_auto_protection_policy( - name="name_value", + response = await client.list_backup_plan_revisions( + 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].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_auto_protection_policy_flattened_error_async(): +async def test_list_backup_plan_revisions_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -18816,96 +19166,301 @@ async def test_delete_auto_protection_policy_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.delete_auto_protection_policy( - autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), - name="name_value", + await client.list_backup_plan_revisions( + backupplan.ListBackupPlanRevisionsRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), - {}, - ], -) -def test_create_auto_protection_policy_binding(request_type, transport: str = "grpc"): +def test_list_backup_plan_revisions_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_auto_protection_policy_binding), "__call__" + type(client.transport.list_backup_plan_revisions), "__call__" ) as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_auto_protection_policy_binding(request) + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + RuntimeError, + ) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backup_plan_revisions( + request={}, retry=retry, timeout=timeout + ) - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + 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__}<") -def test_create_auto_protection_policy_binding_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. + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupplan.BackupPlanRevision) for i in results) + + +def test_list_backup_plan_revisions_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) - # 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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( - parent="parent_value", - auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backup_plan_revisions(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_backup_plan_revisions_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_auto_protection_policy_binding), "__call__" + type(client.transport.list_backup_plan_revisions), + "__call__", + new_callable=mock.AsyncMock, ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + RuntimeError, ) - client.create_auto_protection_policy_binding(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( - parent="parent_value", - auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + async_pager = await client.list_backup_plan_revisions( + request={}, ) - assert args[0] == request_msg + 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) -def test_create_auto_protection_policy_binding_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + assert len(responses) == 6 + assert all(isinstance(i, backupplan.BackupPlanRevision) for i in responses) - # 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_auto_protection_policy_binding +@pytest.mark.asyncio +async def test_list_backup_plan_revisions_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_backup_plan_revisions(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", + [ + backupplanassociation.CreateBackupPlanAssociationRequest(), + {}, + ], +) +def test_create_backup_plan_association(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplanassociation.CreateBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_backup_plan_association_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 = BackupDRClient( + 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 = backupplanassociation.CreateBackupPlanAssociationRequest( + parent="parent_value", + backup_plan_association_id="backup_plan_association_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_backup_plan_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.CreateBackupPlanAssociationRequest( + parent="parent_value", + backup_plan_association_id="backup_plan_association_id_value", + ) + assert args[0] == request_msg + + +def test_create_backup_plan_association_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_backup_plan_association in client._transport._wrapped_methods ) @@ -18915,10 +19470,10 @@ def test_create_auto_protection_policy_binding_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_auto_protection_policy_binding + client._transport.create_backup_plan_association ] = mock_rpc request = {} - client.create_auto_protection_policy_binding(request) + client.create_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -18928,7 +19483,7 @@ def test_create_auto_protection_policy_binding_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_auto_protection_policy_binding(request) + client.create_backup_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18936,7 +19491,7 @@ def test_create_auto_protection_policy_binding_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_auto_protection_policy_binding_async_use_cached_wrapped_rpc( +async def test_create_backup_plan_association_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -18953,7 +19508,7 @@ async def test_create_auto_protection_policy_binding_async_use_cached_wrapped_rp # Ensure method has been cached assert ( - client._client._transport.create_auto_protection_policy_binding + client._client._transport.create_backup_plan_association in client._client._transport._wrapped_methods ) @@ -18961,11 +19516,11 @@ async def test_create_auto_protection_policy_binding_async_use_cached_wrapped_rp mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_auto_protection_policy_binding + client._client._transport.create_backup_plan_association ] = mock_rpc request = {} - await client.create_auto_protection_policy_binding(request) + await client.create_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -18975,7 +19530,7 @@ async def test_create_auto_protection_policy_binding_async_use_cached_wrapped_rp # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_auto_protection_policy_binding(request) + await client.create_backup_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -18986,11 +19541,11 @@ async def test_create_auto_protection_policy_binding_async_use_cached_wrapped_rp @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + backupplanassociation.CreateBackupPlanAssociationRequest(), {}, ], ) -async def test_create_auto_protection_policy_binding_async( +async def test_create_backup_plan_association_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -19004,41 +19559,41 @@ async def test_create_auto_protection_policy_binding_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_auto_protection_policy_binding), "__call__" + type(client.transport.create_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_auto_protection_policy_binding(request) + response = await client.create_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + request = backupplanassociation.CreateBackupPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_auto_protection_policy_binding_field_headers(): +def test_create_backup_plan_association_field_headers(): client = BackupDRClient( 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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + request = backupplanassociation.CreateBackupPlanAssociationRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_auto_protection_policy_binding), "__call__" + type(client.transport.create_backup_plan_association), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_auto_protection_policy_binding(request) + client.create_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -19054,25 +19609,25 @@ def test_create_auto_protection_policy_binding_field_headers(): @pytest.mark.asyncio -async def test_create_auto_protection_policy_binding_field_headers_async(): +async def test_create_backup_plan_association_field_headers_async(): client = BackupDRAsyncClient( 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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + request = backupplanassociation.CreateBackupPlanAssociationRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_auto_protection_policy_binding), "__call__" + type(client.transport.create_backup_plan_association), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_auto_protection_policy_binding(request) + await client.create_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -19087,25 +19642,27 @@ async def test_create_auto_protection_policy_binding_field_headers_async(): ) in kw["metadata"] -def test_create_auto_protection_policy_binding_flattened(): +def test_create_backup_plan_association_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_auto_protection_policy_binding), "__call__" + type(client.transport.create_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_auto_protection_policy_binding( + client.create_backup_plan_association( parent="parent_value", - auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value" + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) ), - auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + backup_plan_association_id="backup_plan_association_id_value", ) # Establish that the underlying call was made with the expected @@ -19115,17 +19672,19 @@ def test_create_auto_protection_policy_binding_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].auto_protection_policy_binding - mock_val = autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value" + arg = args[0].backup_plan_association + mock_val = backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) ) assert arg == mock_val - arg = args[0].auto_protection_policy_binding_id - mock_val = "auto_protection_policy_binding_id_value" + arg = args[0].backup_plan_association_id + mock_val = "backup_plan_association_id_value" assert arg == mock_val -def test_create_auto_protection_policy_binding_flattened_error(): +def test_create_backup_plan_association_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -19133,25 +19692,27 @@ def test_create_auto_protection_policy_binding_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_auto_protection_policy_binding( - autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + client.create_backup_plan_association( + backupplanassociation.CreateBackupPlanAssociationRequest(), parent="parent_value", - auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value" + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) ), - auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + backup_plan_association_id="backup_plan_association_id_value", ) @pytest.mark.asyncio -async def test_create_auto_protection_policy_binding_flattened_async(): +async def test_create_backup_plan_association_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_auto_protection_policy_binding), "__call__" + type(client.transport.create_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -19161,12 +19722,14 @@ async def test_create_auto_protection_policy_binding_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_auto_protection_policy_binding( + response = await client.create_backup_plan_association( parent="parent_value", - auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value" + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) ), - auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + backup_plan_association_id="backup_plan_association_id_value", ) # Establish that the underlying call was made with the expected @@ -19176,18 +19739,20 @@ async def test_create_auto_protection_policy_binding_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].auto_protection_policy_binding - mock_val = autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value" + arg = args[0].backup_plan_association + mock_val = backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) ) assert arg == mock_val - arg = args[0].auto_protection_policy_binding_id - mock_val = "auto_protection_policy_binding_id_value" + arg = args[0].backup_plan_association_id + mock_val = "backup_plan_association_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_auto_protection_policy_binding_flattened_error_async(): +async def test_create_backup_plan_association_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -19195,24 +19760,26 @@ async def test_create_auto_protection_policy_binding_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.create_auto_protection_policy_binding( - autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + await client.create_backup_plan_association( + backupplanassociation.CreateBackupPlanAssociationRequest(), parent="parent_value", - auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value" + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) ), - auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + backup_plan_association_id="backup_plan_association_id_value", ) @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + backupplanassociation.UpdateBackupPlanAssociationRequest(), {}, ], ) -def test_get_auto_protection_policy_binding(request_type, transport: str = "grpc"): +def test_update_backup_plan_association(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19224,37 +19791,23 @@ def test_get_auto_protection_policy_binding(request_type, transport: str = "grpc # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy_binding), "__call__" + type(client.transport.update_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value", - description="description_value", - state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, - scope="scope_value", - etag="etag_value", - ) - response = client.get_auto_protection_policy_binding(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + request = backupplanassociation.UpdateBackupPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( - response.state - == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING - ) - assert response.scope == "scope_value" - assert response.etag == "etag_value" + assert isinstance(response, future.Future) -def test_get_auto_protection_policy_binding_non_empty_request_with_auto_populated_field(): +def test_update_backup_plan_association_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 = BackupDRClient( @@ -19265,27 +19818,23 @@ def test_get_auto_protection_policy_binding_non_empty_request_with_auto_populate # 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 = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( - name="name_value", - ) + request = backupplanassociation.UpdateBackupPlanAssociationRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy_binding), "__call__" + type(client.transport.update_backup_plan_association), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_auto_protection_policy_binding(request=request) + client.update_backup_plan_association(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( - name="name_value", - ) + request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() assert args[0] == request_msg -def test_get_auto_protection_policy_binding_use_cached_wrapped_rpc(): +def test_update_backup_plan_association_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: @@ -19300,7 +19849,7 @@ def test_get_auto_protection_policy_binding_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_auto_protection_policy_binding + client._transport.update_backup_plan_association in client._transport._wrapped_methods ) @@ -19310,15 +19859,20 @@ def test_get_auto_protection_policy_binding_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_auto_protection_policy_binding + client._transport.update_backup_plan_association ] = mock_rpc request = {} - client.get_auto_protection_policy_binding(request) + client.update_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_auto_protection_policy_binding(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.update_backup_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19326,7 +19880,7 @@ def test_get_auto_protection_policy_binding_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_auto_protection_policy_binding_async_use_cached_wrapped_rpc( +async def test_update_backup_plan_association_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -19343,7 +19897,7 @@ async def test_get_auto_protection_policy_binding_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_auto_protection_policy_binding + client._client._transport.update_backup_plan_association in client._client._transport._wrapped_methods ) @@ -19351,16 +19905,21 @@ async def test_get_auto_protection_policy_binding_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_auto_protection_policy_binding + client._client._transport.update_backup_plan_association ] = mock_rpc request = {} - await client.get_auto_protection_policy_binding(request) + await client.update_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_auto_protection_policy_binding(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() + + await client.update_backup_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19371,11 +19930,11 @@ async def test_get_auto_protection_policy_binding_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + backupplanassociation.UpdateBackupPlanAssociationRequest(), {}, ], ) -async def test_get_auto_protection_policy_binding_async( +async def test_update_backup_plan_association_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -19389,55 +19948,41 @@ async def test_get_auto_protection_policy_binding_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy_binding), "__call__" + type(client.transport.update_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value", - description="description_value", - state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, - scope="scope_value", - etag="etag_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_auto_protection_policy_binding(request) + response = await client.update_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + request = backupplanassociation.UpdateBackupPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) - assert response.name == "name_value" - assert response.description == "description_value" - assert ( - response.state - == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING - ) - assert response.scope == "scope_value" - assert response.etag == "etag_value" + assert isinstance(response, future.Future) -def test_get_auto_protection_policy_binding_field_headers(): +def test_update_backup_plan_association_field_headers(): client = BackupDRClient( 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 = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + request = backupplanassociation.UpdateBackupPlanAssociationRequest() - request.name = "name_value" + request.backup_plan_association.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy_binding), "__call__" + type(client.transport.update_backup_plan_association), "__call__" ) as call: - call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() - client.get_auto_protection_policy_binding(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -19448,30 +19993,30 @@ def test_get_auto_protection_policy_binding_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "backup_plan_association.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_auto_protection_policy_binding_field_headers_async(): +async def test_update_backup_plan_association_field_headers_async(): client = BackupDRAsyncClient( 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 = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + request = backupplanassociation.UpdateBackupPlanAssociationRequest() - request.name = "name_value" + request.backup_plan_association.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy_binding), "__call__" + type(client.transport.update_backup_plan_association), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicybinding.AutoProtectionPolicyBinding() + operations_pb2.Operation(name="operations/op") ) - await client.get_auto_protection_policy_binding(request) + await client.update_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -19482,37 +20027,49 @@ async def test_get_auto_protection_policy_binding_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "backup_plan_association.name=name_value", ) in kw["metadata"] -def test_get_auto_protection_policy_binding_flattened(): +def test_update_backup_plan_association_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy_binding), "__call__" + type(client.transport.update_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + 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.get_auto_protection_policy_binding( - name="name_value", + client.update_backup_plan_association( + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + 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].backup_plan_association + mock_val = backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_get_auto_protection_policy_binding_flattened_error(): +def test_update_backup_plan_association_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -19520,45 +20077,62 @@ def test_get_auto_protection_policy_binding_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_auto_protection_policy_binding( - autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), - name="name_value", + client.update_backup_plan_association( + backupplanassociation.UpdateBackupPlanAssociationRequest(), + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_get_auto_protection_policy_binding_flattened_async(): +async def test_update_backup_plan_association_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_auto_protection_policy_binding), "__call__" + type(client.transport.update_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicybinding.AutoProtectionPolicyBinding() + 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.get_auto_protection_policy_binding( - name="name_value", + response = await client.update_backup_plan_association( + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + 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].backup_plan_association + mock_val = backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ) + 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_get_auto_protection_policy_binding_flattened_error_async(): +async def test_update_backup_plan_association_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -19566,20 +20140,25 @@ async def test_get_auto_protection_policy_binding_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.get_auto_protection_policy_binding( - autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), - name="name_value", + await client.update_backup_plan_association( + backupplanassociation.UpdateBackupPlanAssociationRequest(), + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + backupplanassociation.GetBackupPlanAssociationRequest(), {}, ], ) -def test_list_auto_protection_policy_bindings(request_type, transport: str = "grpc"): +def test_get_backup_plan_association(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -19591,30 +20170,45 @@ def test_list_auto_protection_policy_bindings(request_type, transport: str = "gr # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), "__call__" + type(client.transport.get_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + call.return_value = backupplanassociation.BackupPlanAssociation( + name="name_value", + resource_type="resource_type_value", + resource="resource_value", + backup_plan="backup_plan_value", + state=backupplanassociation.BackupPlanAssociation.State.CREATING, + data_source="data_source_value", + backup_plan_revision_id="backup_plan_revision_id_value", + backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", ) - response = client.list_auto_protection_policy_bindings(request) + response = client.get_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + request = backupplanassociation.GetBackupPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, backupplanassociation.BackupPlanAssociation) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert response.resource == "resource_value" + assert response.backup_plan == "backup_plan_value" + assert response.state == backupplanassociation.BackupPlanAssociation.State.CREATING + assert response.data_source == "data_source_value" + assert response.backup_plan_revision_id == "backup_plan_revision_id_value" + assert response.backup_plan_revision_name == "backup_plan_revision_name_value" + assert ( + response.auto_protection_policy_binding + == "auto_protection_policy_binding_value" + ) -def test_list_auto_protection_policy_bindings_non_empty_request_with_auto_populated_field(): +def test_get_backup_plan_association_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 = BackupDRClient( @@ -19625,35 +20219,27 @@ def test_list_auto_protection_policy_bindings_non_empty_request_with_auto_popula # 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = backupplanassociation.GetBackupPlanAssociationRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), "__call__" + type(client.transport.get_backup_plan_association), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_auto_protection_policy_bindings(request=request) + client.get_backup_plan_association(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", - ) + request_msg = backupplanassociation.GetBackupPlanAssociationRequest( + name="name_value", ) assert args[0] == request_msg -def test_list_auto_protection_policy_bindings_use_cached_wrapped_rpc(): +def test_get_backup_plan_association_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: @@ -19668,7 +20254,7 @@ def test_list_auto_protection_policy_bindings_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_auto_protection_policy_bindings + client._transport.get_backup_plan_association in client._transport._wrapped_methods ) @@ -19678,15 +20264,15 @@ def test_list_auto_protection_policy_bindings_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_auto_protection_policy_bindings + client._transport.get_backup_plan_association ] = mock_rpc request = {} - client.list_auto_protection_policy_bindings(request) + client.get_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_auto_protection_policy_bindings(request) + client.get_backup_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19694,7 +20280,7 @@ def test_list_auto_protection_policy_bindings_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_auto_protection_policy_bindings_async_use_cached_wrapped_rpc( +async def test_get_backup_plan_association_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -19711,7 +20297,7 @@ async def test_list_auto_protection_policy_bindings_async_use_cached_wrapped_rpc # Ensure method has been cached assert ( - client._client._transport.list_auto_protection_policy_bindings + client._client._transport.get_backup_plan_association in client._client._transport._wrapped_methods ) @@ -19719,16 +20305,16 @@ async def test_list_auto_protection_policy_bindings_async_use_cached_wrapped_rpc mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_auto_protection_policy_bindings + client._client._transport.get_backup_plan_association ] = mock_rpc request = {} - await client.list_auto_protection_policy_bindings(request) + await client.get_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_auto_protection_policy_bindings(request) + await client.get_backup_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -19739,11 +20325,11 @@ async def test_list_auto_protection_policy_bindings_async_use_cached_wrapped_rpc @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + backupplanassociation.GetBackupPlanAssociationRequest(), {}, ], ) -async def test_list_auto_protection_policy_bindings_async( +async def test_get_backup_plan_association_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -19757,48 +20343,63 @@ async def test_list_auto_protection_policy_bindings_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), "__call__" + type(client.transport.get_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + backupplanassociation.BackupPlanAssociation( + name="name_value", + resource_type="resource_type_value", + resource="resource_value", + backup_plan="backup_plan_value", + state=backupplanassociation.BackupPlanAssociation.State.CREATING, + data_source="data_source_value", + backup_plan_revision_id="backup_plan_revision_id_value", + backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", ) ) - response = await client.list_auto_protection_policy_bindings(request) + response = await client.get_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + request = backupplanassociation.GetBackupPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, backupplanassociation.BackupPlanAssociation) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert response.resource == "resource_value" + assert response.backup_plan == "backup_plan_value" + assert response.state == backupplanassociation.BackupPlanAssociation.State.CREATING + assert response.data_source == "data_source_value" + assert response.backup_plan_revision_id == "backup_plan_revision_id_value" + assert response.backup_plan_revision_name == "backup_plan_revision_name_value" + assert ( + response.auto_protection_policy_binding + == "auto_protection_policy_binding_value" + ) -def test_list_auto_protection_policy_bindings_field_headers(): +def test_get_backup_plan_association_field_headers(): client = BackupDRClient( 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + request = backupplanassociation.GetBackupPlanAssociationRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), "__call__" + type(client.transport.get_backup_plan_association), "__call__" ) as call: - call.return_value = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() - ) - client.list_auto_protection_policy_bindings(request) + call.return_value = backupplanassociation.BackupPlanAssociation() + client.get_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -19809,30 +20410,30 @@ def test_list_auto_protection_policy_bindings_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_auto_protection_policy_bindings_field_headers_async(): +async def test_get_backup_plan_association_field_headers_async(): client = BackupDRAsyncClient( 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + request = backupplanassociation.GetBackupPlanAssociationRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), "__call__" + type(client.transport.get_backup_plan_association), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + backupplanassociation.BackupPlanAssociation() ) - await client.list_auto_protection_policy_bindings(request) + await client.get_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -19843,39 +20444,37 @@ async def test_list_auto_protection_policy_bindings_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_auto_protection_policy_bindings_flattened(): +def test_get_backup_plan_association_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), "__call__" + type(client.transport.get_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() - ) + call.return_value = backupplanassociation.BackupPlanAssociation() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_auto_protection_policy_bindings( - parent="parent_value", + client.get_backup_plan_association( + 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_auto_protection_policy_bindings_flattened_error(): +def test_get_backup_plan_association_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -19883,47 +20482,45 @@ def test_list_auto_protection_policy_bindings_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_auto_protection_policy_bindings( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), - parent="parent_value", + client.get_backup_plan_association( + backupplanassociation.GetBackupPlanAssociationRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_auto_protection_policy_bindings_flattened_async(): +async def test_get_backup_plan_association_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), "__call__" + type(client.transport.get_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() - ) + call.return_value = backupplanassociation.BackupPlanAssociation() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + backupplanassociation.BackupPlanAssociation() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_auto_protection_policy_bindings( - parent="parent_value", + response = await client.get_backup_plan_association( + 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" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_auto_protection_policy_bindings_flattened_error_async(): +async def test_get_backup_plan_association_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -19931,233 +20528,20 @@ async def test_list_auto_protection_policy_bindings_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.list_auto_protection_policy_bindings( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), - parent="parent_value", - ) - - -def test_list_auto_protection_policy_bindings_pager(transport_name: str = "grpc"): - client = BackupDRClient( - 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_auto_protection_policy_bindings), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - next_page_token="abc", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[], - next_page_token="def", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - next_page_token="ghi", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_auto_protection_policy_bindings( - 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, autoprotectionpolicybinding.AutoProtectionPolicyBinding) - for i in results - ) - - -def test_list_auto_protection_policy_bindings_pages(transport_name: str = "grpc"): - client = BackupDRClient( - 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_auto_protection_policy_bindings), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - next_page_token="abc", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[], - next_page_token="def", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - next_page_token="ghi", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - ), - RuntimeError, - ) - pages = list(client.list_auto_protection_policy_bindings(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_auto_protection_policy_bindings_async_pager(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - next_page_token="abc", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[], - next_page_token="def", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - next_page_token="ghi", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_auto_protection_policy_bindings( - 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, autoprotectionpolicybinding.AutoProtectionPolicyBinding) - for i in responses - ) - - -@pytest.mark.asyncio -async def test_list_auto_protection_policy_bindings_async_pages(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - next_page_token="abc", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[], - next_page_token="def", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - next_page_token="ghi", - ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - ], - ), - RuntimeError, + await client.get_backup_plan_association( + backupplanassociation.GetBackupPlanAssociationRequest(), + name="name_value", ) - pages = [] - async for page_ in ( - await client.list_auto_protection_policy_bindings(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", [ - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + backupplanassociation.ListBackupPlanAssociationsRequest(), {}, ], ) -def test_list_applied_auto_protection_policies(request_type, transport: str = "grpc"): +def test_list_backup_plan_associations(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -20169,30 +20553,28 @@ def test_list_applied_auto_protection_policies(request_type, transport: str = "g # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" + type(client.transport.list_backup_plan_associations), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - response = client.list_applied_auto_protection_policies(request) + response = client.list_backup_plan_associations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + request = backupplanassociation.ListBackupPlanAssociationsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAppliedAutoProtectionPoliciesPager) + assert isinstance(response, pagers.ListBackupPlanAssociationsPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_applied_auto_protection_policies_non_empty_request_with_auto_populated_field(): +def test_list_backup_plan_associations_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 = BackupDRClient( @@ -20203,35 +20585,31 @@ def test_list_applied_auto_protection_policies_non_empty_request_with_auto_popul # 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + request = backupplanassociation.ListBackupPlanAssociationsRequest( 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_applied_auto_protection_policies), "__call__" + type(client.transport.list_backup_plan_associations), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_applied_auto_protection_policies(request=request) + client.list_backup_plan_associations(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", - ) + request_msg = backupplanassociation.ListBackupPlanAssociationsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", ) assert args[0] == request_msg -def test_list_applied_auto_protection_policies_use_cached_wrapped_rpc(): +def test_list_backup_plan_associations_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: @@ -20246,7 +20624,7 @@ def test_list_applied_auto_protection_policies_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_applied_auto_protection_policies + client._transport.list_backup_plan_associations in client._transport._wrapped_methods ) @@ -20256,15 +20634,15 @@ def test_list_applied_auto_protection_policies_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_applied_auto_protection_policies + client._transport.list_backup_plan_associations ] = mock_rpc request = {} - client.list_applied_auto_protection_policies(request) + client.list_backup_plan_associations(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_applied_auto_protection_policies(request) + client.list_backup_plan_associations(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -20272,7 +20650,7 @@ def test_list_applied_auto_protection_policies_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_applied_auto_protection_policies_async_use_cached_wrapped_rpc( +async def test_list_backup_plan_associations_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -20289,7 +20667,7 @@ async def test_list_applied_auto_protection_policies_async_use_cached_wrapped_rp # Ensure method has been cached assert ( - client._client._transport.list_applied_auto_protection_policies + client._client._transport.list_backup_plan_associations in client._client._transport._wrapped_methods ) @@ -20297,16 +20675,16 @@ async def test_list_applied_auto_protection_policies_async_use_cached_wrapped_rp mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_applied_auto_protection_policies + client._client._transport.list_backup_plan_associations ] = mock_rpc request = {} - await client.list_applied_auto_protection_policies(request) + await client.list_backup_plan_associations(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_applied_auto_protection_policies(request) + await client.list_backup_plan_associations(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -20317,11 +20695,11 @@ async def test_list_applied_auto_protection_policies_async_use_cached_wrapped_rp @pytest.mark.parametrize( "request_type", [ - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + backupplanassociation.ListBackupPlanAssociationsRequest(), {}, ], ) -async def test_list_applied_auto_protection_policies_async( +async def test_list_backup_plan_associations_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -20335,48 +20713,46 @@ async def test_list_applied_auto_protection_policies_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" + type(client.transport.list_backup_plan_associations), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + backupplanassociation.ListBackupPlanAssociationsResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) ) - response = await client.list_applied_auto_protection_policies(request) + response = await client.list_backup_plan_associations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + request = backupplanassociation.ListBackupPlanAssociationsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAppliedAutoProtectionPoliciesAsyncPager) + assert isinstance(response, pagers.ListBackupPlanAssociationsAsyncPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_applied_auto_protection_policies_field_headers(): +def test_list_backup_plan_associations_field_headers(): client = BackupDRClient( 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + request = backupplanassociation.ListBackupPlanAssociationsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" + type(client.transport.list_backup_plan_associations), "__call__" ) as call: - call.return_value = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() - ) - client.list_applied_auto_protection_policies(request) + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + client.list_backup_plan_associations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -20392,25 +20768,25 @@ def test_list_applied_auto_protection_policies_field_headers(): @pytest.mark.asyncio -async def test_list_applied_auto_protection_policies_field_headers_async(): +async def test_list_backup_plan_associations_field_headers_async(): client = BackupDRAsyncClient( 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + request = backupplanassociation.ListBackupPlanAssociationsRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" + type(client.transport.list_backup_plan_associations), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + backupplanassociation.ListBackupPlanAssociationsResponse() ) - await client.list_applied_auto_protection_policies(request) + await client.list_backup_plan_associations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -20425,22 +20801,20 @@ async def test_list_applied_auto_protection_policies_field_headers_async(): ) in kw["metadata"] -def test_list_applied_auto_protection_policies_flattened(): +def test_list_backup_plan_associations_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" + type(client.transport.list_backup_plan_associations), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() - ) + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_applied_auto_protection_policies( + client.list_backup_plan_associations( parent="parent_value", ) @@ -20453,7 +20827,7 @@ def test_list_applied_auto_protection_policies_flattened(): assert arg == mock_val -def test_list_applied_auto_protection_policies_flattened_error(): +def test_list_backup_plan_associations_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -20461,33 +20835,31 @@ def test_list_applied_auto_protection_policies_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_applied_auto_protection_policies( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + client.list_backup_plan_associations( + backupplanassociation.ListBackupPlanAssociationsRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_applied_auto_protection_policies_flattened_async(): +async def test_list_backup_plan_associations_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" + type(client.transport.list_backup_plan_associations), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() - ) + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + backupplanassociation.ListBackupPlanAssociationsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_applied_auto_protection_policies( + response = await client.list_backup_plan_associations( parent="parent_value", ) @@ -20501,7 +20873,7 @@ async def test_list_applied_auto_protection_policies_flattened_async(): @pytest.mark.asyncio -async def test_list_applied_auto_protection_policies_flattened_error_async(): +async def test_list_backup_plan_associations_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -20509,13 +20881,13 @@ async def test_list_applied_auto_protection_policies_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.list_applied_auto_protection_policies( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + await client.list_backup_plan_associations( + backupplanassociation.ListBackupPlanAssociationsRequest(), parent="parent_value", ) -def test_list_applied_auto_protection_policies_pager(transport_name: str = "grpc"): +def test_list_backup_plan_associations_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -20523,32 +20895,32 @@ def test_list_applied_auto_protection_policies_pager(transport_name: str = "grpc # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" + type(client.transport.list_backup_plan_associations), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), ], next_page_token="abc", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[], + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], next_page_token="def", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), ], next_page_token="ghi", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), ], ), RuntimeError, @@ -20560,7 +20932,7 @@ def test_list_applied_auto_protection_policies_pager(transport_name: str = "grpc expected_metadata = tuple(expected_metadata) + ( gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - pager = client.list_applied_auto_protection_policies( + pager = client.list_backup_plan_associations( request={}, retry=retry, timeout=timeout ) @@ -20574,12 +20946,11 @@ def test_list_applied_auto_protection_policies_pager(transport_name: str = "grpc results = list(pager) assert len(results) == 6 assert all( - isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) - for i in results + isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results ) -def test_list_applied_auto_protection_policies_pages(transport_name: str = "grpc"): +def test_list_backup_plan_associations_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport_name, @@ -20587,82 +20958,82 @@ def test_list_applied_auto_protection_policies_pages(transport_name: str = "grpc # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" + type(client.transport.list_backup_plan_associations), "__call__" ) as call: # Set the response to a series of pages. call.side_effect = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), ], next_page_token="abc", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[], + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], next_page_token="def", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), ], next_page_token="ghi", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), ], ), RuntimeError, ) - pages = list(client.list_applied_auto_protection_policies(request={}).pages) + pages = list(client.list_backup_plan_associations(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_applied_auto_protection_policies_async_pager(): +async def test_list_backup_plan_associations_async_pager(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), + type(client.transport.list_backup_plan_associations), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), ], next_page_token="abc", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[], + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], next_page_token="def", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), ], next_page_token="ghi", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), ], ), RuntimeError, ) - async_pager = await client.list_applied_auto_protection_policies( + async_pager = await client.list_backup_plan_associations( request={}, ) assert async_pager.next_page_token == "abc" @@ -20674,54 +21045,54 @@ async def test_list_applied_auto_protection_policies_async_pager(): assert len(responses) == 6 assert all( - isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + isinstance(i, backupplanassociation.BackupPlanAssociation) for i in responses ) @pytest.mark.asyncio -async def test_list_applied_auto_protection_policies_async_pages(): +async def test_list_backup_plan_associations_async_pages(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), + type(client.transport.list_backup_plan_associations), "__call__", new_callable=mock.AsyncMock, ) as call: # Set the response to a series of pages. call.side_effect = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), ], next_page_token="abc", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[], + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], next_page_token="def", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), ], next_page_token="ghi", ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), ], ), RuntimeError, ) pages = [] async for page_ in ( - await client.list_applied_auto_protection_policies(request={}) + await client.list_backup_plan_associations(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -20731,11 +21102,11 @@ async def test_list_applied_auto_protection_policies_async_pages(): @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), {}, ], ) -def test_initiate_delete_auto_protection_policy_binding( +def test_fetch_backup_plan_associations_for_resource_type( request_type, transport: str = "grpc" ): client = BackupDRClient( @@ -20749,24 +21120,31 @@ def test_initiate_delete_auto_protection_policy_binding( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.initiate_delete_auto_protection_policy_binding), + type(client.transport.fetch_backup_plan_associations_for_resource_type), "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.initiate_delete_auto_protection_policy_binding(request) + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.fetch_backup_plan_associations_for_resource_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.FetchBackupPlanAssociationsForResourceTypePager) + assert response.next_page_token == "next_page_token_value" -def test_initiate_delete_auto_protection_policy_binding_non_empty_request_with_auto_populated_field(): +def test_fetch_backup_plan_associations_for_resource_type_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 = BackupDRClient( @@ -20777,30 +21155,38 @@ def test_initiate_delete_auto_protection_policy_binding_non_empty_request_with_a # 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 = ( - autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( - name="name_value", - ) + request = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_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.initiate_delete_auto_protection_policy_binding), + type(client.transport.fetch_backup_plan_associations_for_resource_type), "__call__", ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.initiate_delete_auto_protection_policy_binding(request=request) + client.fetch_backup_plan_associations_for_resource_type(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( - name="name_value", + request_msg = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) ) assert args[0] == request_msg -def test_initiate_delete_auto_protection_policy_binding_use_cached_wrapped_rpc(): +def test_fetch_backup_plan_associations_for_resource_type_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: @@ -20815,7 +21201,7 @@ def test_initiate_delete_auto_protection_policy_binding_use_cached_wrapped_rpc() # Ensure method has been cached assert ( - client._transport.initiate_delete_auto_protection_policy_binding + client._transport.fetch_backup_plan_associations_for_resource_type in client._transport._wrapped_methods ) @@ -20825,20 +21211,15 @@ def test_initiate_delete_auto_protection_policy_binding_use_cached_wrapped_rpc() "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.initiate_delete_auto_protection_policy_binding + client._transport.fetch_backup_plan_associations_for_resource_type ] = mock_rpc request = {} - client.initiate_delete_auto_protection_policy_binding(request) + client.fetch_backup_plan_associations_for_resource_type(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.initiate_delete_auto_protection_policy_binding(request) + client.fetch_backup_plan_associations_for_resource_type(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -20846,7 +21227,7 @@ def test_initiate_delete_auto_protection_policy_binding_use_cached_wrapped_rpc() @pytest.mark.asyncio -async def test_initiate_delete_auto_protection_policy_binding_async_use_cached_wrapped_rpc( +async def test_fetch_backup_plan_associations_for_resource_type_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -20863,7 +21244,7 @@ async def test_initiate_delete_auto_protection_policy_binding_async_use_cached_w # Ensure method has been cached assert ( - client._client._transport.initiate_delete_auto_protection_policy_binding + client._client._transport.fetch_backup_plan_associations_for_resource_type in client._client._transport._wrapped_methods ) @@ -20871,21 +21252,16 @@ async def test_initiate_delete_auto_protection_policy_binding_async_use_cached_w mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.initiate_delete_auto_protection_policy_binding + client._client._transport.fetch_backup_plan_associations_for_resource_type ] = mock_rpc request = {} - await client.initiate_delete_auto_protection_policy_binding(request) + await client.fetch_backup_plan_associations_for_resource_type(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.initiate_delete_auto_protection_policy_binding(request) + await client.fetch_backup_plan_associations_for_resource_type(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -20896,11 +21272,11 @@ async def test_initiate_delete_auto_protection_policy_binding_async_use_cached_w @pytest.mark.parametrize( "request_type", [ - autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), {}, ], ) -async def test_initiate_delete_auto_protection_policy_binding_async( +async def test_fetch_backup_plan_associations_for_resource_type_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -20914,45 +21290,54 @@ async def test_initiate_delete_auto_protection_policy_binding_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.initiate_delete_auto_protection_policy_binding), + type(client.transport.fetch_backup_plan_associations_for_resource_type), "__call__", ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.fetch_backup_plan_associations_for_resource_type( + request ) - response = await client.initiate_delete_auto_protection_policy_binding(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + request = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance( + response, pagers.FetchBackupPlanAssociationsForResourceTypeAsyncPager + ) + assert response.next_page_token == "next_page_token_value" -def test_initiate_delete_auto_protection_policy_binding_field_headers(): +def test_fetch_backup_plan_associations_for_resource_type_field_headers(): client = BackupDRClient( 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 = ( - autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() - ) + request = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() - request.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.initiate_delete_auto_protection_policy_binding), + type(client.transport.fetch_backup_plan_associations_for_resource_type), "__call__", ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.initiate_delete_auto_protection_policy_binding(request) + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + client.fetch_backup_plan_associations_for_resource_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -20963,33 +21348,31 @@ def test_initiate_delete_auto_protection_policy_binding_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_initiate_delete_auto_protection_policy_binding_field_headers_async(): +async def test_fetch_backup_plan_associations_for_resource_type_field_headers_async(): client = BackupDRAsyncClient( 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 = ( - autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() - ) + request = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() - request.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.initiate_delete_auto_protection_policy_binding), + type(client.transport.fetch_backup_plan_associations_for_resource_type), "__call__", ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() ) - await client.initiate_delete_auto_protection_policy_binding(request) + await client.fetch_backup_plan_associations_for_resource_type(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -21000,38 +21383,44 @@ async def test_initiate_delete_auto_protection_policy_binding_field_headers_asyn _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_initiate_delete_auto_protection_policy_binding_flattened(): +def test_fetch_backup_plan_associations_for_resource_type_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.initiate_delete_auto_protection_policy_binding), + type(client.transport.fetch_backup_plan_associations_for_resource_type), "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.initiate_delete_auto_protection_policy_binding( - name="name_value", + client.fetch_backup_plan_associations_for_resource_type( + parent="parent_value", + resource_type="resource_type_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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource_type + mock_val = "resource_type_value" assert arg == mock_val -def test_initiate_delete_auto_protection_policy_binding_flattened_error(): +def test_fetch_backup_plan_associations_for_resource_type_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -21039,46 +21428,53 @@ def test_initiate_delete_auto_protection_policy_binding_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.initiate_delete_auto_protection_policy_binding( - autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), - name="name_value", + client.fetch_backup_plan_associations_for_resource_type( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", ) @pytest.mark.asyncio -async def test_initiate_delete_auto_protection_policy_binding_flattened_async(): +async def test_fetch_backup_plan_associations_for_resource_type_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.initiate_delete_auto_protection_policy_binding), + type(client.transport.fetch_backup_plan_associations_for_resource_type), "__call__", ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.initiate_delete_auto_protection_policy_binding( - name="name_value", + response = await client.fetch_backup_plan_associations_for_resource_type( + parent="parent_value", + resource_type="resource_type_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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].resource_type + mock_val = "resource_type_value" assert arg == mock_val @pytest.mark.asyncio -async def test_initiate_delete_auto_protection_policy_binding_flattened_error_async(): +async def test_fetch_backup_plan_associations_for_resource_type_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -21086,142 +21482,365 @@ async def test_initiate_delete_auto_protection_policy_binding_flattened_error_as # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.initiate_delete_auto_protection_policy_binding( - autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), - name="name_value", + await client.fetch_backup_plan_associations_for_resource_type( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", ) -@pytest.mark.parametrize( - "request_type", - [ - bindingmatchingresource.GetBindingMatchingResourceRequest(), - {}, - ], -) -def test_get_binding_matching_resource(request_type, transport: str = "grpc"): +def test_fetch_backup_plan_associations_for_resource_type_pager( + transport_name: str = "grpc", +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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_binding_matching_resource), "__call__" + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", ) as call: - # Designate an appropriate return value for the call. - call.return_value = bindingmatchingresource.BindingMatchingResource( - name="name_value", - resource="resource_value", + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, ) - response = client.get_binding_matching_resource(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = bindingmatchingresource.GetBindingMatchingResourceRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.fetch_backup_plan_associations_for_resource_type( + request={}, retry=retry, timeout=timeout + ) - # Establish that the response is the type that we expect. - assert isinstance(response, bindingmatchingresource.BindingMatchingResource) - assert response.name == "name_value" - assert response.resource == "resource_value" + 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__}<") -def test_get_binding_matching_resource_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. + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results + ) + + +def test_fetch_backup_plan_associations_for_resource_type_pages( + transport_name: str = "grpc", +): client = BackupDRClient( 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 = bindingmatchingresource.GetBindingMatchingResourceRequest( - name="name_value", + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_binding_matching_resource), "__call__" + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.get_binding_matching_resource(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest( - name="name_value", - ) - assert args[0] == request_msg - - -def test_get_binding_matching_resource_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 = BackupDRClient( - 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_binding_matching_resource - in client._transport._wrapped_methods + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, ) - - # 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. + pages = list( + client.fetch_backup_plan_associations_for_resource_type(request={}).pages ) - client._transport._wrapped_methods[ - client._transport.get_binding_matching_resource - ] = mock_rpc - request = {} - client.get_binding_matching_resource(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_binding_matching_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 + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_get_binding_matching_resource_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 = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport=transport, - ) +async def test_fetch_backup_plan_associations_for_resource_type_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_backup_plan_associations_for_resource_type( + 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, backupplanassociation.BackupPlanAssociation) + for i in responses + ) + + +@pytest.mark.asyncio +async def test_fetch_backup_plan_associations_for_resource_type_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.fetch_backup_plan_associations_for_resource_type(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", + [ + backupplanassociation.DeleteBackupPlanAssociationRequest(), + {}, + ], +) +def test_delete_backup_plan_association(request_type, transport: str = "grpc"): + client = BackupDRClient( + 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_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupplanassociation.DeleteBackupPlanAssociationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_backup_plan_association_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 = BackupDRClient( + 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 = backupplanassociation.DeleteBackupPlanAssociationRequest( + name="name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_backup_plan_association(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest( + name="name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + assert args[0] == request_msg + + +def test_delete_backup_plan_association_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 = BackupDRClient( + 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._client._transport.get_binding_matching_resource + client._transport.delete_backup_plan_association + 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_plan_association + ] = mock_rpc + request = {} + client.delete_backup_plan_association(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_plan_association(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_backup_plan_association_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 = BackupDRAsyncClient( + 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_plan_association in client._client._transport._wrapped_methods ) @@ -21229,16 +21848,21 @@ async def test_get_binding_matching_resource_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_binding_matching_resource + client._client._transport.delete_backup_plan_association ] = mock_rpc request = {} - await client.get_binding_matching_resource(request) + await client.delete_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_binding_matching_resource(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() + + await client.delete_backup_plan_association(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -21249,11 +21873,11 @@ async def test_get_binding_matching_resource_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bindingmatchingresource.GetBindingMatchingResourceRequest(), + backupplanassociation.DeleteBackupPlanAssociationRequest(), {}, ], ) -async def test_get_binding_matching_resource_async( +async def test_delete_backup_plan_association_async( request_type, transport: str = "grpc_asyncio" ): client = BackupDRAsyncClient( @@ -21267,46 +21891,41 @@ async def test_get_binding_matching_resource_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_binding_matching_resource), "__call__" + type(client.transport.delete_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bindingmatchingresource.BindingMatchingResource( - name="name_value", - resource="resource_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_binding_matching_resource(request) + response = await client.delete_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bindingmatchingresource.GetBindingMatchingResourceRequest() + request = backupplanassociation.DeleteBackupPlanAssociationRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, bindingmatchingresource.BindingMatchingResource) - assert response.name == "name_value" - assert response.resource == "resource_value" + assert isinstance(response, future.Future) -def test_get_binding_matching_resource_field_headers(): +def test_delete_backup_plan_association_field_headers(): client = BackupDRClient( 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 = bindingmatchingresource.GetBindingMatchingResourceRequest() + request = backupplanassociation.DeleteBackupPlanAssociationRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_binding_matching_resource), "__call__" + type(client.transport.delete_backup_plan_association), "__call__" ) as call: - call.return_value = bindingmatchingresource.BindingMatchingResource() - client.get_binding_matching_resource(request) + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -21322,25 +21941,25 @@ def test_get_binding_matching_resource_field_headers(): @pytest.mark.asyncio -async def test_get_binding_matching_resource_field_headers_async(): +async def test_delete_backup_plan_association_field_headers_async(): client = BackupDRAsyncClient( 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 = bindingmatchingresource.GetBindingMatchingResourceRequest() + request = backupplanassociation.DeleteBackupPlanAssociationRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_binding_matching_resource), "__call__" + type(client.transport.delete_backup_plan_association), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bindingmatchingresource.BindingMatchingResource() + operations_pb2.Operation(name="operations/op") ) - await client.get_binding_matching_resource(request) + await client.delete_backup_plan_association(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -21355,20 +21974,20 @@ async def test_get_binding_matching_resource_field_headers_async(): ) in kw["metadata"] -def test_get_binding_matching_resource_flattened(): +def test_delete_backup_plan_association_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_binding_matching_resource), "__call__" + type(client.transport.delete_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = bindingmatchingresource.BindingMatchingResource() + 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.get_binding_matching_resource( + client.delete_backup_plan_association( name="name_value", ) @@ -21381,7 +22000,7 @@ def test_get_binding_matching_resource_flattened(): assert arg == mock_val -def test_get_binding_matching_resource_flattened_error(): +def test_delete_backup_plan_association_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -21389,31 +22008,31 @@ def test_get_binding_matching_resource_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_binding_matching_resource( - bindingmatchingresource.GetBindingMatchingResourceRequest(), + client.delete_backup_plan_association( + backupplanassociation.DeleteBackupPlanAssociationRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_get_binding_matching_resource_flattened_async(): +async def test_delete_backup_plan_association_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_binding_matching_resource), "__call__" + type(client.transport.delete_backup_plan_association), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = bindingmatchingresource.BindingMatchingResource() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bindingmatchingresource.BindingMatchingResource() + 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.get_binding_matching_resource( + response = await client.delete_backup_plan_association( name="name_value", ) @@ -21427,7 +22046,7 @@ async def test_get_binding_matching_resource_flattened_async(): @pytest.mark.asyncio -async def test_get_binding_matching_resource_flattened_error_async(): +async def test_delete_backup_plan_association_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -21435,8 +22054,8 @@ async def test_get_binding_matching_resource_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.get_binding_matching_resource( - bindingmatchingresource.GetBindingMatchingResourceRequest(), + await client.delete_backup_plan_association( + backupplanassociation.DeleteBackupPlanAssociationRequest(), name="name_value", ) @@ -21444,11 +22063,11 @@ async def test_get_binding_matching_resource_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - bindingmatchingresource.ListBindingMatchingResourcesRequest(), + backupplanassociation.TriggerBackupRequest(), {}, ], ) -def test_list_binding_matching_resources(request_type, transport: str = "grpc"): +def test_trigger_backup(request_type, transport: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -21459,29 +22078,22 @@ def test_list_binding_matching_resources(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.list_binding_matching_resources), "__call__" - ) as call: + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse( - next_page_token="next_page_token_value", - ) - ) - response = client.list_binding_matching_resources(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.trigger_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + request = backupplanassociation.TriggerBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBindingMatchingResourcesPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_binding_matching_resources_non_empty_request_with_auto_populated_field(): +def test_trigger_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 = BackupDRClient( @@ -21492,33 +22104,27 @@ def test_list_binding_matching_resources_non_empty_request_with_auto_populated_f # 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = backupplanassociation.TriggerBackupRequest( + name="name_value", + rule_id="rule_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), "__call__" - ) as call: + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_binding_matching_resources(request=request) + client.trigger_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request_msg = backupplanassociation.TriggerBackupRequest( + name="name_value", + rule_id="rule_id_value", ) assert args[0] == request_msg -def test_list_binding_matching_resources_use_cached_wrapped_rpc(): +def test_trigger_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: @@ -21532,26 +22138,26 @@ def test_list_binding_matching_resources_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_binding_matching_resources - in client._transport._wrapped_methods - ) + assert client._transport.trigger_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.list_binding_matching_resources - ] = mock_rpc + client._transport._wrapped_methods[client._transport.trigger_backup] = mock_rpc request = {} - client.list_binding_matching_resources(request) + client.trigger_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_binding_matching_resources(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.trigger_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -21559,7 +22165,7 @@ def test_list_binding_matching_resources_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_binding_matching_resources_async_use_cached_wrapped_rpc( +async def test_trigger_backup_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -21576,7 +22182,7 @@ async def test_list_binding_matching_resources_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_binding_matching_resources + client._client._transport.trigger_backup in client._client._transport._wrapped_methods ) @@ -21584,16 +22190,21 @@ async def test_list_binding_matching_resources_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_binding_matching_resources + client._client._transport.trigger_backup ] = mock_rpc request = {} - await client.list_binding_matching_resources(request) + await client.trigger_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_binding_matching_resources(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() + + await client.trigger_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -21604,13 +22215,11 @@ async def test_list_binding_matching_resources_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - bindingmatchingresource.ListBindingMatchingResourcesRequest(), + backupplanassociation.TriggerBackupRequest(), {}, ], ) -async def test_list_binding_matching_resources_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_trigger_backup_async(request_type, transport: str = "grpc_asyncio"): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -21621,47 +22230,38 @@ async def test_list_binding_matching_resources_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), "__call__" - ) as call: + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bindingmatchingresource.ListBindingMatchingResourcesResponse( - next_page_token="next_page_token_value", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_binding_matching_resources(request) + response = await client.trigger_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + request = backupplanassociation.TriggerBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBindingMatchingResourcesAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, future.Future) -def test_list_binding_matching_resources_field_headers(): +def test_trigger_backup_field_headers(): client = BackupDRClient( 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest() + request = backupplanassociation.TriggerBackupRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), "__call__" - ) as call: - call.return_value = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse() - ) - client.list_binding_matching_resources(request) + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -21672,30 +22272,28 @@ def test_list_binding_matching_resources_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_binding_matching_resources_field_headers_async(): +async def test_trigger_backup_field_headers_async(): client = BackupDRAsyncClient( 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest() + request = backupplanassociation.TriggerBackupRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), "__call__" - ) as call: + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bindingmatchingresource.ListBindingMatchingResourcesResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_binding_matching_resources(request) + await client.trigger_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -21706,39 +22304,39 @@ async def test_list_binding_matching_resources_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_binding_matching_resources_flattened(): +def test_trigger_backup_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), "__call__" - ) as call: + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse() - ) + 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.list_binding_matching_resources( - parent="parent_value", + client.trigger_backup( + name="name_value", + rule_id="rule_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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].rule_id + mock_val = "rule_id_value" assert arg == mock_val -def test_list_binding_matching_resources_flattened_error(): +def test_trigger_backup_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -21746,47 +22344,48 @@ def test_list_binding_matching_resources_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_binding_matching_resources( - bindingmatchingresource.ListBindingMatchingResourcesRequest(), - parent="parent_value", + client.trigger_backup( + backupplanassociation.TriggerBackupRequest(), + name="name_value", + rule_id="rule_id_value", ) @pytest.mark.asyncio -async def test_list_binding_matching_resources_flattened_async(): +async def test_trigger_backup_flattened_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), "__call__" - ) as call: + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse() - ) + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bindingmatchingresource.ListBindingMatchingResourcesResponse() + 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.list_binding_matching_resources( - parent="parent_value", + response = await client.trigger_backup( + name="name_value", + rule_id="rule_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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].rule_id + mock_val = "rule_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_binding_matching_resources_flattened_error_async(): +async def test_trigger_backup_flattened_error_async(): client = BackupDRAsyncClient( credentials=async_anonymous_credentials(), ) @@ -21794,232 +22393,99 @@ async def test_list_binding_matching_resources_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.list_binding_matching_resources( - bindingmatchingresource.ListBindingMatchingResourcesRequest(), - parent="parent_value", + await client.trigger_backup( + backupplanassociation.TriggerBackupRequest(), + name="name_value", + rule_id="rule_id_value", ) -def test_list_binding_matching_resources_pager(transport_name: str = "grpc"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.GetDataSourceReferenceRequest(), + {}, + ], +) +def test_get_data_source_reference(request_type, transport: str = "grpc"): + client = BackupDRClient( + 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_binding_matching_resources), "__call__" + type(client.transport.get_data_source_reference), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - ], - next_page_token="abc", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[], - next_page_token="def", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - ], - next_page_token="ghi", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_binding_matching_resources( - request={}, retry=retry, timeout=timeout + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.DataSourceReference( + name="name_value", + data_source="data_source_value", + data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, + data_source_backup_count=2535, + total_stored_bytes=1946, ) + response = client.get_data_source_reference(request) - 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__}<") + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasourcereference.GetDataSourceReferenceRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, bindingmatchingresource.BindingMatchingResource) - for i in results - ) + # Establish that the response is the type that we expect. + assert isinstance(response, datasourcereference.DataSourceReference) + assert response.name == "name_value" + assert response.data_source == "data_source_value" + assert ( + response.data_source_backup_config_state == backupvault.BackupConfigState.ACTIVE + ) + assert response.data_source_backup_count == 2535 + assert response.total_stored_bytes == 1946 -def test_list_binding_matching_resources_pages(transport_name: str = "grpc"): +def test_get_data_source_reference_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - ], - next_page_token="abc", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[], - next_page_token="def", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - ], - next_page_token="ghi", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - ], - ), - RuntimeError, - ) - pages = list(client.list_binding_matching_resources(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_binding_matching_resources_async_pager(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), + # 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 = datasourcereference.GetDataSourceReferenceRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_binding_matching_resources), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.get_data_source_reference), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - ], - next_page_token="abc", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[], - next_page_token="def", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - ], - next_page_token="ghi", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_binding_matching_resources( - 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, bindingmatchingresource.BindingMatchingResource) - for i in responses + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -@pytest.mark.asyncio -async def test_list_binding_matching_resources_async_pages(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - ], - next_page_token="abc", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[], - next_page_token="def", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - ], - next_page_token="ghi", - ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - ], - ), - RuntimeError, + client.get_data_source_reference(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.GetDataSourceReferenceRequest( + name="name_value", ) - pages = [] - async for page_ in ( - await client.list_binding_matching_resources(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + assert args[0] == request_msg -def test_list_management_servers_rest_use_cached_wrapped_rpc(): +def test_get_data_source_reference_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -22028,7 +22494,7 @@ def test_list_management_servers_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_management_servers + client._transport.get_data_source_reference in client._transport._wrapped_methods ) @@ -22038,238 +22504,351 @@ def test_list_management_servers_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_management_servers + client._transport.get_data_source_reference ] = mock_rpc - request = {} - client.list_management_servers(request) + client.get_data_source_reference(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_management_servers(request) + client.get_data_source_reference(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_management_servers_rest_required_fields( - request_type=backupdr.ListManagementServersRequest, +@pytest.mark.asyncio +async def test_get_data_source_reference_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.get_data_source_reference + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseListManagementServers, - "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_data_source_reference + ] = mock_rpc + + request = {} + await client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_data_source_reference(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", + [ + datasourcereference.GetDataSourceReferenceRequest(), {}, + ], +) +async def test_get_data_source_reference_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.DataSourceReference( + name="name_value", + data_source="data_source_value", + data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, + data_source_backup_count=2535, + total_stored_bytes=1946, + ) ) + response = await client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasourcereference.GetDataSourceReferenceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, datasourcereference.DataSourceReference) + assert response.name == "name_value" + assert response.data_source == "data_source_value" + assert ( + response.data_source_backup_config_state == backupvault.BackupConfigState.ACTIVE ) + assert response.data_source_backup_count == 2535 + assert response.total_stored_bytes == 1946 - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_get_data_source_reference_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupdr.ListManagementServersResponse() - # 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 + # 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 = datasourcereference.GetDataSourceReferenceRequest() - # Convert return value to protobuf type - return_value = backupdr.ListManagementServersResponse.pb(return_value) - 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_data_source_reference), "__call__" + ) as call: + call.return_value = datasourcereference.DataSourceReference() + client.get_data_source_reference(request) - response = client.list_management_servers(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_list_management_servers_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_data_source_reference_field_headers_async(): + client = BackupDRAsyncClient( + 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 = backupdr.ListManagementServersResponse() + # 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 = datasourcereference.GetDataSourceReferenceRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.DataSourceReference() ) - mock_args.update(sample_request) + await client.get_data_source_reference(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 = backupdr.ListManagementServersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.list_management_servers(**mock_args) + # 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_data_source_reference_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.DataSourceReference() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_data_source_reference( + name="name_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/{parent=projects/*/locations/*}/managementServers" - % 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_list_management_servers_rest_flattened_error(transport: str = "rest"): +def test_get_data_source_reference_flattened_error(): client = BackupDRClient( 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_management_servers( - backupdr.ListManagementServersRequest(), - parent="parent_value", + client.get_data_source_reference( + datasourcereference.GetDataSourceReferenceRequest(), + name="name_value", ) -def test_list_management_servers_rest_pager(transport: str = "rest"): - client = BackupDRClient( +@pytest.mark.asyncio +async def test_get_data_source_reference_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.DataSourceReference() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.DataSourceReference() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_data_source_reference( + 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_data_source_reference_flattened_error_async(): + client = BackupDRAsyncClient( + 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_data_source_reference( + datasourcereference.GetDataSourceReferenceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.ListDataSourceReferencesRequest(), + {}, + ], +) +def test_list_data_source_references(request_type, transport: str = "grpc"): + client = BackupDRClient( 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 = ( - backupdr.ListManagementServersResponse( - management_servers=[ - backupdr.ManagementServer(), - backupdr.ManagementServer(), - backupdr.ManagementServer(), - ], - next_page_token="abc", - ), - backupdr.ListManagementServersResponse( - management_servers=[], - next_page_token="def", - ), - backupdr.ListManagementServersResponse( - management_servers=[ - backupdr.ManagementServer(), - ], - next_page_token="ghi", - ), - backupdr.ListManagementServersResponse( - management_servers=[ - backupdr.ManagementServer(), - backupdr.ManagementServer(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - backupdr.ListManagementServersResponse.to_json(x) for x in response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.ListDataSourceReferencesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 + response = client.list_data_source_references(request) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasourcereference.ListDataSourceReferencesRequest() + assert args[0] == request - pager = client.list_management_servers(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourceReferencesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - 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, backupdr.ManagementServer) for i in results) +def test_list_data_source_references_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_management_servers(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = datasourcereference.ListDataSourceReferencesRequest( + 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_data_source_references), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_data_source_references(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.ListDataSourceReferencesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg -def test_get_management_server_rest_use_cached_wrapped_rpc(): +def test_list_data_source_references_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -22278,7 +22857,7 @@ def test_get_management_server_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_management_server + client._transport.list_data_source_references in client._transport._wrapped_methods ) @@ -22287,366 +22866,561 @@ def test_get_management_server_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.get_management_server] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.list_data_source_references + ] = mock_rpc request = {} - client.get_management_server(request) + client.list_data_source_references(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_management_server(request) + client.list_data_source_references(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_management_server_rest_required_fields( - request_type=backupdr.GetManagementServerRequest, +@pytest.mark.asyncio +async def test_list_data_source_references_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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_data_source_references + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetManagementServer, - "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_data_source_references + ] = mock_rpc + + request = {} + await client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_data_source_references(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", + [ + datasourcereference.ListDataSourceReferencesRequest(), {}, + ], +) +async def test_list_data_source_references_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.ListDataSourceReferencesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_data_source_references(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasourcereference.ListDataSourceReferencesRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDataSourceReferencesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_data_source_references_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupdr.ManagementServer() - # 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 + # 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 = datasourcereference.ListDataSourceReferencesRequest() - # Convert return value to protobuf type - return_value = backupdr.ManagementServer.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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_data_source_references), "__call__" + ) as call: + call.return_value = datasourcereference.ListDataSourceReferencesResponse() + client.list_data_source_references(request) - response = client.get_management_server(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", + "parent=parent_value", + ) in kw["metadata"] -def test_get_management_server_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_data_source_references_field_headers_async(): + client = BackupDRAsyncClient( + 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 = backupdr.ManagementServer() + # 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 = datasourcereference.ListDataSourceReferencesRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/managementServers/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_data_source_references), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.ListDataSourceReferencesResponse() ) - mock_args.update(sample_request) + await client.list_data_source_references(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 = backupdr.ManagementServer.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_management_server(**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_data_source_references_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.ListDataSourceReferencesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_data_source_references( + 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/*/managementServers/*}" - % 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_management_server_rest_flattened_error(transport: str = "rest"): +def test_list_data_source_references_flattened_error(): client = BackupDRClient( 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_management_server( - backupdr.GetManagementServerRequest(), - name="name_value", + client.list_data_source_references( + datasourcereference.ListDataSourceReferencesRequest(), + parent="parent_value", ) -def test_create_management_server_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_list_data_source_references_flattened_async(): + client = BackupDRAsyncClient( + 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_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = datasourcereference.ListDataSourceReferencesResponse() - # Ensure method has been cached - assert ( - client._transport.create_management_server - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.ListDataSourceReferencesResponse() ) - - # 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_data_source_references( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.create_management_server - ] = mock_rpc - - request = {} - client.create_management_server(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() + # 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 - client.create_management_server(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_data_source_references_flattened_error_async(): + client = BackupDRAsyncClient( + 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_data_source_references( + datasourcereference.ListDataSourceReferencesRequest(), + parent="parent_value", + ) -def test_create_management_server_rest_required_fields( - request_type=backupdr.CreateManagementServerRequest, -): - transport_class = transports.BackupDRRestTransport - request_init = {} - request_init["parent"] = "" - request_init["management_server_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_data_source_references_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # verify fields with default values are dropped - assert "managementServerId" not in jsonified_request - - default_values = getattr( - transport_class._BaseCreateManagementServer, - "_BaseCreateManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.list_data_source_references), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) - # verify required fields with default values are now present - assert "managementServerId" in jsonified_request - assert ( - jsonified_request["managementServerId"] == request_init["management_server_id"] - ) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_data_source_references( + request={}, retry=retry, timeout=timeout + ) - jsonified_request["parent"] = "parent_value" - jsonified_request["managementServerId"] = "management_server_id_value" + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "managementServerId", - "requestId", + 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, datasourcereference.DataSourceReference) 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 "managementServerId" in jsonified_request - assert jsonified_request["managementServerId"] == "management_server_id_value" +def test_list_data_source_references_pages(transport_name: str = "grpc"): client = BackupDRClient( 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_data_source_references), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + pages = list(client.list_data_source_references(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_data_source_references_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - response = client.create_management_server(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_data_source_references( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - expected_params = [ - ( - "managementServerId", - "", - ), - ("$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, datasourcereference.DataSourceReference) for i in responses + ) -def test_create_management_server_rest_flattened(): +@pytest.mark.asyncio +async def test_list_data_source_references_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_data_source_references(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", + [ + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + {}, + ], +) +def test_fetch_data_source_references_for_resource_type( + request_type, transport: str = "grpc" +): client = BackupDRClient( 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", - management_server=backupdr.ManagementServer(name="name_value"), - management_server_id="management_server_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + next_page_token="next_page_token_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"} + response = client.fetch_data_source_references_for_resource_type(request) - client.create_management_server(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + 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/{parent=projects/*/locations/*}/managementServers" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchDataSourceReferencesForResourceTypePager) + assert response.next_page_token == "next_page_token_value" -def test_create_management_server_rest_flattened_error(transport: str = "rest"): +def test_fetch_data_source_references_for_resource_type_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 = BackupDRClient( 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_management_server( - backupdr.CreateManagementServerRequest(), - parent="parent_value", - management_server=backupdr.ManagementServer(name="name_value"), - management_server_id="management_server_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 = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_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.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_data_source_references_for_resource_type(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest( + parent="parent_value", + resource_type="resource_type_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) ) + assert args[0] == request_msg -def test_delete_management_server_rest_use_cached_wrapped_rpc(): +def test_fetch_data_source_references_for_resource_type_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -22655,7 +23429,7 @@ def test_delete_management_server_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_management_server + client._transport.fetch_data_source_references_for_resource_type in client._transport._wrapped_methods ) @@ -22665,865 +23439,576 @@ def test_delete_management_server_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_management_server + client._transport.fetch_data_source_references_for_resource_type ] = mock_rpc - request = {} - client.delete_management_server(request) + client.fetch_data_source_references_for_resource_type(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_management_server(request) + client.fetch_data_source_references_for_resource_type(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_management_server_rest_required_fields( - request_type=backupdr.DeleteManagementServerRequest, +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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.fetch_data_source_references_for_resource_type + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseDeleteManagementServer, - "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.fetch_data_source_references_for_resource_type + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.fetch_data_source_references_for_resource_type(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + await client.fetch_data_source_references_for_resource_type(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 = BackupDRClient( - 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 +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + {}, + ], +) +async def test_fetch_data_source_references_for_resource_type_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value = Response() - response_value.status_code = 200 - 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.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.fetch_data_source_references_for_resource_type(request) - response = client.delete_management_server(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + 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.FetchDataSourceReferencesForResourceTypeAsyncPager + ) + assert response.next_page_token == "next_page_token_value" -def test_delete_management_server_rest_flattened(): +def test_fetch_data_source_references_for_resource_type_field_headers(): client = BackupDRClient( 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/managementServers/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_management_server(**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/*/managementServers/*}" - % client.transport._host, - args[1], - ) - - -def test_delete_management_server_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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_management_server( - backupdr.DeleteManagementServerRequest(), - name="name_value", - ) - - -def test_create_backup_vault_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # 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 = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() - # Ensure method has been cached - assert ( - client._transport.create_backup_vault in client._transport._wrapped_methods - ) + request.parent = "parent_value" - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client._transport._wrapped_methods[client._transport.create_backup_vault] = ( - mock_rpc + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() ) - - request = {} - client.create_backup_vault(request) + client.fetch_data_source_references_for_resource_type(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_backup_vault(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_backup_vault_rest_required_fields( - request_type=backupvault.CreateBackupVaultRequest, -): - transport_class = transports.BackupDRRestTransport + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - request_init = {} - request_init["parent"] = "" - request_init["backup_vault_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) - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # verify fields with default values are dropped - assert "backupVaultId" not in jsonified_request - default_values = getattr( - transport_class._BaseCreateBackupVault, - "_BaseCreateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - assert "backupVaultId" in jsonified_request - assert jsonified_request["backupVaultId"] == request_init["backup_vault_id"] + # 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 = datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() - jsonified_request["parent"] = "parent_value" - jsonified_request["backupVaultId"] = "backup_vault_id_value" + request.parent = "parent_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "backupVaultId", - "requestId", - "validateOnly", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() ) - ) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "backupVaultId" in jsonified_request - assert jsonified_request["backupVaultId"] == "backup_vault_id_value" - - client = BackupDRClient( - 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"} + await client.fetch_data_source_references_for_resource_type(request) - response = client.create_backup_vault(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [ - ( - "backupVaultId", - "", - ), - ("$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", + "parent=parent_value", + ) in kw["metadata"] -def test_create_backup_vault_rest_flattened(): +def test_fetch_data_source_references_for_resource_type_flattened(): client = BackupDRClient( 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( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_data_source_references_for_resource_type( parent="parent_value", - backup_vault=backupvault.BackupVault(name="name_value"), - backup_vault_id="backup_vault_id_value", + resource_type="resource_type_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_backup_vault(**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/*}/backupVaults" - % 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 + arg = args[0].resource_type + mock_val = "resource_type_value" + assert arg == mock_val -def test_create_backup_vault_rest_flattened_error(transport: str = "rest"): +def test_fetch_data_source_references_for_resource_type_flattened_error(): client = BackupDRClient( 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_backup_vault( - backupvault.CreateBackupVaultRequest(), + client.fetch_data_source_references_for_resource_type( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), parent="parent_value", - backup_vault=backupvault.BackupVault(name="name_value"), - backup_vault_id="backup_vault_id_value", - ) - - -def test_list_backup_vaults_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 = BackupDRClient( - 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_vaults 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_vaults] = ( - mock_rpc + resource_type="resource_type_value", ) - request = {} - client.list_backup_vaults(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_backup_vaults(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_vaults_rest_required_fields( - request_type=backupvault.ListBackupVaultsRequest, -): - transport_class = transports.BackupDRRestTransport - - 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 - default_values = getattr( - transport_class._BaseListBackupVaults, - "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "view", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() ) - ) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupvault.ListBackupVaultsResponse() - # 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 = backupvault.ListBackupVaultsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._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_vaults(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_vaults_rest_flattened(): - client = BackupDRClient( - 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 = backupvault.ListBackupVaultsResponse() - - # 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( + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_data_source_references_for_resource_type( parent="parent_value", + resource_type="resource_type_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 = backupvault.ListBackupVaultsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_vaults(**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/*}/backupVaults" - % client.transport._host, - args[1], - ) + 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].resource_type + mock_val = "resource_type_value" + assert arg == mock_val -def test_list_backup_vaults_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backup_vaults( - backupvault.ListBackupVaultsRequest(), + await client.fetch_data_source_references_for_resource_type( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), parent="parent_value", + resource_type="resource_type_value", ) -def test_list_backup_vaults_rest_pager(transport: str = "rest"): +def test_fetch_data_source_references_for_resource_type_pager( + transport_name: str = "grpc", +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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 = ( - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), ], next_page_token="abc", ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[], + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], next_page_token="def", ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), ], next_page_token="ghi", ), - backupvault.ListBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - backupvault.ListBackupVaultsResponse.to_json(x) for x in response + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.fetch_data_source_references_for_resource_type( + request={}, retry=retry, timeout=timeout ) - 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_vaults(request=sample_request) + 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, backupvault.BackupVault) for i in results) - - pages = list(client.list_backup_vaults(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_fetch_usable_backup_vaults_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 = BackupDRClient( - 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.fetch_usable_backup_vaults - 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. + assert all( + isinstance(i, datasourcereference.DataSourceReference) for i in results ) - client._transport._wrapped_methods[ - client._transport.fetch_usable_backup_vaults - ] = mock_rpc - - request = {} - client.fetch_usable_backup_vaults(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_usable_backup_vaults(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_fetch_usable_backup_vaults_rest_required_fields( - request_type=backupvault.FetchUsableBackupVaultsRequest, +def test_fetch_data_source_references_for_resource_type_pages( + transport_name: str = "grpc", ): - transport_class = transports.BackupDRRestTransport - - 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 - - default_values = getattr( - transport_class._BaseFetchUsableBackupVaults, - "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupvault.FetchUsableBackupVaultsResponse() - # 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 = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._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.fetch_usable_backup_vaults(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, + ) + pages = list( + client.fetch_data_source_references_for_resource_type(request={}).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_fetch_usable_backup_vaults_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_async_pager(): + client = BackupDRAsyncClient( + 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 = backupvault.FetchUsableBackupVaultsResponse() - - # 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 the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + RuntimeError, ) - 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 = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.fetch_usable_backup_vaults(**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/*}/backupVaults:fetchUsable" - % client.transport._host, - args[1], + async_pager = await client.fetch_data_source_references_for_resource_type( + 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) -def test_fetch_usable_backup_vaults_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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.fetch_usable_backup_vaults( - backupvault.FetchUsableBackupVaultsRequest(), - parent="parent_value", + assert len(responses) == 6 + assert all( + isinstance(i, datasourcereference.DataSourceReference) for i in responses ) -def test_fetch_usable_backup_vaults_rest_pager(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_fetch_data_source_references_for_resource_type_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = ( - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), - backupvault.BackupVault(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), ], next_page_token="abc", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[], + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], next_page_token="def", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), ], next_page_token="ghi", ), - backupvault.FetchUsableBackupVaultsResponse( - backup_vaults=[ - backupvault.BackupVault(), - backupvault.BackupVault(), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response + pages = [] + async for page_ in ( + await client.fetch_data_source_references_for_resource_type(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # Wrap the values into proper Response objs - response = tuple( - backupvault.FetchUsableBackupVaultsResponse.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"} +@pytest.mark.parametrize( + "request_type", + [ + backupdr.InitializeServiceRequest(), + {}, + ], +) +def test_initialize_service(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - pager = client.fetch_usable_backup_vaults(request=sample_request) + # 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 - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.initialize_service(request) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, backupvault.BackupVault) for i in results) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = backupdr.InitializeServiceRequest() + assert args[0] == request - pages = list(client.fetch_usable_backup_vaults(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_get_backup_vault_rest_use_cached_wrapped_rpc(): +def test_initialize_service_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 = BackupDRClient( + 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 = backupdr.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + backup_plan_location="backup_plan_location_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.initialize_service(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest( + name="name_value", + resource_type="resource_type_value", + backup_plan_location="backup_plan_location_value", + ) + assert args[0] == request_msg + + +def test_initialize_service_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -23531,175 +24016,261 @@ def test_get_backup_vault_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup_vault in client._transport._wrapped_methods + assert ( + client._transport.initialize_service 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_vault] = ( + client._transport._wrapped_methods[client._transport.initialize_service] = ( mock_rpc ) - request = {} - client.get_backup_vault(request) + client.initialize_service(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup_vault(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.initialize_service(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_vault_rest_required_fields( - request_type=backupvault.GetBackupVaultRequest, +@pytest.mark.asyncio +async def test_initialize_service_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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.initialize_service + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetBackupVault, - "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.initialize_service + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.initialize_service(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + # 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() - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + await client.initialize_service(request) - client = BackupDRClient( - 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 = backupvault.BackupVault() - # 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", + [ + backupdr.InitializeServiceRequest(), + {}, + ], +) +async def test_initialize_service_async(request_type, transport: str = "grpc_asyncio"): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Convert return value to protobuf type - return_value = backupvault.BackupVault.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.initialize_service), "__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.initialize_service(request) - response = client.get_backup_vault(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = backupdr.InitializeServiceRequest() + 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, future.Future) -def test_get_backup_vault_rest_flattened(): +def test_initialize_service_field_headers(): client = BackupDRClient( 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 = backupvault.BackupVault() + # 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 = backupdr.InitializeServiceRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3" - } + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initialize_service(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 = backupvault.BackupVault.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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] + assert args[0] == request - client.get_backup_vault(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - # 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/*/backupVaults/*}" - % client.transport._host, - args[1], + +@pytest.mark.asyncio +async def test_initialize_service_field_headers_async(): + client = BackupDRAsyncClient( + 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 = backupdr.InitializeServiceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) + await client.initialize_service(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_backup_vault_rest_flattened_error(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + {}, + ], +) +def test_create_auto_protection_policy(request_type, transport: str = "grpc"): client = BackupDRClient( 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_vault( - backupvault.GetBackupVaultRequest(), - name="name_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 + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_auto_protection_policy_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 = BackupDRClient( + 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest( + parent="parent_value", + auto_protection_policy_id="auto_protection_policy_id_value", ) + assert args[0] == request_msg -def test_update_backup_vault_rest_use_cached_wrapped_rpc(): +def test_create_auto_protection_policy_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -23708,7 +24279,8 @@ def test_update_backup_vault_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_backup_vault in client._transport._wrapped_methods + client._transport.create_auto_protection_policy + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -23716,175 +24288,37 @@ def test_update_backup_vault_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_backup_vault] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.create_auto_protection_policy + ] = mock_rpc request = {} - client.update_backup_vault(request) + client.create_auto_protection_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 + # 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.update_backup_vault(request) + client.create_auto_protection_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_backup_vault_rest_required_fields( - request_type=backupvault.UpdateBackupVaultRequest, +@pytest.mark.asyncio +async def test_create_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport - - 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 - - default_values = getattr( - transport_class._BaseUpdateBackupVault, - "_BaseUpdateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "force", - "forceUpdateAccessRestriction", - "requestId", - "updateMask", - "validateOnly", - ) - ) - - # verify required fields with non-default values are left alone - - client = BackupDRClient( - 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_backup_vault(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_backup_vault_rest_flattened(): - client = BackupDRClient( - 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 = { - "backup_vault": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3" - } - } - - # get truthy value for each flattened field - mock_args = dict( - backup_vault=backupvault.BackupVault(name="name_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_backup_vault(**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/{backup_vault.name=projects/*/locations/*/backupVaults/*}" - % client.transport._host, - args[1], - ) - - -def test_update_backup_vault_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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_backup_vault( - backupvault.UpdateBackupVaultRequest(), - backup_vault=backupvault.BackupVault(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -def test_delete_backup_vault_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) # Should wrap all calls on client creation @@ -23893,435 +24327,338 @@ def test_delete_backup_vault_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_backup_vault in client._transport._wrapped_methods + client._client._transport.create_auto_protection_policy + in client._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_vault] = ( - mock_rpc - ) + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_auto_protection_policy + ] = mock_rpc request = {} - client.delete_backup_vault(request) + await client.create_auto_protection_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 + # 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_vault(request) + await client.create_auto_protection_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_delete_backup_vault_rest_required_fields( - request_type=backupvault.DeleteBackupVaultRequest, +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + {}, + ], +) +async def test_create_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" ): - transport_class = transports.BackupDRRestTransport - - 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) + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped - - default_values = getattr( - transport_class._BaseDeleteBackupVault, - "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + # 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 - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_auto_protection_policy(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + assert args[0] == request - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allowMissing", - "etag", - "force", - "ignoreBackupPlanReferences", - "requestId", - "validateOnly", - ) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_create_auto_protection_policy_field_headers(): client = BackupDRClient( 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 + # 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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.create_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy(request) - response = client.delete_backup_vault(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", + "parent=parent_value", + ) in kw["metadata"] -def test_delete_backup_vault_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_create_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupVaults/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.create_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - 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"} + await client.create_auto_protection_policy(request) - client.delete_backup_vault(**mock_args) + # 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 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/*/backupVaults/*}" - % client.transport._host, - args[1], - ) + # 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_delete_backup_vault_rest_flattened_error(transport: str = "rest"): +def test_create_auto_protection_policy_flattened(): client = BackupDRClient( 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_vault( - backupvault.DeleteBackupVaultRequest(), - name="name_value", - ) - - -def test_list_data_sources_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 = BackupDRClient( - 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_data_sources 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_data_sources] = ( - mock_rpc + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_auto_protection_policy( + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", ) - request = {} - client.list_data_sources(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_data_sources(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_data_sources_rest_required_fields( - request_type=backupvault.ListDataSourcesRequest, -): - transport_class = transports.BackupDRRestTransport - - 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 - - default_values = getattr( - transport_class._BaseListDataSources, - "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) + # 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].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") + assert arg == mock_val + arg = args[0].auto_protection_policy_id + mock_val = "auto_protection_policy_id_value" + assert arg == mock_val - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_create_auto_protection_policy_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupvault.ListDataSourcesResponse() - # 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 = backupvault.ListDataSourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._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_data_sources(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_auto_protection_policy( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) -def test_list_data_sources_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_create_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + 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 = backupvault.ListDataSourcesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3" - } + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # get truthy value for each flattened field - mock_args = dict( + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_auto_protection_policy( parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_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 = backupvault.ListDataSourcesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_data_sources(**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/*/backupVaults/*}/dataSources" - % client.transport._host, - args[1], - ) + 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].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(name="name_value") + assert arg == mock_val + arg = args[0].auto_protection_policy_id + mock_val = "auto_protection_policy_id_value" + assert arg == mock_val -def test_list_data_sources_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_create_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_data_sources( - backupvault.ListDataSourcesRequest(), + await client.create_auto_protection_policy( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", ) -def test_list_data_sources_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + {}, + ], +) +def test_list_auto_protection_policies(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = ( - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), - backupvault.DataSource(), - ], - next_page_token="abc", - ), - backupvault.ListDataSourcesResponse( - data_sources=[], - next_page_token="def", - ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - ], - next_page_token="ghi", - ), - backupvault.ListDataSourcesResponse( - data_sources=[ - backupvault.DataSource(), - backupvault.DataSource(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - backupvault.ListDataSourcesResponse.to_json(x) for x in response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 + response = client.list_auto_protection_policies(request) - sample_request = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3" - } + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + assert args[0] == request - pager = client.list_data_sources(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPoliciesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - 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, backupvault.DataSource) for i in results) +def test_list_auto_protection_policies_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_data_sources(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest( + 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_auto_protection_policies), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_auto_protection_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg -def test_get_data_source_rest_use_cached_wrapped_rpc(): +def test_list_auto_protection_policies_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -24329,611 +24666,563 @@ def test_get_data_source_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_data_source in client._transport._wrapped_methods + assert ( + client._transport.list_auto_protection_policies + 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_data_source] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.list_auto_protection_policies + ] = mock_rpc request = {} - client.get_data_source(request) + client.list_auto_protection_policies(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_data_source(request) + client.list_auto_protection_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_get_data_source_rest_required_fields( - request_type=backupvault.GetDataSourceRequest, +@pytest.mark.asyncio +async def test_list_auto_protection_policies_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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_auto_protection_policies + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetDataSource, - "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_auto_protection_policies + ] = mock_rpc + + request = {} + await client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_auto_protection_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), {}, + ], +) +async def test_list_auto_protection_policies_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_auto_protection_policies(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPoliciesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + +def test_list_auto_protection_policies_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupvault.DataSource() - # 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 + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() - # Convert return value to protobuf type - return_value = backupvault.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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_auto_protection_policies), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + client.list_auto_protection_policies(request) - response = client.get_data_source(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", + "parent=parent_value", + ) in kw["metadata"] -def test_get_data_source_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_auto_protection_policies_field_headers_async(): + client = BackupDRAsyncClient( + 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 = backupvault.DataSource() + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } + 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_auto_protection_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse() ) - mock_args.update(sample_request) + await client.list_auto_protection_policies(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 = backupvault.DataSource.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_data_source(**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_auto_protection_policies_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_auto_protection_policies( + 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/*/backupVaults/*/dataSources/*}" - % 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_data_source_rest_flattened_error(transport: str = "rest"): +def test_list_auto_protection_policies_flattened_error(): client = BackupDRClient( 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_data_source( - backupvault.GetDataSourceRequest(), - name="name_value", + client.list_auto_protection_policies( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + parent="parent_value", ) -def test_update_data_source_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 = BackupDRClient( - 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_auto_protection_policies_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.update_data_source 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_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() - # 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( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse() ) - client._transport._wrapped_methods[client._transport.update_data_source] = ( - mock_rpc + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_auto_protection_policies( + parent="parent_value", ) - request = {} - client.update_data_source(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_data_source(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_data_source_rest_required_fields( - request_type=backupvault.UpdateDataSourceRequest, -): - transport_class = transports.BackupDRRestTransport - - 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) - ) + # 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 - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseUpdateDataSource, - "_BaseUpdateDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_list_auto_protection_policies_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allowMissing", - "requestId", - "updateMask", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_auto_protection_policies( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + parent="parent_value", ) - ) - - # verify required fields with non-default values are left alone - - client = BackupDRClient( - 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_data_source(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_data_source_rest_flattened(): +def test_list_auto_protection_policies_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # 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 = { - "data_source": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } - } - - # get truthy value for each flattened field - mock_args = dict( - data_source=backupvault.DataSource( - data_source_gcp_resource=backupvault.DataSourceGcpResource( - compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( - name="name_value" - ) - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, ) - 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"} + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_auto_protection_policies( + request={}, retry=retry, timeout=timeout + ) - client.update_data_source(**mock_args) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - # 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/{data_source.name=projects/*/locations/*/backupVaults/*/dataSources/*}" - % client.transport._host, - args[1], + 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, autoprotectionpolicy.AutoProtectionPolicy) for i in results ) -def test_update_data_source_rest_flattened_error(transport: str = "rest"): +def test_list_auto_protection_policies_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_data_source( - backupvault.UpdateDataSourceRequest(), - data_source=backupvault.DataSource( - data_source_gcp_resource=backupvault.DataSourceGcpResource( - compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( - name="name_value" - ) - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, ) + pages = list(client.list_auto_protection_policies(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_list_auto_protection_policies_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # 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. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, ) - 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=backupvault.ListBackupsRequest): - transport_class = transports.BackupDRRestTransport - - 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 - - default_values = getattr( - transport_class._BaseListBackups, - "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present + async_pager = await client.list_auto_protection_policies( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - jsonified_request["parent"] = "parent_value" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "view", + assert len(responses) == 6 + assert all( + isinstance(i, autoprotectionpolicy.AutoProtectionPolicy) for i in responses ) - ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_auto_protection_policies_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupvault.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 = backupvault.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) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_auto_protection_policies(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_list_backups_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + {}, + ], +) +def test_get_auto_protection_policy(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = backupvault.ListBackupsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } + # 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", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.AutoProtectionPolicy( + name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_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 = backupvault.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.get_auto_protection_policy(request) - client.list_backups(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + 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/{parent=projects/*/locations/*/backupVaults/*/dataSources/*}/backups" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicy.AutoProtectionPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING + assert response.etag == "etag_value" -def test_list_backups_rest_flattened_error(transport: str = "rest"): +def test_get_auto_protection_policy_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 = BackupDRClient( 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.list_backups( - backupvault.ListBackupsRequest(), - parent="parent_value", - ) - - -def test_list_backups_rest_pager(transport: str = "rest"): - client = BackupDRClient( - 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 = autoprotectionpolicy.GetAutoProtectionPolicyRequest( + name="name_value", ) - # 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 = ( - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), - ], - next_page_token="abc", - ), - backupvault.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - ], - next_page_token="ghi", - ), - backupvault.ListBackupsResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - ], - ), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(backupvault.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/backupVaults/sample3/dataSources/sample4" - } - - 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, backupvault.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 + client.get_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest( + name="name_value", + ) + assert args[0] == request_msg -def test_fetch_backups_for_resource_type_rest_use_cached_wrapped_rpc(): +def test_get_auto_protection_policy_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -24942,7 +25231,7 @@ def test_fetch_backups_for_resource_type_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_backups_for_resource_type + client._transport.get_auto_protection_policy in client._transport._wrapped_methods ) @@ -24952,263 +25241,332 @@ def test_fetch_backups_for_resource_type_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_backups_for_resource_type + client._transport.get_auto_protection_policy ] = mock_rpc - request = {} - client.fetch_backups_for_resource_type(request) + client.get_auto_protection_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_backups_for_resource_type(request) + client.get_auto_protection_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_fetch_backups_for_resource_type_rest_required_fields( - request_type=backupvault.FetchBackupsForResourceTypeRequest, +@pytest.mark.asyncio +async def test_get_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["resource_type"] = "" - 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 - assert "resourceType" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.get_auto_protection_policy + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseFetchBackupsForResourceType, - "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_auto_protection_policy + ] = mock_rpc + + request = {} + await client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_auto_protection_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), {}, + ], +) +async def test_get_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == request_init["resource_type"] - jsonified_request["parent"] = "parent_value" - jsonified_request["resourceType"] = "resource_type_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "resourceType", - "view", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy( + name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_value", + ) ) - ) + response = await client.get_auto_protection_policy(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == "resource_type_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicy.AutoProtectionPolicy) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.state == autoprotectionpolicy.AutoProtectionPolicy.State.CREATING + assert response.etag == "etag_value" + +def test_get_auto_protection_policy_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupvault.FetchBackupsForResourceTypeResponse() - # 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 + # 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 = autoprotectionpolicy.GetAutoProtectionPolicyRequest() - response_value = Response() - response_value.status_code = 200 + request.name = "name_value" - # Convert return value to protobuf type - return_value = backupvault.FetchBackupsForResourceTypeResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + client.get_auto_protection_policy(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.fetch_backups_for_resource_type(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - expected_params = [ - ( - "resourceType", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_get_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_fetch_backups_for_resource_type_rest_flattened(): + # 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 = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy() + ) + await client.get_auto_protection_policy(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_auto_protection_policy_flattened(): client = BackupDRClient( 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 = backupvault.FetchBackupsForResourceTypeResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_auto_protection_policy( + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } + # 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 - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - resource_type="resource_type_value", + +def test_get_auto_protection_policy_flattened_error(): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + 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 = backupvault.FetchBackupsForResourceTypeResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.fetch_backups_for_resource_type(**mock_args) +@pytest.mark.asyncio +async def test_get_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_auto_protection_policy( + name="name_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/{parent=projects/*/locations/*/backupVaults/*/dataSources/*}/backups:fetchForResourceType" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_fetch_backups_for_resource_type_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_get_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_backups_for_resource_type( - backupvault.FetchBackupsForResourceTypeRequest(), - parent="parent_value", - resource_type="resource_type_value", + await client.get_auto_protection_policy( + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + name="name_value", ) -def test_fetch_backups_for_resource_type_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + {}, + ], +) +def test_update_auto_protection_policy(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = ( - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - backupvault.Backup(), - ], - next_page_token="abc", - ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[], - next_page_token="def", - ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - ], - next_page_token="ghi", - ), - backupvault.FetchBackupsForResourceTypeResponse( - backups=[ - backupvault.Backup(), - backupvault.Backup(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - backupvault.FetchBackupsForResourceTypeResponse.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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_auto_protection_policy(request) - sample_request = { - "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" - } + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request - pager = client.fetch_backups_for_resource_type(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - 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, backupvault.Backup) for i in results) +def test_update_auto_protection_policy_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list( - client.fetch_backups_for_resource_type(request=sample_request).pages + # 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 = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.update_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + assert args[0] == request_msg -def test_get_backup_rest_use_cached_wrapped_rpc(): +def test_update_auto_protection_policy_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -25216,357 +25574,368 @@ def test_get_backup_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup in client._transport._wrapped_methods + assert ( + client._transport.update_auto_protection_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_backup] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.update_auto_protection_policy + ] = mock_rpc request = {} - client.get_backup(request) + client.update_auto_protection_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup(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.update_auto_protection_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_backup_rest_required_fields(request_type=backupvault.GetBackupRequest): - transport_class = transports.BackupDRRestTransport +@pytest.mark.asyncio +async def test_update_auto_protection_policy_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 = BackupDRAsyncClient( + 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.update_auto_protection_policy + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetBackup, - "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.update_auto_protection_policy + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.update_auto_protection_policy(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + # 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() - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + await client.update_auto_protection_policy(request) - client = BackupDRClient( - 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 = backupvault.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 +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + {}, + ], +) +async def test_update_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Convert return value to protobuf type - return_value = backupvault.Backup.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.update_auto_protection_policy), "__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.update_auto_protection_policy(request) - response = client.get_backup(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + 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, future.Future) -def test_get_backup_rest_flattened(): +def test_update_auto_protection_policy_field_headers(): client = BackupDRClient( 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 = backupvault.Backup() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" - } + # 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 = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + request.auto_protection_policy.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 = backupvault.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"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_auto_protection_policy(request) - client.get_backup(**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 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/*/backupVaults/*/dataSources/*/backups/*}" - % client.transport._host, - args[1], - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "auto_protection_policy.name=name_value", + ) in kw["metadata"] -def test_get_backup_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_update_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_backup( - backupvault.GetBackupRequest(), - name="name_value", - ) - + # 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 = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() -def test_update_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + request.auto_protection_policy.name = "name_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.update_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. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - client._transport._wrapped_methods[client._transport.update_backup] = mock_rpc - - request = {} - client.update_backup(request) + await client.update_auto_protection_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() + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.update_backup(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "auto_protection_policy.name=name_value", + ) in kw["metadata"] - # 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_auto_protection_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) -def test_update_backup_rest_required_fields( - request_type=backupvault.UpdateBackupRequest, -): - transport_class = transports.BackupDRRestTransport + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__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.update_auto_protection_policy( + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - 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) - ) + # 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].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(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 - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseUpdateBackup, - "_BaseUpdateBackup__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +def test_update_auto_protection_policy_flattened_error(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_auto_protection_policy( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - ) - # verify required fields with non-default values are left alone - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_update_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + 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.update_auto_protection_policy( + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - response_value._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 call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].auto_protection_policy + mock_val = autoprotectionpolicy.AutoProtectionPolicy(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 - response = client.update_backup(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_update_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + 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_auto_protection_policy( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) -def test_update_backup_rest_flattened(): + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + {}, + ], +) +def test_delete_auto_protection_policy(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = { - "backup": { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" - } - } - - # get truthy value for each flattened field - mock_args = dict( - backup=backupvault.Backup( - compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( - description="description_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - mock_args.update(sample_request) + # 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 - # 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"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_auto_protection_policy(request) - client.update_backup(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + 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/{backup.name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_update_backup_rest_flattened_error(transport: str = "rest"): +def test_delete_auto_protection_policy_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 = BackupDRClient( 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.update_backup( - backupvault.UpdateBackupRequest(), - backup=backupvault.Backup( - compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( - description="description_value" - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest( + name="name_value", + etag="etag_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_auto_protection_policy(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest( + name="name_value", + etag="etag_value", ) + assert args[0] == request_msg -def test_delete_backup_rest_use_cached_wrapped_rpc(): +def test_delete_auto_protection_policy_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -25574,172 +25943,47 @@ def test_delete_backup_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_backup in client._transport._wrapped_methods + assert ( + client._transport.delete_auto_protection_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.delete_backup] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.delete_auto_protection_policy + ] = mock_rpc request = {} - client.delete_backup(request) + client.delete_auto_protection_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 + # 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) + client.delete_auto_protection_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_delete_backup_rest_required_fields( - request_type=backupvault.DeleteBackupRequest, +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport - - 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 - - default_values = getattr( - transport_class._BaseDeleteBackup, - "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - - client = BackupDRClient( - 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_flattened(): - client = BackupDRClient( - 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/backupVaults/sample3/dataSources/sample4/backups/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_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/*/backupVaults/*/dataSources/*/backups/*}" - % client.transport._host, - args[1], - ) - - -def test_delete_backup_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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( - backupvault.DeleteBackupRequest(), - name="name_value", - ) - - -def test_restore_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) # Should wrap all calls on client creation @@ -25747,376 +25991,302 @@ def test_restore_backup_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.restore_backup in client._transport._wrapped_methods + assert ( + client._client._transport.delete_auto_protection_policy + in client._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.restore_backup] = mock_rpc + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_auto_protection_policy + ] = mock_rpc request = {} - client.restore_backup(request) + await client.delete_auto_protection_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 + # 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.restore_backup(request) + await client.delete_auto_protection_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_restore_backup_rest_required_fields( - request_type=backupvault.RestoreBackupRequest, +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + {}, + ], +) +async def test_delete_auto_protection_policy_async( + request_type, transport: str = "grpc_asyncio" ): - transport_class = transports.BackupDRRestTransport - - 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) + client = BackupDRAsyncClient( + 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 - default_values = getattr( - transport_class._BaseRestoreBackup, - "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.delete_auto_protection_policy), "__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_auto_protection_policy(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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + assert args[0] == request - jsonified_request["name"] = "name_value" + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_delete_auto_protection_policy_field_headers(): client = BackupDRClient( 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 + # 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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() - 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.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_auto_protection_policy(request) - response = client.restore_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 - 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_restore_backup_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" - } + request.name = "name_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.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.delete_auto_protection_policy(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.restore_backup(**mock_args) + # 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_auto_protection_policy_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__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_auto_protection_policy( + name="name_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/*/backupVaults/*/dataSources/*/backups/*}:restore" - % 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_restore_backup_rest_flattened_error(transport: str = "rest"): +def test_delete_auto_protection_policy_flattened_error(): client = BackupDRClient( 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.restore_backup( - backupvault.RestoreBackupRequest(), + client.delete_auto_protection_policy( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), name="name_value", ) -def test_create_backup_plan_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 = BackupDRClient( - 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_delete_auto_protection_policy_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.create_backup_plan in client._transport._wrapped_methods - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # 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( + operations_pb2.Operation(name="operations/spam") ) - client._transport._wrapped_methods[client._transport.create_backup_plan] = ( - mock_rpc + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_auto_protection_policy( + name="name_value", ) - request = {} - client.create_backup_plan(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_backup_plan(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_backup_plan_rest_required_fields( - request_type=backupplan.CreateBackupPlanRequest, -): - transport_class = transports.BackupDRRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["backup_plan_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) - ) + # 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 - # verify fields with default values are dropped - assert "backupPlanId" not in jsonified_request - default_values = getattr( - transport_class._BaseCreateBackupPlan, - "_BaseCreateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_delete_auto_protection_policy_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - assert "backupPlanId" in jsonified_request - assert jsonified_request["backupPlanId"] == request_init["backup_plan_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["backupPlanId"] = "backup_plan_id_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "backupPlanId", - "requestId", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_auto_protection_policy( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + name="name_value", ) - ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "backupPlanId" in jsonified_request - assert jsonified_request["backupPlanId"] == "backup_plan_id_value" +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + {}, + ], +) +def test_create_auto_protection_policy_binding(request_type, transport: str = "grpc"): client = BackupDRClient( 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": "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) + # 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.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_auto_protection_policy_binding(request) - response = client.create_backup_plan(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + assert args[0] == request - expected_params = [ - ( - "backupPlanId", - "", - ), - ("$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, future.Future) -def test_create_backup_plan_rest_flattened(): +def test_create_auto_protection_policy_binding_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 = BackupDRClient( 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 = {"parent": "projects/sample1/locations/sample2"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - backup_plan_id="backup_plan_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_backup_plan(**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/*}/backupPlans" - % client.transport._host, - args[1], - ) - - -def test_create_backup_plan_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( + parent="parent_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_backup_plan( - backupplan.CreateBackupPlanRequest(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_auto_protection_policy_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest( parent="parent_value", - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - backup_plan_id="backup_plan_id_value", + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", ) + assert args[0] == request_msg -def test_update_backup_plan_rest_use_cached_wrapped_rpc(): +def test_create_auto_protection_policy_binding_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -26125,7 +26295,8 @@ def test_update_backup_plan_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_backup_plan in client._transport._wrapped_methods + client._transport.create_auto_protection_policy_binding + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -26133,351 +26304,384 @@ def test_update_backup_plan_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_backup_plan] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.create_auto_protection_policy_binding + ] = mock_rpc request = {} - client.update_backup_plan(request) + client.create_auto_protection_policy_binding(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 + # 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.update_backup_plan(request) + client.create_auto_protection_policy_binding(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_backup_plan_rest_required_fields( - request_type=backupplan.UpdateBackupPlanRequest, +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.create_auto_protection_policy_binding + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseUpdateBackupPlan, - "_BaseUpdateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.create_auto_protection_policy_binding + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.create_auto_protection_policy_binding(request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", - ) - ) + # 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 + # 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 = BackupDRClient( - 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_backup_plan(request) + await client.create_auto_protection_policy_binding(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_update_backup_plan_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + {}, + ], +) +async def test_create_auto_protection_policy_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + 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 = { - "backup_plan": { - "name": "projects/sample1/locations/sample2/backupPlans/sample3" - } - } + # 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( - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - 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.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - 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"} + response = await client.create_auto_protection_policy_binding(request) - client.update_backup_plan(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + 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/{backup_plan.name=projects/*/locations/*/backupPlans/*}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_update_backup_plan_rest_flattened_error(transport: str = "rest"): +def test_create_auto_protection_policy_binding_field_headers(): client = BackupDRClient( 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_backup_plan( - backupplan.UpdateBackupPlanRequest(), - backup_plan=backupplan.BackupPlan( - disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( - guest_flush=True - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - + # 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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() -def test_get_backup_plan_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + request.parent = "parent_value" - # 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.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy_binding(request) - # Ensure method has been cached - assert client._transport.get_backup_plan in client._transport._wrapped_methods + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - # 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_plan] = mock_rpc + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - request = {} - client.get_backup_plan(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - client.get_backup_plan(request) + # 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 = autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + request.parent = "parent_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_auto_protection_policy_binding(request) -def test_get_backup_plan_rest_required_fields( - request_type=backupplan.GetBackupPlanRequest, -): - transport_class = transports.BackupDRRestTransport + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - 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) - ) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseGetBackupPlan, - "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +def test_create_auto_protection_policy_binding_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_auto_protection_policy_binding( + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) - jsonified_request["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].auto_protection_policy_binding + mock_val = autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ) + assert arg == mock_val + arg = args[0].auto_protection_policy_binding_id + mock_val = "auto_protection_policy_binding_id_value" + assert arg == mock_val - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_create_auto_protection_policy_binding_flattened_error(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupplan.BackupPlan() - # 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 + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_auto_protection_policy_binding( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = backupplan.BackupPlan.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_flattened_async(): + client = BackupDRAsyncClient( + 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.create_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - response = client.get_backup_plan(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_auto_protection_policy_binding( + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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].auto_protection_policy_binding + mock_val = autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ) + assert arg == mock_val + arg = args[0].auto_protection_policy_binding_id + mock_val = "auto_protection_policy_binding_id_value" + assert arg == mock_val -def test_get_backup_plan_rest_flattened(): +@pytest.mark.asyncio +async def test_create_auto_protection_policy_binding_flattened_error_async(): + client = BackupDRAsyncClient( + 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_auto_protection_policy_binding( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + {}, + ], +) +def test_get_auto_protection_policy_binding(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = backupplan.BackupPlan() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlans/sample3" - } + # 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_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding( name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_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 = backupplan.BackupPlan.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_auto_protection_policy_binding(request) - client.get_backup_plan(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + 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/*/backupPlans/*}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING + ) + assert response.scope == "scope_value" + assert response.etag == "etag_value" -def test_get_backup_plan_rest_flattened_error(transport: str = "rest"): +def test_get_auto_protection_policy_binding_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 = BackupDRClient( 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_backup_plan( - backupplan.GetBackupPlanRequest(), + # 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 = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_auto_protection_policy_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest( name="name_value", ) + assert args[0] == request_msg -def test_list_backup_plans_rest_use_cached_wrapped_rpc(): +def test_get_auto_protection_policy_binding_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -26485,246 +26689,367 @@ def test_list_backup_plans_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_backup_plans in client._transport._wrapped_methods + assert ( + client._transport.get_auto_protection_policy_binding + 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_plans] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.get_auto_protection_policy_binding + ] = mock_rpc request = {} - client.list_backup_plans(request) + client.get_auto_protection_policy_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backup_plans(request) + client.get_auto_protection_policy_binding(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_plans_rest_required_fields( - request_type=backupplan.ListBackupPlansRequest, +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.get_auto_protection_policy_binding + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseListBackupPlans, - "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_auto_protection_policy_binding + ] = mock_rpc + + request = {} + await client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_auto_protection_policy_binding(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", + [ + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), {}, + ], +) +async def test_get_auto_protection_policy_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_value", + ) ) + response = await client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING ) + assert response.scope == "scope_value" + assert response.etag == "etag_value" - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" +def test_get_auto_protection_policy_binding_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = backupplan.ListBackupPlansResponse() - # 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 + # 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 = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() - response_value = Response() - response_value.status_code = 200 + request.name = "name_value" - # Convert return value to protobuf type - return_value = backupplan.ListBackupPlansResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + client.get_auto_protection_policy_binding(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.list_backup_plans(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_field_headers_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_list_backup_plans_rest_flattened(): + # 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 = autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding() + ) + await client.get_auto_protection_policy_binding(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_auto_protection_policy_binding_flattened(): client = BackupDRClient( 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 = backupplan.ListBackupPlansResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_auto_protection_policy_binding( + name="name_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # 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 - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + +def test_get_auto_protection_policy_binding_flattened_error(): + client = BackupDRClient( + 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_auto_protection_policy_binding( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + 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 = backupplan.ListBackupPlansResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_plans(**mock_args) +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_auto_protection_policy_binding( + name="name_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/{parent=projects/*/locations/*}/backupPlans" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_list_backup_plans_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_get_auto_protection_policy_binding_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backup_plans( - backupplan.ListBackupPlansRequest(), - parent="parent_value", + await client.get_auto_protection_policy_binding( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + name="name_value", ) -def test_list_backup_plans_rest_pager(transport: str = "rest"): +@pytest.mark.parametrize( + "request_type", + [ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + {}, + ], +) +def test_list_auto_protection_policy_bindings(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = ( - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), - backupplan.BackupPlan(), - ], - next_page_token="abc", - ), - backupplan.ListBackupPlansResponse( - backup_plans=[], - next_page_token="def", - ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - ], - next_page_token="ghi", - ), - backupplan.ListBackupPlansResponse( - backup_plans=[ - backupplan.BackupPlan(), - backupplan.BackupPlan(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - backupplan.ListBackupPlansResponse.to_json(x) for x in response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 + response = client.list_auto_protection_policy_bindings(request) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + assert args[0] == request - pager = client.list_backup_plans(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - 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, backupplan.BackupPlan) for i in results) +def test_list_auto_protection_policy_bindings_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_backup_plans(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + 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_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_auto_protection_policy_bindings(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + ) + assert args[0] == request_msg -def test_delete_backup_plan_rest_use_cached_wrapped_rpc(): +def test_list_auto_protection_policy_bindings_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -26733,7 +27058,8 @@ def test_delete_backup_plan_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_backup_plan in client._transport._wrapped_methods + client._transport.list_auto_protection_policy_bindings + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -26741,595 +27067,567 @@ def test_delete_backup_plan_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.delete_backup_plan] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.list_auto_protection_policy_bindings + ] = mock_rpc request = {} - client.delete_backup_plan(request) + client.list_auto_protection_policy_bindings(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_plan(request) + client.list_auto_protection_policy_bindings(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_plan_rest_required_fields( - request_type=backupplan.DeleteBackupPlanRequest, +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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_auto_protection_policy_bindings + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseDeleteBackupPlan, - "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_auto_protection_policy_bindings + ] = mock_rpc + + request = {} + await client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_auto_protection_policy_bindings(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", + [ + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), {}, + ], +) +async def test_list_auto_protection_policy_bindings_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_auto_protection_policy_bindings(request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("requestId",)) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAutoProtectionPolicyBindingsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_list_auto_protection_policy_bindings_field_headers(): client = BackupDRClient( 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 + # 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + client.list_auto_protection_policy_bindings(request) - response = client.delete_backup_plan(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", + "parent=parent_value", + ) in kw["metadata"] -def test_delete_backup_plan_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlans/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_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() ) - mock_args.update(sample_request) + await client.list_auto_protection_policy_bindings(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_backup_plan(**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_auto_protection_policy_bindings_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_auto_protection_policy_bindings( + 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/*/backupPlans/*}" - % 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_delete_backup_plan_rest_flattened_error(transport: str = "rest"): +def test_list_auto_protection_policy_bindings_flattened_error(): client = BackupDRClient( 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_plan( - backupplan.DeleteBackupPlanRequest(), - name="name_value", + client.list_auto_protection_policy_bindings( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + parent="parent_value", ) -def test_get_backup_plan_revision_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 = BackupDRClient( - 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_auto_protection_policy_bindings_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.get_backup_plan_revision - 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_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() ) - # 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( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_auto_protection_policy_bindings( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.get_backup_plan_revision - ] = mock_rpc - - request = {} - client.get_backup_plan_revision(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_backup_plan_revision(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_plan_revision_rest_required_fields( - request_type=backupplan.GetBackupPlanRevisionRequest, -): - transport_class = transports.BackupDRRestTransport - - 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 - - default_values = getattr( - transport_class._BaseGetBackupPlanRevision, - "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["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 - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupplan.BackupPlanRevision() - # 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 = backupplan.BackupPlanRevision.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._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_plan_revision(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_auto_protection_policy_bindings( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + parent="parent_value", + ) -def test_get_backup_plan_revision_rest_flattened(): +def test_list_auto_protection_policy_bindings_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # 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 = backupplan.BackupPlanRevision() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/sample4" - } + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, + ) - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_auto_protection_policy_bindings( + request={}, retry=retry, timeout=timeout ) - 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 = backupplan.BackupPlanRevision.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - client.get_backup_plan_revision(**mock_args) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # 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/*/backupPlans/*/revisions/*}" - % client.transport._host, - args[1], + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + for i in results ) -def test_get_backup_plan_revision_rest_flattened_error(transport: str = "rest"): +def test_list_auto_protection_policy_bindings_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_backup_plan_revision( - backupplan.GetBackupPlanRevisionRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, ) + pages = list(client.list_auto_protection_policy_bindings(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_list_backup_plan_revisions_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 = BackupDRClient( - 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_auto_protection_policy_bindings_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.list_backup_plan_revisions - 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_auto_protection_policy_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, ) - - # 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. + async_pager = await client.list_auto_protection_policy_bindings( + request={}, ) - client._transport._wrapped_methods[ - client._transport.list_backup_plan_revisions - ] = mock_rpc - - request = {} - client.list_backup_plan_revisions(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.list_backup_plan_revisions(request) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + assert len(responses) == 6 + assert all( + isinstance(i, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + for i in responses + ) -def test_list_backup_plan_revisions_rest_required_fields( - request_type=backupplan.ListBackupPlanRevisionsRequest, -): - transport_class = transports.BackupDRRestTransport - 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) +@pytest.mark.asyncio +async def test_list_auto_protection_policy_bindings_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped - - default_values = getattr( - transport_class._BaseListBackupPlanRevisions, - "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + RuntimeError, ) - ) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupplan.ListBackupPlanRevisionsResponse() - # 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 = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._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_plan_revisions(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + pages = [] + async for page_ in ( + await client.list_auto_protection_policy_bindings(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_list_backup_plan_revisions_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + {}, + ], +) +def test_list_applied_auto_protection_policies(request_type, transport: str = "grpc"): client = BackupDRClient( 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 = backupplan.ListBackupPlanRevisionsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/backupPlans/sample3" - } + # 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", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_applied_auto_protection_policies(request) - client.list_backup_plan_revisions(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + 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/{parent=projects/*/locations/*/backupPlans/*}/revisions" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppliedAutoProtectionPoliciesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_list_backup_plan_revisions_rest_flattened_error(transport: str = "rest"): +def test_list_applied_auto_protection_policies_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 = BackupDRClient( 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.list_backup_plan_revisions( - backupplan.ListBackupPlanRevisionsRequest(), - parent="parent_value", - ) - - -def test_list_backup_plan_revisions_rest_pager(transport: str = "rest"): - client = BackupDRClient( - 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) - # 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 = ( - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - next_page_token="abc", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[], - next_page_token="def", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - ], - next_page_token="ghi", - ), - backupplan.ListBackupPlanRevisionsResponse( - backup_plan_revisions=[ - backupplan.BackupPlanRevision(), - backupplan.BackupPlanRevision(), - ], - ), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - backupplan.ListBackupPlanRevisionsResponse.to_json(x) for x in response + client.list_applied_auto_protection_policies(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_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/backupPlans/sample3" - } - - pager = client.list_backup_plan_revisions(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, backupplan.BackupPlanRevision) for i in results) - - pages = list(client.list_backup_plan_revisions(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + assert args[0] == request_msg -def test_create_backup_plan_association_rest_use_cached_wrapped_rpc(): +def test_list_applied_auto_protection_policies_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -27338,7 +27636,7 @@ def test_create_backup_plan_association_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_backup_plan_association + client._transport.list_applied_auto_protection_policies in client._transport._wrapped_methods ) @@ -27348,201 +27646,31 @@ def test_create_backup_plan_association_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_backup_plan_association + client._transport.list_applied_auto_protection_policies ] = mock_rpc - request = {} - client.create_backup_plan_association(request) + client.list_applied_auto_protection_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.create_backup_plan_association(request) + client.list_applied_auto_protection_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_create_backup_plan_association_rest_required_fields( - request_type=backupplanassociation.CreateBackupPlanAssociationRequest, +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["backup_plan_association_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 "backupPlanAssociationId" not in jsonified_request - - default_values = getattr( - transport_class._BaseCreateBackupPlanAssociation, - "_BaseCreateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "backupPlanAssociationId" in jsonified_request - assert ( - jsonified_request["backupPlanAssociationId"] - == request_init["backup_plan_association_id"] - ) - - jsonified_request["parent"] = "parent_value" - jsonified_request["backupPlanAssociationId"] = "backup_plan_association_id_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "backupPlanAssociationId", - "requestId", - ) - ) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "backupPlanAssociationId" in jsonified_request - assert ( - jsonified_request["backupPlanAssociationId"] - == "backup_plan_association_id_value" - ) - - client = BackupDRClient( - 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_backup_plan_association(request) - - expected_params = [ - ( - "backupPlanAssociationId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) - - -def test_create_backup_plan_association_rest_flattened(): - client = BackupDRClient( - 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", - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - backup_plan_association_id="backup_plan_association_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_backup_plan_association(**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/*}/backupPlanAssociations" - % client.transport._host, - args[1], - ) - - -def test_create_backup_plan_association_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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_backup_plan_association( - backupplanassociation.CreateBackupPlanAssociationRequest(), - parent="parent_value", - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - backup_plan_association_id="backup_plan_association_id_value", - ) - - -def test_update_backup_plan_association_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) # Should wrap all calls on client creation @@ -27551,365 +27679,526 @@ def test_update_backup_plan_association_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_backup_plan_association - in client._transport._wrapped_methods + client._client._transport.list_applied_auto_protection_policies + in client._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_backup_plan_association + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_applied_auto_protection_policies ] = mock_rpc request = {} - client.update_backup_plan_association(request) + await client.list_applied_auto_protection_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.update_backup_plan_association(request) + await client.list_applied_auto_protection_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_update_backup_plan_association_rest_required_fields( - request_type=backupplanassociation.UpdateBackupPlanAssociationRequest, +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + {}, + ], +) +async def test_list_applied_auto_protection_policies_async( + request_type, transport: str = "grpc_asyncio" ): - transport_class = transports.BackupDRRestTransport + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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 + # 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 - default_values = getattr( - transport_class._BaseUpdateBackupPlanAssociation, - "_BaseUpdateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_applied_auto_protection_policies(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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + assert args[0] == request - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "requestId", - "updateMask", - ) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAppliedAutoProtectionPoliciesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - # verify required fields with non-default values are left alone +def test_list_applied_auto_protection_policies_field_headers(): client = BackupDRClient( 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + client.list_applied_auto_protection_policies(request) - response = client.update_backup_plan_association(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", + "parent=parent_value", + ) in kw["metadata"] -def test_update_backup_plan_association_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "backup_plan_association": { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" - } - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - 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.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() ) - mock_args.update(sample_request) + await client.list_applied_auto_protection_policies(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.update_backup_plan_association(**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_applied_auto_protection_policies_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_applied_auto_protection_policies( + 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/{backup_plan_association.name=projects/*/locations/*/backupPlanAssociations/*}" - % 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_update_backup_plan_association_rest_flattened_error(transport: str = "rest"): +def test_list_applied_auto_protection_policies_flattened_error(): client = BackupDRClient( 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_backup_plan_association( - backupplanassociation.UpdateBackupPlanAssociationRequest(), - backup_plan_association=backupplanassociation.BackupPlanAssociation( - cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( - instance_create_time=timestamp_pb2.Timestamp(seconds=751) - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_applied_auto_protection_policies( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + parent="parent_value", ) -def test_get_backup_plan_association_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 = BackupDRClient( - 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_applied_auto_protection_policies_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.get_backup_plan_association - 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_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() ) - # 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( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_applied_auto_protection_policies( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.get_backup_plan_association - ] = mock_rpc - - request = {} - client.get_backup_plan_association(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_backup_plan_association(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_plan_association_rest_required_fields( - request_type=backupplanassociation.GetBackupPlanAssociationRequest, -): - transport_class = transports.BackupDRRestTransport - 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) - ) + # 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 - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseGetBackupPlanAssociation, - "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["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.list_applied_auto_protection_policies( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + parent="parent_value", + ) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_list_applied_auto_protection_policies_pager(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupplanassociation.BackupPlanAssociation() - # 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) - # Convert return value to protobuf type - return_value = backupplanassociation.BackupPlanAssociation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_applied_auto_protection_policies( + request={}, retry=retry, timeout=timeout + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - response = client.get_backup_plan_association(request) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + for i in results + ) -def test_get_backup_plan_association_rest_flattened(): +def test_list_applied_auto_protection_policies_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - # 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 = backupplanassociation.BackupPlanAssociation() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = list(client.list_applied_auto_protection_policies(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" - } - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_async_pager(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = backupplanassociation.BackupPlanAssociation.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_applied_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_applied_auto_protection_policies( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - client.get_backup_plan_association(**mock_args) + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # 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/*/backupPlanAssociations/*}" - % client.transport._host, - args[1], + assert len(responses) == 6 + assert all( + isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + for i in responses ) -def test_get_backup_plan_association_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.asyncio +async def test_list_applied_auto_protection_policies_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_applied_auto_protection_policies(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", + [ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + {}, + ], +) +def test_initiate_delete_auto_protection_policy_binding( + request_type, transport: str = "grpc" +): + client = BackupDRClient( + 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_plan_association( - backupplanassociation.GetBackupPlanAssociationRequest(), + # 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.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.initiate_delete_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_initiate_delete_auto_protection_policy_binding_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 = BackupDRClient( + 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 = ( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( + name="name_value", + etag="etag_value", + ) + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.initiate_delete_auto_protection_policy_binding(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest( name="name_value", + etag="etag_value", ) + assert args[0] == request_msg -def test_list_backup_plan_associations_rest_use_cached_wrapped_rpc(): +def test_initiate_delete_auto_protection_policy_binding_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -27918,7 +28207,7 @@ def test_list_backup_plan_associations_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_backup_plan_associations + client._transport.initiate_delete_auto_protection_policy_binding in client._transport._wrapped_methods ) @@ -27928,245 +28217,352 @@ def test_list_backup_plan_associations_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_backup_plan_associations + client._transport.initiate_delete_auto_protection_policy_binding ] = mock_rpc - request = {} - client.list_backup_plan_associations(request) + client.initiate_delete_auto_protection_policy_binding(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backup_plan_associations(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.initiate_delete_auto_protection_policy_binding(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_plan_associations_rest_required_fields( - request_type=backupplanassociation.ListBackupPlanAssociationsRequest, +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.initiate_delete_auto_protection_policy_binding + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseListBackupPlanAssociations, - "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.initiate_delete_auto_protection_policy_binding + ] = mock_rpc + + request = {} + await client.initiate_delete_auto_protection_policy_binding(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.initiate_delete_auto_protection_policy_binding(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", + [ + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), {}, + ], +) +async def test_initiate_delete_auto_protection_policy_binding_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__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.initiate_delete_auto_protection_policy_binding(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + +def test_initiate_delete_auto_protection_policy_binding_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = backupplanassociation.ListBackupPlanAssociationsResponse() - # 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 + # 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 = ( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + ) - # Convert return value to protobuf type - return_value = backupplanassociation.ListBackupPlanAssociationsResponse.pb( - return_value - ) - 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.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initiate_delete_auto_protection_policy_binding(request) - response = client.list_backup_plan_associations(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_list_backup_plan_associations_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_field_headers_async(): + client = BackupDRAsyncClient( + 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 = backupplanassociation.ListBackupPlanAssociationsResponse() + # 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 = ( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + ) - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.initiate_delete_auto_protection_policy_binding(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 = backupplanassociation.ListBackupPlanAssociationsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.list_backup_plan_associations(**mock_args) + # 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_initiate_delete_auto_protection_policy_binding_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__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.initiate_delete_auto_protection_policy_binding( + name="name_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/{parent=projects/*/locations/*}/backupPlanAssociations" - % 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_list_backup_plan_associations_rest_flattened_error(transport: str = "rest"): +def test_initiate_delete_auto_protection_policy_binding_flattened_error(): client = BackupDRClient( 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_plan_associations( - backupplanassociation.ListBackupPlanAssociationsRequest(), - parent="parent_value", + client.initiate_delete_auto_protection_policy_binding( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + name="name_value", ) -def test_list_backup_plan_associations_rest_pager(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = ( - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - ], - next_page_token="abc", - ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[], - next_page_token="def", - ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - ], - next_page_token="ghi", - ), - backupplanassociation.ListBackupPlanAssociationsResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # Wrap the values into proper Response objs - response = tuple( - backupplanassociation.ListBackupPlanAssociationsResponse.to_json(x) - for x in response + 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.initiate_delete_auto_protection_policy_binding( + 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"} + # 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 - pager = client.list_backup_plan_associations(request=sample_request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") +@pytest.mark.asyncio +async def test_initiate_delete_auto_protection_policy_binding_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, backupplanassociation.BackupPlanAssociation) for i in results + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.initiate_delete_auto_protection_policy_binding( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + name="name_value", ) - pages = list(client.list_backup_plan_associations(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.GetBindingMatchingResourceRequest(), + {}, + ], +) +def test_get_binding_matching_resource(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) -def test_fetch_backup_plan_associations_for_resource_type_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + # 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_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bindingmatchingresource.BindingMatchingResource( + name="name_value", + resource="resource_value", + ) + response = client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.GetBindingMatchingResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bindingmatchingresource.BindingMatchingResource) + assert response.name == "name_value" + assert response.resource == "resource_value" + + +def test_get_binding_matching_resource_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 = BackupDRClient( + 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 = bindingmatchingresource.GetBindingMatchingResourceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_binding_matching_resource(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_binding_matching_resource_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -28174,7 +28570,7 @@ def test_fetch_backup_plan_associations_for_resource_type_rest_use_cached_wrappe # Ensure method has been cached assert ( - client._transport.fetch_backup_plan_associations_for_resource_type + client._transport.get_binding_matching_resource in client._transport._wrapped_methods ) @@ -28184,462 +28580,343 @@ def test_fetch_backup_plan_associations_for_resource_type_rest_use_cached_wrappe "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_backup_plan_associations_for_resource_type + client._transport.get_binding_matching_resource ] = mock_rpc - request = {} - client.fetch_backup_plan_associations_for_resource_type(request) + client.get_binding_matching_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_backup_plan_associations_for_resource_type(request) + client.get_binding_matching_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_fetch_backup_plan_associations_for_resource_type_rest_required_fields( - request_type=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, +@pytest.mark.asyncio +async def test_get_binding_matching_resource_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["resource_type"] = "" - 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 - assert "resourceType" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.get_binding_matching_resource + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseFetchBackupPlanAssociationsForResourceType, - "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_binding_matching_resource + ] = mock_rpc + + request = {} + await client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_binding_matching_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.GetBindingMatchingResourceRequest(), {}, + ], +) +async def test_get_binding_matching_resource_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == request_init["resource_type"] - jsonified_request["parent"] = "parent_value" - jsonified_request["resourceType"] = "resource_type_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "resourceType", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.BindingMatchingResource( + name="name_value", + resource="resource_value", + ) ) - ) + response = await client.get_binding_matching_resource(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == "resource_type_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.GetBindingMatchingResourceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, bindingmatchingresource.BindingMatchingResource) + assert response.name == "name_value" + assert response.resource == "resource_value" + +def test_get_binding_matching_resource_field_headers(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() ) - # 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 + # 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 = bindingmatchingresource.GetBindingMatchingResourceRequest() - # Convert return value to protobuf type - return_value = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( - return_value - ) - 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_binding_matching_resource), "__call__" + ) as call: + call.return_value = bindingmatchingresource.BindingMatchingResource() + client.get_binding_matching_resource(request) - response = client.fetch_backup_plan_associations_for_resource_type(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 = [ - ( - "resourceType", - "", - ), - ("$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_fetch_backup_plan_associations_for_resource_type_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_get_binding_matching_resource_field_headers_async(): + client = BackupDRAsyncClient( + 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 = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() - ) + # 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 = bindingmatchingresource.GetBindingMatchingResourceRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - resource_type="resource_type_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.BindingMatchingResource() ) - mock_args.update(sample_request) + await client.get_binding_matching_resource(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 = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( - return_value - ) - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.fetch_backup_plan_associations_for_resource_type(**mock_args) + # 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_binding_matching_resource_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bindingmatchingresource.BindingMatchingResource() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_binding_matching_resource( + name="name_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/{parent=projects/*/locations/*}/backupPlanAssociations:fetchForResourceType" - % 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_fetch_backup_plan_associations_for_resource_type_rest_flattened_error( - transport: str = "rest", -): +def test_get_binding_matching_resource_flattened_error(): client = BackupDRClient( 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.fetch_backup_plan_associations_for_resource_type( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), - parent="parent_value", - resource_type="resource_type_value", + client.get_binding_matching_resource( + bindingmatchingresource.GetBindingMatchingResourceRequest(), + name="name_value", ) -def test_fetch_backup_plan_associations_for_resource_type_rest_pager( - transport: str = "rest", -): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_get_binding_matching_resource_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - ], - next_page_token="abc", - ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[], - next_page_token="def", - ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - ], - next_page_token="ghi", - ), - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - backup_plan_associations=[ - backupplanassociation.BackupPlanAssociation(), - backupplanassociation.BackupPlanAssociation(), - ], - ), - ) - # Two responses for two calls - response = response + response + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = bindingmatchingresource.BindingMatchingResource() - # Wrap the values into proper Response objs - response = tuple( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.to_json( - x - ) - for x in response + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.BindingMatchingResource() ) - 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.fetch_backup_plan_associations_for_resource_type( - request=sample_request + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_binding_matching_resource( + name="name_value", ) - 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, backupplanassociation.BackupPlanAssociation) for i in results - ) + # 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 - pages = list( - client.fetch_backup_plan_associations_for_resource_type( - request=sample_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_get_binding_matching_resource_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_delete_backup_plan_association_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_binding_matching_resource( + bindingmatchingresource.GetBindingMatchingResourceRequest(), + name="name_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.delete_backup_plan_association - in client._transport._wrapped_methods - ) +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + {}, + ], +) +def test_list_binding_matching_resources(request_type, transport: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # 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_plan_association - ] = mock_rpc + # 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 - request = {} - client.delete_backup_plan_association(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.list_binding_matching_resources(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_backup_plan_association(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_plan_association_rest_required_fields( - request_type=backupplanassociation.DeleteBackupPlanAssociationRequest, -): - transport_class = transports.BackupDRRestTransport - - 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 - - default_values = getattr( - transport_class._BaseDeleteBackupPlanAssociation, - "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "autoProtectionPolicyBinding", - "requestId", - ) - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBindingMatchingResourcesPager) + assert response.next_page_token == "next_page_token_value" - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_list_binding_matching_resources_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - 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_plan_association(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_plan_association_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) - # 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/backupPlanAssociations/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_backup_plan_association(**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/*/backupPlanAssociations/*}" - % client.transport._host, - args[1], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -def test_delete_backup_plan_association_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - 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_plan_association( - backupplanassociation.DeleteBackupPlanAssociationRequest(), - name="name_value", + client.list_binding_matching_resources(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) + assert args[0] == request_msg -def test_trigger_backup_rest_use_cached_wrapped_rpc(): +def test_list_binding_matching_resources_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -28647,342 +28924,488 @@ def test_trigger_backup_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.trigger_backup in client._transport._wrapped_methods + assert ( + client._transport.list_binding_matching_resources + 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.trigger_backup] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.list_binding_matching_resources + ] = mock_rpc request = {} - client.trigger_backup(request) + client.list_binding_matching_resources(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.trigger_backup(request) + client.list_binding_matching_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_trigger_backup_rest_required_fields( - request_type=backupplanassociation.TriggerBackupRequest, +@pytest.mark.asyncio +async def test_list_binding_matching_resources_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.BackupDRRestTransport + # Clients should use _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 = BackupDRAsyncClient( + 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_binding_matching_resources + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseTriggerBackup, - "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_binding_matching_resources + ] = mock_rpc + + request = {} + await client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_binding_matching_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 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + bindingmatchingresource.ListBindingMatchingResourcesRequest(), {}, + ], +) +async def test_list_binding_matching_resources_async( + request_type, transport: str = "grpc_asyncio" +): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_binding_matching_resources(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBindingMatchingResourcesAsyncPager) + assert response.next_page_token == "next_page_token_value" + +def test_list_binding_matching_resources_field_headers(): client = BackupDRClient( 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 + # 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.parent = "parent_value" - response_value._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_binding_matching_resources), "__call__" + ) as call: + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + client.list_binding_matching_resources(request) - response = client.trigger_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 - 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", + "parent=parent_value", + ) in kw["metadata"] -def test_trigger_backup_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_binding_matching_resources_field_headers_async(): + client = BackupDRAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = bindingmatchingresource.ListBindingMatchingResourcesRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - rule_id="rule_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse() ) - mock_args.update(sample_request) + await client.list_binding_matching_resources(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.trigger_backup(**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_binding_matching_resources_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_binding_matching_resources( + 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/*/backupPlanAssociations/*}:triggerBackup" - % 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_trigger_backup_rest_flattened_error(transport: str = "rest"): +def test_list_binding_matching_resources_flattened_error(): client = BackupDRClient( 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.trigger_backup( - backupplanassociation.TriggerBackupRequest(), - name="name_value", - rule_id="rule_id_value", + client.list_binding_matching_resources( + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + parent="parent_value", ) -def test_get_data_source_reference_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 = BackupDRClient( - 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_binding_matching_resources_flattened_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.get_data_source_reference - 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_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() ) - # 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( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_binding_matching_resources( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.get_data_source_reference - ] = mock_rpc - request = {} - client.get_data_source_reference(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_data_source_reference(request) +@pytest.mark.asyncio +async def test_list_binding_matching_resources_flattened_error_async(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_binding_matching_resources( + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + parent="parent_value", + ) -def test_get_data_source_reference_rest_required_fields( - request_type=datasourcereference.GetDataSourceReferenceRequest, -): - transport_class = transports.BackupDRRestTransport +def test_list_binding_matching_resources_pager(transport_name: str = "grpc"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) - 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) - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, + ) - # verify fields with default values are dropped + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_binding_matching_resources( + request={}, retry=retry, timeout=timeout + ) - default_values = getattr( - transport_class._BaseGetDataSourceReference, - "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - # verify required fields with default values are now present + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - jsonified_request["name"] = "name_value" + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, bindingmatchingresource.BindingMatchingResource) + 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_binding_matching_resources_pages(transport_name: str = "grpc"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = datasourcereference.DataSourceReference() - # 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 = datasourcereference.DataSourceReference.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._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_data_source_reference(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, + ) + pages = list(client.list_binding_matching_resources(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_get_data_source_reference_rest_flattened(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_list_binding_matching_resources_async_pager(): + client = BackupDRAsyncClient( + 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 = datasourcereference.DataSourceReference() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/dataSourceReferences/sample3" - } - - # 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_binding_matching_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, ) - 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 = datasourcereference.DataSourceReference.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + async_pager = await client.list_binding_matching_resources( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - client.get_data_source_reference(**mock_args) + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # 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/*/dataSourceReferences/*}" - % client.transport._host, - args[1], + assert len(responses) == 6 + assert all( + isinstance(i, bindingmatchingresource.BindingMatchingResource) + for i in responses ) -def test_get_data_source_reference_rest_flattened_error(transport: str = "rest"): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_binding_matching_resources_async_pages(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_data_source_reference( - datasourcereference.GetDataSourceReferenceRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in ( + await client.list_binding_matching_resources(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_list_data_source_references_rest_use_cached_wrapped_rpc(): +def test_list_management_servers_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: @@ -28997,7 +29420,7 @@ def test_list_data_source_references_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_data_source_references + client._transport.list_management_servers in client._transport._wrapped_methods ) @@ -29007,24 +29430,24 @@ def test_list_data_source_references_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_data_source_references + client._transport.list_management_servers ] = mock_rpc request = {} - client.list_data_source_references(request) + client.list_management_servers(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_data_source_references(request) + client.list_management_servers(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_data_source_references_rest_required_fields( - request_type=datasourcereference.ListDataSourceReferencesRequest, +def test_list_management_servers_rest_required_fields( + request_type=backupdr.ListManagementServersRequest, ): transport_class = transports.BackupDRRestTransport @@ -29039,8 +29462,8 @@ def test_list_data_source_references_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListDataSourceReferences, - "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListManagementServers, + "_BaseListManagementServers__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -29073,7 +29496,7 @@ def test_list_data_source_references_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = datasourcereference.ListDataSourceReferencesResponse() + return_value = backupdr.ListManagementServersResponse() # 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 @@ -29094,23 +29517,21 @@ def test_list_data_source_references_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = datasourcereference.ListDataSourceReferencesResponse.pb( - return_value - ) + return_value = backupdr.ListManagementServersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_data_source_references(request) + response = client.list_management_servers(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_data_source_references_rest_flattened(): +def test_list_management_servers_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -29119,7 +29540,7 @@ def test_list_data_source_references_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 = datasourcereference.ListDataSourceReferencesResponse() + return_value = backupdr.ListManagementServersResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "projects/sample1/locations/sample2"} @@ -29134,28 +29555,26 @@ def test_list_data_source_references_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = datasourcereference.ListDataSourceReferencesResponse.pb( - return_value - ) + return_value = backupdr.ListManagementServersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_data_source_references(**mock_args) + client.list_management_servers(**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/*}/dataSourceReferences" + "%s/v1beta/{parent=projects/*/locations/*}/managementServers" % client.transport._host, args[1], ) -def test_list_data_source_references_rest_flattened_error(transport: str = "rest"): +def test_list_management_servers_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -29164,13 +29583,13 @@ def test_list_data_source_references_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_data_source_references( - datasourcereference.ListDataSourceReferencesRequest(), + client.list_management_servers( + backupdr.ListManagementServersRequest(), parent="parent_value", ) -def test_list_data_source_references_rest_pager(transport: str = "rest"): +def test_list_management_servers_rest_pager(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -29182,28 +29601,28 @@ def test_list_data_source_references_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), + backupdr.ManagementServer(), ], next_page_token="abc", ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[], + backupdr.ListManagementServersResponse( + management_servers=[], next_page_token="def", ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), ], next_page_token="ghi", ), - datasourcereference.ListDataSourceReferencesResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), + backupdr.ListManagementServersResponse( + management_servers=[ + backupdr.ManagementServer(), + backupdr.ManagementServer(), ], ), ) @@ -29212,8 +29631,7 @@ def test_list_data_source_references_rest_pager(transport: str = "rest"): # Wrap the values into proper Response objs response = tuple( - datasourcereference.ListDataSourceReferencesResponse.to_json(x) - for x in response + backupdr.ListManagementServersResponse.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): @@ -29223,23 +29641,21 @@ def test_list_data_source_references_rest_pager(transport: str = "rest"): sample_request = {"parent": "projects/sample1/locations/sample2"} - pager = client.list_data_source_references(request=sample_request) + pager = client.list_management_servers(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, datasourcereference.DataSourceReference) for i in results - ) + assert all(isinstance(i, backupdr.ManagementServer) for i in results) - pages = list(client.list_data_source_references(request=sample_request).pages) + pages = list(client.list_management_servers(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_fetch_data_source_references_for_resource_type_rest_use_cached_wrapped_rpc(): +def test_get_management_server_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: @@ -29254,7 +29670,7 @@ def test_fetch_data_source_references_for_resource_type_rest_use_cached_wrapped_ # Ensure method has been cached assert ( - client._transport.fetch_data_source_references_for_resource_type + client._transport.get_management_server in client._transport._wrapped_methods ) @@ -29263,31 +29679,30 @@ def test_fetch_data_source_references_for_resource_type_rest_use_cached_wrapped_ mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.fetch_data_source_references_for_resource_type - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_management_server] = ( + mock_rpc + ) request = {} - client.fetch_data_source_references_for_resource_type(request) + client.get_management_server(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_data_source_references_for_resource_type(request) + client.get_management_server(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_fetch_data_source_references_for_resource_type_rest_required_fields( - request_type=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, +def test_get_management_server_rest_required_fields( + request_type=backupdr.GetManagementServerRequest, ): transport_class = transports.BackupDRRestTransport request_init = {} - request_init["parent"] = "" - request_init["resource_type"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -29295,11 +29710,10 @@ def test_fetch_data_source_references_for_resource_type_rest_required_fields( ) # verify fields with default values are dropped - assert "resourceType" not in jsonified_request default_values = getattr( - transport_class._BaseFetchDataSourceReferencesForResourceType, - "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetManagementServer, + "_BaseGetManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -29308,28 +29722,12 @@ def test_fetch_data_source_references_for_resource_type_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == request_init["resource_type"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["resourceType"] = "resource_type_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - "resourceType", - ) - ) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == "resource_type_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -29338,9 +29736,7 @@ def test_fetch_data_source_references_for_resource_type_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() - ) + return_value = backupdr.ManagementServer() # 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 @@ -29361,31 +29757,21 @@ def test_fetch_data_source_references_for_resource_type_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( - return_value - ) - ) + return_value = backupdr.ManagementServer.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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.fetch_data_source_references_for_resource_type(request) + response = client.get_management_server(request) - expected_params = [ - ( - "resourceType", - "", - ), - ("$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_fetch_data_source_references_for_resource_type_rest_flattened(): +def test_get_management_server_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -29394,17 +29780,16 @@ def test_fetch_data_source_references_for_resource_type_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 = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() - ) + return_value = backupdr.ManagementServer() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/managementServers/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - resource_type="resource_type_value", + name="name_value", ) mock_args.update(sample_request) @@ -29412,32 +29797,26 @@ def test_fetch_data_source_references_for_resource_type_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( - return_value - ) - ) + return_value = backupdr.ManagementServer.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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.fetch_data_source_references_for_resource_type(**mock_args) + client.get_management_server(**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/*}/dataSourceReferences:fetchForResourceType" + "%s/v1beta/{name=projects/*/locations/*/managementServers/*}" % client.transport._host, args[1], ) -def test_fetch_data_source_references_for_resource_type_rest_flattened_error( - transport: str = "rest", -): +def test_get_management_server_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -29446,100 +29825,20 @@ def test_fetch_data_source_references_for_resource_type_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_data_source_references_for_resource_type( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), - parent="parent_value", - resource_type="resource_type_value", + client.get_management_server( + backupdr.GetManagementServerRequest(), + name="name_value", ) -def test_fetch_data_source_references_for_resource_type_rest_pager( - transport: str = "rest", -): - client = BackupDRClient( - 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 = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - next_page_token="abc", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[], - next_page_token="def", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - ], - next_page_token="ghi", - ), - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - data_source_references=[ - datasourcereference.DataSourceReference(), - datasourcereference.DataSourceReference(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.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.fetch_data_source_references_for_resource_type( - 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, datasourcereference.DataSourceReference) for i in results - ) - - pages = list( - client.fetch_data_source_references_for_resource_type( - request=sample_request - ).pages - ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_initialize_service_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 = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_create_management_server_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -29547,7 +29846,8 @@ def test_initialize_service_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.initialize_service in client._transport._wrapped_methods + client._transport.create_management_server + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -29555,12 +29855,12 @@ def test_initialize_service_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.initialize_service] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.create_management_server + ] = mock_rpc request = {} - client.initialize_service(request) + client.create_management_server(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -29569,21 +29869,21 @@ def test_initialize_service_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.initialize_service(request) + client.create_management_server(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_initialize_service_rest_required_fields( - request_type=backupdr.InitializeServiceRequest, +def test_create_management_server_rest_required_fields( + request_type=backupdr.CreateManagementServerRequest, ): transport_class = transports.BackupDRRestTransport request_init = {} - request_init["name"] = "" - request_init["resource_type"] = "" + request_init["parent"] = "" + request_init["management_server_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -29591,10 +29891,11 @@ def test_initialize_service_rest_required_fields( ) # verify fields with default values are dropped + assert "managementServerId" not in jsonified_request default_values = getattr( - transport_class._BaseInitializeService, - "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateManagementServer, + "_BaseCreateManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -29603,15 +29904,27 @@ def test_initialize_service_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "managementServerId" in jsonified_request + assert ( + jsonified_request["managementServerId"] == request_init["management_server_id"] + ) - jsonified_request["name"] = "name_value" - jsonified_request["resourceType"] = "resource_type_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["managementServerId"] = "management_server_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "managementServerId", + "requestId", + ) + ) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - assert "resourceType" in jsonified_request - assert jsonified_request["resourceType"] == "resource_type_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "managementServerId" in jsonified_request + assert jsonified_request["managementServerId"] == "management_server_id_value" client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -29646,14 +29959,80 @@ def test_initialize_service_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.initialize_service(request) + response = client.create_management_server(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "managementServerId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_auto_protection_policy_rest_use_cached_wrapped_rpc(): +def test_create_management_server_rest_flattened(): + client = BackupDRClient( + 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", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_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_management_server(**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/*}/managementServers" + % client.transport._host, + args[1], + ) + + +def test_create_management_server_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_management_server( + backupdr.CreateManagementServerRequest(), + parent="parent_value", + management_server=backupdr.ManagementServer(name="name_value"), + management_server_id="management_server_id_value", + ) + + +def test_delete_management_server_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: @@ -29668,7 +30047,7 @@ def test_create_auto_protection_policy_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_auto_protection_policy + client._transport.delete_management_server in client._transport._wrapped_methods ) @@ -29678,11 +30057,11 @@ def test_create_auto_protection_policy_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_auto_protection_policy + client._transport.delete_management_server ] = mock_rpc request = {} - client.create_auto_protection_policy(request) + client.delete_management_server(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -29691,21 +30070,20 @@ def test_create_auto_protection_policy_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_auto_protection_policy(request) + client.delete_management_server(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_auto_protection_policy_rest_required_fields( - request_type=autoprotectionpolicy.CreateAutoProtectionPolicyRequest, +def test_delete_management_server_rest_required_fields( + request_type=backupdr.DeleteManagementServerRequest, ): transport_class = transports.BackupDRRestTransport request_init = {} - request_init["parent"] = "" - request_init["auto_protection_policy_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -29713,11 +30091,10 @@ def test_create_auto_protection_policy_rest_required_fields( ) # verify fields with default values are dropped - assert "autoProtectionPolicyId" not in jsonified_request default_values = getattr( - transport_class._BaseCreateAutoProtectionPolicy, - "_BaseCreateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteManagementServer, + "_BaseDeleteManagementServer__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -29726,25 +30103,15 @@ def test_create_auto_protection_policy_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "autoProtectionPolicyId" in jsonified_request - assert ( - jsonified_request["autoProtectionPolicyId"] - == request_init["auto_protection_policy_id"] - ) - jsonified_request["parent"] = "parent_value" - jsonified_request["autoProtectionPolicyId"] = "auto_protection_policy_id_value" + jsonified_request["name"] = "name_value" # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("autoProtectionPolicyId",)) + assert not set(unset_fields) - set(("requestId",)) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "autoProtectionPolicyId" in jsonified_request - assert ( - jsonified_request["autoProtectionPolicyId"] == "auto_protection_policy_id_value" - ) + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -29765,10 +30132,9 @@ def test_create_auto_protection_policy_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() @@ -29779,20 +30145,14 @@ def test_create_auto_protection_policy_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_auto_protection_policy(request) + response = client.delete_management_server(request) - expected_params = [ - ( - "autoProtectionPolicyId", - "", - ), - ("$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_auto_protection_policy_rest_flattened(): +def test_delete_management_server_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -29804,15 +30164,13 @@ def test_create_auto_protection_policy_rest_flattened(): 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"} + sample_request = { + "name": "projects/sample1/locations/sample2/managementServers/sample3" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - auto_protection_policy_id="auto_protection_policy_id_value", + name="name_value", ) mock_args.update(sample_request) @@ -29824,20 +30182,20 @@ def test_create_auto_protection_policy_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_auto_protection_policy(**mock_args) + client.delete_management_server(**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/*}/autoProtectionPolicies" + "%s/v1beta/{name=projects/*/locations/*/managementServers/*}" % client.transport._host, args[1], ) -def test_create_auto_protection_policy_rest_flattened_error(transport: str = "rest"): +def test_delete_management_server_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -29846,17 +30204,13 @@ def test_create_auto_protection_policy_rest_flattened_error(transport: str = "re # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_auto_protection_policy( - autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), - parent="parent_value", - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - auto_protection_policy_id="auto_protection_policy_id_value", + client.delete_management_server( + backupdr.DeleteManagementServerRequest(), + name="name_value", ) -def test_list_auto_protection_policies_rest_use_cached_wrapped_rpc(): +def test_create_restore_template_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: @@ -29871,7 +30225,7 @@ def test_list_auto_protection_policies_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_auto_protection_policies + client._transport.create_restore_template in client._transport._wrapped_methods ) @@ -29881,29 +30235,34 @@ def test_list_auto_protection_policies_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_auto_protection_policies + client._transport.create_restore_template ] = mock_rpc request = {} - client.list_auto_protection_policies(request) + client.create_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_auto_protection_policies(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_restore_template(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_auto_protection_policies_rest_required_fields( - request_type=autoprotectionpolicy.ListAutoProtectionPoliciesRequest, +def test_create_restore_template_rest_required_fields( + request_type=gcb_restore_template.CreateRestoreTemplateRequest, ): transport_class = transports.BackupDRRestTransport request_init = {} request_init["parent"] = "" + request_init["restore_template_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -29911,10 +30270,11 @@ def test_list_auto_protection_policies_rest_required_fields( ) # verify fields with default values are dropped + assert "restoreTemplateId" not in jsonified_request default_values = getattr( - transport_class._BaseListAutoProtectionPolicies, - "_BaseListAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateRestoreTemplate, + "_BaseCreateRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -29923,22 +30283,25 @@ def test_list_auto_protection_policies_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "restoreTemplateId" in jsonified_request + assert jsonified_request["restoreTemplateId"] == request_init["restore_template_id"] jsonified_request["parent"] = "parent_value" + jsonified_request["restoreTemplateId"] = "restore_template_id_value" # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "requestId", + "restoreTemplateId", ) ) # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" + assert "restoreTemplateId" in jsonified_request + assert jsonified_request["restoreTemplateId"] == "restore_template_id_value" client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -29947,7 +30310,7 @@ def test_list_auto_protection_policies_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + 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 @@ -29959,32 +30322,34 @@ def test_list_auto_protection_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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._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_auto_protection_policies(request) + response = client.create_restore_template(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "restoreTemplateId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_auto_protection_policies_rest_flattened(): +def test_create_restore_template_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -29993,7 +30358,7 @@ def test_list_auto_protection_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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + 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"} @@ -30001,35 +30366,33 @@ def test_list_auto_protection_policies_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._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_auto_protection_policies(**mock_args) + client.create_restore_template(**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/*}/autoProtectionPolicies" + "%s/v1beta/{parent=projects/*/locations/*}/restoreTemplates" % client.transport._host, args[1], ) -def test_list_auto_protection_policies_rest_flattened_error(transport: str = "rest"): +def test_create_restore_template_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -30038,82 +30401,15 @@ def test_list_auto_protection_policies_rest_flattened_error(transport: str = "re # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_auto_protection_policies( - autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + client.create_restore_template( + gcb_restore_template.CreateRestoreTemplateRequest(), parent="parent_value", + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + restore_template_id="restore_template_id_value", ) -def test_list_auto_protection_policies_rest_pager(transport: str = "rest"): - client = BackupDRClient( - 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 = ( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), - ], - next_page_token="abc", - ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[], - next_page_token="def", - ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - ], - next_page_token="ghi", - ), - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - auto_protection_policies=[ - autoprotectionpolicy.AutoProtectionPolicy(), - autoprotectionpolicy.AutoProtectionPolicy(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse.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_auto_protection_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, autoprotectionpolicy.AutoProtectionPolicy) for i in results - ) - - pages = list(client.list_auto_protection_policies(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_get_auto_protection_policy_rest_use_cached_wrapped_rpc(): +def test_get_restore_template_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: @@ -30128,8 +30424,7 @@ def test_get_auto_protection_policy_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_auto_protection_policy - in client._transport._wrapped_methods + client._transport.get_restore_template in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -30137,25 +30432,25 @@ def test_get_auto_protection_policy_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.get_auto_protection_policy - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_restore_template] = ( + mock_rpc + ) request = {} - client.get_auto_protection_policy(request) + client.get_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_auto_protection_policy(request) + client.get_restore_template(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_auto_protection_policy_rest_required_fields( - request_type=autoprotectionpolicy.GetAutoProtectionPolicyRequest, +def test_get_restore_template_rest_required_fields( + request_type=restore_template.GetRestoreTemplateRequest, ): transport_class = transports.BackupDRRestTransport @@ -30170,8 +30465,8 @@ def test_get_auto_protection_policy_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetAutoProtectionPolicy, - "_BaseGetAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetRestoreTemplate, + "_BaseGetRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -30194,7 +30489,7 @@ def test_get_auto_protection_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = autoprotectionpolicy.AutoProtectionPolicy() + return_value = restore_template.RestoreTemplate() # 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 @@ -30215,21 +30510,21 @@ def test_get_auto_protection_policy_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) + return_value = restore_template.RestoreTemplate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_auto_protection_policy(request) + response = client.get_restore_template(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_auto_protection_policy_rest_flattened(): +def test_get_restore_template_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -30238,11 +30533,11 @@ def test_get_auto_protection_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 = autoprotectionpolicy.AutoProtectionPolicy() + return_value = restore_template.RestoreTemplate() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" } # get truthy value for each flattened field @@ -30255,26 +30550,26 @@ def test_get_auto_protection_policy_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) + return_value = restore_template.RestoreTemplate.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_auto_protection_policy(**mock_args) + client.get_restore_template(**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/*/autoProtectionPolicies/*}" + "%s/v1beta/{name=projects/*/locations/*/restoreTemplates/*}" % client.transport._host, args[1], ) -def test_get_auto_protection_policy_rest_flattened_error(transport: str = "rest"): +def test_get_restore_template_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -30283,13 +30578,13 @@ def test_get_auto_protection_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_auto_protection_policy( - autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + client.get_restore_template( + restore_template.GetRestoreTemplateRequest(), name="name_value", ) -def test_update_auto_protection_policy_rest_use_cached_wrapped_rpc(): +def test_list_restore_templates_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: @@ -30304,7 +30599,7 @@ def test_update_auto_protection_policy_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_auto_protection_policy + client._transport.list_restore_templates in client._transport._wrapped_methods ) @@ -30313,33 +30608,30 @@ def test_update_auto_protection_policy_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_auto_protection_policy - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_restore_templates] = ( + mock_rpc + ) request = {} - client.update_auto_protection_policy(request) + client.list_restore_templates(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_auto_protection_policy(request) + client.list_restore_templates(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_auto_protection_policy_rest_required_fields( - request_type=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, +def test_list_restore_templates_rest_required_fields( + request_type=restore_template.ListRestoreTemplatesRequest, ): transport_class = transports.BackupDRRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -30349,8 +30641,8 @@ def test_update_auto_protection_policy_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateAutoProtectionPolicy, - "_BaseUpdateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListRestoreTemplates, + "_BaseListRestoreTemplates__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -30360,10 +30652,21 @@ def test_update_auto_protection_policy_rest_required_fields( # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("updateMask",)) + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -30372,7 +30675,7 @@ def test_update_auto_protection_policy_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 = restore_template.ListRestoreTemplatesResponse() # 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 @@ -30384,28 +30687,32 @@ def test_update_auto_protection_policy_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = restore_template.ListRestoreTemplatesResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._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_auto_protection_policy(request) + response = client.list_restore_templates(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_auto_protection_policy_rest_flattened(): +def test_list_restore_templates_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -30414,46 +30721,41 @@ def test_update_auto_protection_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 = operations_pb2.Operation(name="operations/spam") + return_value = restore_template.ListRestoreTemplatesResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "auto_protection_policy": { - "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" - } - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + 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 = restore_template.ListRestoreTemplatesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_auto_protection_policy(**mock_args) + client.list_restore_templates(**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/{auto_protection_policy.name=projects/*/locations/*/autoProtectionPolicies/*}" + "%s/v1beta/{parent=projects/*/locations/*}/restoreTemplates" % client.transport._host, args[1], ) -def test_update_auto_protection_policy_rest_flattened_error(transport: str = "rest"): +def test_list_restore_templates_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -30462,16 +30764,79 @@ def test_update_auto_protection_policy_rest_flattened_error(transport: str = "re # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_auto_protection_policy( - autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), - auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( - name="name_value" + client.list_restore_templates( + restore_template.ListRestoreTemplatesRequest(), + parent="parent_value", + ) + + +def test_list_restore_templates_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + next_page_token="abc", ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[], + next_page_token="def", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + ], + next_page_token="ghi", + ), + restore_template.ListRestoreTemplatesResponse( + restore_templates=[ + restore_template.RestoreTemplate(), + restore_template.RestoreTemplate(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + restore_template.ListRestoreTemplatesResponse.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"} -def test_delete_auto_protection_policy_rest_use_cached_wrapped_rpc(): + pager = client.list_restore_templates(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, restore_template.RestoreTemplate) for i in results) + + pages = list(client.list_restore_templates(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_update_restore_template_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: @@ -30486,7 +30851,7 @@ def test_delete_auto_protection_policy_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_auto_protection_policy + client._transport.update_restore_template in client._transport._wrapped_methods ) @@ -30496,11 +30861,11 @@ def test_delete_auto_protection_policy_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_auto_protection_policy + client._transport.update_restore_template ] = mock_rpc request = {} - client.delete_auto_protection_policy(request) + client.update_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -30509,15 +30874,199 @@ def test_delete_auto_protection_policy_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_auto_protection_policy(request) + client.update_restore_template(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_auto_protection_policy_rest_required_fields( - request_type=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, +def test_update_restore_template_rest_required_fields( + request_type=gcb_restore_template.UpdateRestoreTemplateRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateRestoreTemplate, + "_BaseUpdateRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_restore_template(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_restore_template_rest_flattened(): + client = BackupDRClient( + 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 = { + "restore_template": { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + restore_template=gcb_restore_template.RestoreTemplate(name="name_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_restore_template(**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/{restore_template.name=projects/*/locations/*/restoreTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_update_restore_template_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_template( + gcb_restore_template.UpdateRestoreTemplateRequest(), + restore_template=gcb_restore_template.RestoreTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_restore_template_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 = BackupDRClient( + 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_restore_template + 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_restore_template + ] = mock_rpc + + request = {} + client.delete_restore_template(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_restore_template(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_restore_template_rest_required_fields( + request_type=restore_template.DeleteRestoreTemplateRequest, ): transport_class = transports.BackupDRRestTransport @@ -30532,8 +31081,8 @@ def test_delete_auto_protection_policy_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteAutoProtectionPolicy, - "_BaseDeleteAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteRestoreTemplate, + "_BaseDeleteRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -30546,7 +31095,12 @@ def test_delete_auto_protection_policy_rest_required_fields( jsonified_request["name"] = "name_value" # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("etag",)) + assert not set(unset_fields) - set( + ( + "force", + "requestId", + ) + ) # verify required fields with non-default values are left alone assert "name" in jsonified_request @@ -30584,14 +31138,14 @@ def test_delete_auto_protection_policy_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_auto_protection_policy(request) + response = client.delete_restore_template(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_auto_protection_policy_rest_flattened(): +def test_delete_restore_template_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -30604,7 +31158,7 @@ def test_delete_auto_protection_policy_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" } # get truthy value for each flattened field @@ -30621,20 +31175,20 @@ def test_delete_auto_protection_policy_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_auto_protection_policy(**mock_args) + client.delete_restore_template(**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/*/autoProtectionPolicies/*}" + "%s/v1beta/{name=projects/*/locations/*/restoreTemplates/*}" % client.transport._host, args[1], ) -def test_delete_auto_protection_policy_rest_flattened_error(transport: str = "rest"): +def test_delete_restore_template_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -30643,13 +31197,13 @@ def test_delete_auto_protection_policy_rest_flattened_error(transport: str = "re # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_auto_protection_policy( - autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + client.delete_restore_template( + restore_template.DeleteRestoreTemplateRequest(), name="name_value", ) -def test_create_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): +def test_run_restore_template_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: @@ -30664,8 +31218,7 @@ def test_create_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_auto_protection_policy_binding - in client._transport._wrapped_methods + client._transport.run_restore_template in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -30673,12 +31226,12 @@ def test_create_auto_protection_policy_binding_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.create_auto_protection_policy_binding - ] = mock_rpc + client._transport._wrapped_methods[client._transport.run_restore_template] = ( + mock_rpc + ) request = {} - client.create_auto_protection_policy_binding(request) + client.run_restore_template(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -30687,21 +31240,20 @@ def test_create_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_auto_protection_policy_binding(request) + client.run_restore_template(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_auto_protection_policy_binding_rest_required_fields( - request_type=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, +def test_run_restore_template_rest_required_fields( + request_type=restore_template.RunRestoreTemplateRequest, ): transport_class = transports.BackupDRRestTransport request_init = {} - request_init["parent"] = "" - request_init["auto_protection_policy_binding_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -30709,11 +31261,10 @@ def test_create_auto_protection_policy_binding_rest_required_fields( ) # verify fields with default values are dropped - assert "autoProtectionPolicyBindingId" not in jsonified_request default_values = getattr( - transport_class._BaseCreateAutoProtectionPolicyBinding, - "_BaseCreateAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseRunRestoreTemplate, + "_BaseRunRestoreTemplate__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -30722,28 +31273,12 @@ def test_create_auto_protection_policy_binding_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "autoProtectionPolicyBindingId" in jsonified_request - assert ( - jsonified_request["autoProtectionPolicyBindingId"] - == request_init["auto_protection_policy_binding_id"] - ) - jsonified_request["parent"] = "parent_value" - jsonified_request["autoProtectionPolicyBindingId"] = ( - "auto_protection_policy_binding_id_value" - ) - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("autoProtectionPolicyBindingId",)) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "autoProtectionPolicyBindingId" in jsonified_request - assert ( - jsonified_request["autoProtectionPolicyBindingId"] - == "auto_protection_policy_binding_id_value" - ) + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -30778,20 +31313,14 @@ def test_create_auto_protection_policy_binding_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.create_auto_protection_policy_binding(request) + response = client.run_restore_template(request) - expected_params = [ - ( - "autoProtectionPolicyBindingId", - "", - ), - ("$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_auto_protection_policy_binding_rest_flattened(): +def test_run_restore_template_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -30804,16 +31333,12 @@ def test_create_auto_protection_policy_binding_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value" - ), - auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + name="name_value", ) mock_args.update(sample_request) @@ -30825,22 +31350,20 @@ def test_create_auto_protection_policy_binding_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_auto_protection_policy_binding(**mock_args) + client.run_restore_template(**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/*/autoProtectionPolicies/*}/bindings" + "%s/v1beta/{name=projects/*/locations/*/restoreTemplates/*}:run" % client.transport._host, args[1], ) -def test_create_auto_protection_policy_binding_rest_flattened_error( - transport: str = "rest", -): +def test_run_restore_template_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -30849,17 +31372,13 @@ def test_create_auto_protection_policy_binding_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_auto_protection_policy_binding( - autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), - parent="parent_value", - auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value" - ), - auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + client.run_restore_template( + restore_template.RunRestoreTemplateRequest(), + name="name_value", ) -def test_get_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): +def test_get_restore_template_execution_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: @@ -30874,7 +31393,7 @@ def test_get_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_auto_protection_policy_binding + client._transport.get_restore_template_execution in client._transport._wrapped_methods ) @@ -30884,24 +31403,24 @@ def test_get_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_auto_protection_policy_binding + client._transport.get_restore_template_execution ] = mock_rpc request = {} - client.get_auto_protection_policy_binding(request) + client.get_restore_template_execution(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_auto_protection_policy_binding(request) + client.get_restore_template_execution(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_auto_protection_policy_binding_rest_required_fields( - request_type=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, +def test_get_restore_template_execution_rest_required_fields( + request_type=restore_template_execution.GetRestoreTemplateExecutionRequest, ): transport_class = transports.BackupDRRestTransport @@ -30916,8 +31435,8 @@ def test_get_auto_protection_policy_binding_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetAutoProtectionPolicyBinding, - "_BaseGetAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetRestoreTemplateExecution, + "_BaseGetRestoreTemplateExecution__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -30940,7 +31459,7 @@ def test_get_auto_protection_policy_binding_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + return_value = restore_template_execution.RestoreTemplateExecution() # 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 @@ -30961,7 +31480,7 @@ def test_get_auto_protection_policy_binding_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value = restore_template_execution.RestoreTemplateExecution.pb( return_value ) json_return_value = json_format.MessageToJson(return_value) @@ -30970,14 +31489,14 @@ def test_get_auto_protection_policy_binding_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_auto_protection_policy_binding(request) + response = client.get_restore_template_execution(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_auto_protection_policy_binding_rest_flattened(): +def test_get_restore_template_execution_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -30986,11 +31505,11 @@ def test_get_auto_protection_policy_binding_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 = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + return_value = restore_template_execution.RestoreTemplateExecution() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/sample4" } # get truthy value for each flattened field @@ -31003,7 +31522,7 @@ def test_get_auto_protection_policy_binding_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value = restore_template_execution.RestoreTemplateExecution.pb( return_value ) json_return_value = json_format.MessageToJson(return_value) @@ -31011,22 +31530,20 @@ def test_get_auto_protection_policy_binding_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_auto_protection_policy_binding(**mock_args) + client.get_restore_template_execution(**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/*/autoProtectionPolicies/*/bindings/*}" + "%s/v1beta/{name=projects/*/locations/*/restoreTemplates/*/executions/*}" % client.transport._host, args[1], ) -def test_get_auto_protection_policy_binding_rest_flattened_error( - transport: str = "rest", -): +def test_get_restore_template_execution_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -31035,13 +31552,13 @@ def test_get_auto_protection_policy_binding_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_auto_protection_policy_binding( - autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + client.get_restore_template_execution( + restore_template_execution.GetRestoreTemplateExecutionRequest(), name="name_value", ) -def test_list_auto_protection_policy_bindings_rest_use_cached_wrapped_rpc(): +def test_list_restore_template_executions_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: @@ -31056,7 +31573,7 @@ def test_list_auto_protection_policy_bindings_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_auto_protection_policy_bindings + client._transport.list_restore_template_executions in client._transport._wrapped_methods ) @@ -31066,24 +31583,24 @@ def test_list_auto_protection_policy_bindings_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_auto_protection_policy_bindings + client._transport.list_restore_template_executions ] = mock_rpc request = {} - client.list_auto_protection_policy_bindings(request) + client.list_restore_template_executions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_auto_protection_policy_bindings(request) + client.list_restore_template_executions(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_auto_protection_policy_bindings_rest_required_fields( - request_type=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, +def test_list_restore_template_executions_rest_required_fields( + request_type=restore_template_execution.ListRestoreTemplateExecutionsRequest, ): transport_class = transports.BackupDRRestTransport @@ -31098,8 +31615,8 @@ def test_list_auto_protection_policy_bindings_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListAutoProtectionPolicyBindings, - "_BaseListAutoProtectionPolicyBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListRestoreTemplateExecutions, + "_BaseListRestoreTemplateExecutions__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -31132,9 +31649,7 @@ def test_list_auto_protection_policy_bindings_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() - ) + return_value = restore_template_execution.ListRestoreTemplateExecutionsResponse() # 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 @@ -31156,7 +31671,7 @@ def test_list_auto_protection_policy_bindings_rest_required_fields( # Convert return value to protobuf type return_value = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + restore_template_execution.ListRestoreTemplateExecutionsResponse.pb( return_value ) ) @@ -31166,14 +31681,14 @@ def test_list_auto_protection_policy_bindings_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_auto_protection_policy_bindings(request) + response = client.list_restore_template_executions(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_auto_protection_policy_bindings_rest_flattened(): +def test_list_restore_template_executions_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -31183,12 +31698,12 @@ def test_list_auto_protection_policy_bindings_rest_flattened(): with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + restore_template_execution.ListRestoreTemplateExecutionsResponse() ) # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + "parent": "projects/sample1/locations/sample2/restoreTemplates/sample3" } # get truthy value for each flattened field @@ -31202,7 +31717,7 @@ def test_list_auto_protection_policy_bindings_rest_flattened(): response_value.status_code = 200 # Convert return value to protobuf type return_value = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + restore_template_execution.ListRestoreTemplateExecutionsResponse.pb( return_value ) ) @@ -31211,22 +31726,20 @@ def test_list_auto_protection_policy_bindings_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_auto_protection_policy_bindings(**mock_args) + client.list_restore_template_executions(**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/*/autoProtectionPolicies/*}/bindings" + "%s/v1beta/{parent=projects/*/locations/*/restoreTemplates/*}/executions" % client.transport._host, args[1], ) -def test_list_auto_protection_policy_bindings_rest_flattened_error( - transport: str = "rest", -): +def test_list_restore_template_executions_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -31235,13 +31748,13 @@ def test_list_auto_protection_policy_bindings_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_auto_protection_policy_bindings( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + client.list_restore_template_executions( + restore_template_execution.ListRestoreTemplateExecutionsRequest(), parent="parent_value", ) -def test_list_auto_protection_policy_bindings_rest_pager(transport: str = "rest"): +def test_list_restore_template_executions_rest_pager(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -31253,28 +31766,28 @@ def test_list_auto_protection_policy_bindings_rest_pager(transport: str = "rest" # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="abc", ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[], + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[], next_page_token="def", ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), ], next_page_token="ghi", ), - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - auto_protection_policy_bindings=[ - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), - autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + restore_template_execution.ListRestoreTemplateExecutionsResponse( + restore_template_executions=[ + restore_template_execution.RestoreTemplateExecution(), + restore_template_execution.RestoreTemplateExecution(), ], ), ) @@ -31283,9 +31796,7 @@ def test_list_auto_protection_policy_bindings_rest_pager(transport: str = "rest" # Wrap the values into proper Response objs response = tuple( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.to_json( - x - ) + restore_template_execution.ListRestoreTemplateExecutionsResponse.to_json(x) for x in response ) return_values = tuple(Response() for i in response) @@ -31295,10 +31806,10 @@ def test_list_auto_protection_policy_bindings_rest_pager(transport: str = "rest" req.side_effect = return_values sample_request = { - "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + "parent": "projects/sample1/locations/sample2/restoreTemplates/sample3" } - pager = client.list_auto_protection_policy_bindings(request=sample_request) + pager = client.list_restore_template_executions(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") @@ -31306,18 +31817,18 @@ def test_list_auto_protection_policy_bindings_rest_pager(transport: str = "rest" results = list(pager) assert len(results) == 6 assert all( - isinstance(i, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + isinstance(i, restore_template_execution.RestoreTemplateExecution) for i in results ) pages = list( - client.list_auto_protection_policy_bindings(request=sample_request).pages + client.list_restore_template_executions(request=sample_request).pages ) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_list_applied_auto_protection_policies_rest_use_cached_wrapped_rpc(): +def test_trigger_restore_cleanup_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: @@ -31332,7 +31843,7 @@ def test_list_applied_auto_protection_policies_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_applied_auto_protection_policies + client._transport.trigger_restore_cleanup in client._transport._wrapped_methods ) @@ -31342,29 +31853,33 @@ def test_list_applied_auto_protection_policies_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_applied_auto_protection_policies + client._transport.trigger_restore_cleanup ] = mock_rpc request = {} - client.list_applied_auto_protection_policies(request) + client.trigger_restore_cleanup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_applied_auto_protection_policies(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.trigger_restore_cleanup(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_applied_auto_protection_policies_rest_required_fields( - request_type=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, +def test_trigger_restore_cleanup_rest_required_fields( + request_type=restore_template_execution.TriggerRestoreCleanupRequest, ): transport_class = transports.BackupDRRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -31374,8 +31889,8 @@ def test_list_applied_auto_protection_policies_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListAppliedAutoProtectionPolicies, - "_BaseListAppliedAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseTriggerRestoreCleanup, + "_BaseTriggerRestoreCleanup__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -31385,21 +31900,11 @@ def test_list_applied_auto_protection_policies_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) + jsonified_request["name"] = "name_value" # 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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -31408,9 +31913,7 @@ def test_list_applied_auto_protection_policies_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() - ) + 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 @@ -31422,32 +31925,28 @@ def test_list_applied_auto_protection_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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( - return_value - ) json_return_value = json_format.MessageToJson(return_value) response_value._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_applied_auto_protection_policies(request) + response = client.trigger_restore_cleanup(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_applied_auto_protection_policies_rest_flattened(): +def test_trigger_restore_cleanup_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -31456,49 +31955,41 @@ def test_list_applied_auto_protection_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 = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() - ) + 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"} + sample_request = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/sample4" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_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 = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( - return_value - ) - ) json_return_value = json_format.MessageToJson(return_value) response_value._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_applied_auto_protection_policies(**mock_args) + client.trigger_restore_cleanup(**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/*}/appliedAutoProtectionPolicies" + "%s/v1beta/{name=projects/*/locations/*/restoreTemplates/*/executions/*}:triggerRestoreCleanup" % client.transport._host, args[1], ) -def test_list_applied_auto_protection_policies_rest_flattened_error( - transport: str = "rest", -): +def test_trigger_restore_cleanup_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -31507,87 +31998,224 @@ def test_list_applied_auto_protection_policies_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_applied_auto_protection_policies( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), - parent="parent_value", + client.trigger_restore_cleanup( + restore_template_execution.TriggerRestoreCleanupRequest(), + name="name_value", ) -def test_list_applied_auto_protection_policies_rest_pager(transport: str = "rest"): +def test_create_restore_verification_plan_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 = BackupDRClient( + 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_restore_verification_plan + 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_restore_verification_plan + ] = mock_rpc + + request = {} + client.create_restore_verification_plan(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_restore_verification_plan(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_restore_verification_plan_rest_required_fields( + request_type=gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["restore_verification_plan_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 "restoreVerificationPlanId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateRestoreVerificationPlan, + "_BaseCreateRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "restoreVerificationPlanId" in jsonified_request + assert ( + jsonified_request["restoreVerificationPlanId"] + == request_init["restore_verification_plan_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["restoreVerificationPlanId"] = ( + "restore_verification_plan_id_value" + ) + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "restoreVerificationPlanId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "restoreVerificationPlanId" in jsonified_request + assert ( + jsonified_request["restoreVerificationPlanId"] + == "restore_verification_plan_id_value" + ) + client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + 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: - # 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 = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - ], - next_page_token="abc", - ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[], - next_page_token="def", - ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - ], - next_page_token="ghi", - ), - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - applied_auto_protection_policies=[ - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.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 + 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_restore_verification_plan(request) + + expected_params = [ + ( + "restoreVerificationPlanId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_restore_verification_plan_rest_flattened(): + client = BackupDRClient( + 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"} - pager = client.list_applied_auto_protection_policies(request=sample_request) + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" + ), + restore_verification_plan_id="restore_verification_plan_id_value", + ) + mock_args.update(sample_request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # 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"} - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) - for i in results + client.create_restore_verification_plan(**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/*}/restoreVerificationPlans" + % client.transport._host, + args[1], ) - pages = list( - client.list_applied_auto_protection_policies(request=sample_request).pages + +def test_create_restore_verification_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_restore_verification_plan( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest(), + parent="parent_value", + restore_verification_plan=gcb_restore_verification_plan.RestoreVerificationPlan( + name="name_value" + ), + restore_verification_plan_id="restore_verification_plan_id_value", ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_initiate_delete_auto_protection_policy_binding_rest_use_cached_wrapped_rpc(): +def test_create_restore_verification_plan_association_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: @@ -31602,7 +32230,7 @@ def test_initiate_delete_auto_protection_policy_binding_rest_use_cached_wrapped_ # Ensure method has been cached assert ( - client._transport.initiate_delete_auto_protection_policy_binding + client._transport.create_restore_verification_plan_association in client._transport._wrapped_methods ) @@ -31612,11 +32240,11 @@ def test_initiate_delete_auto_protection_policy_binding_rest_use_cached_wrapped_ "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.initiate_delete_auto_protection_policy_binding + client._transport.create_restore_verification_plan_association ] = mock_rpc request = {} - client.initiate_delete_auto_protection_policy_binding(request) + client.create_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -31625,20 +32253,21 @@ def test_initiate_delete_auto_protection_policy_binding_rest_use_cached_wrapped_ # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.initiate_delete_auto_protection_policy_binding(request) + client.create_restore_verification_plan_association(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_initiate_delete_auto_protection_policy_binding_rest_required_fields( - request_type=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, +def test_create_restore_verification_plan_association_rest_required_fields( + request_type=gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, ): transport_class = transports.BackupDRRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["restore_verification_plan_association_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -31646,10 +32275,11 @@ def test_initiate_delete_auto_protection_policy_binding_rest_required_fields( ) # verify fields with default values are dropped + assert "restoreVerificationPlanAssociationId" not in jsonified_request default_values = getattr( - transport_class._BaseInitiateDeleteAutoProtectionPolicyBinding, - "_BaseInitiateDeleteAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateRestoreVerificationPlanAssociation, + "_BaseCreateRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -31658,12 +32288,33 @@ def test_initiate_delete_auto_protection_policy_binding_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "restoreVerificationPlanAssociationId" in jsonified_request + assert ( + jsonified_request["restoreVerificationPlanAssociationId"] + == request_init["restore_verification_plan_association_id"] + ) - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["restoreVerificationPlanAssociationId"] = ( + "restore_verification_plan_association_id_value" + ) + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "restoreVerificationPlanAssociationId", + ) + ) # 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 "restoreVerificationPlanAssociationId" in jsonified_request + assert ( + jsonified_request["restoreVerificationPlanAssociationId"] + == "restore_verification_plan_association_id_value" + ) client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), @@ -31698,14 +32349,20 @@ def test_initiate_delete_auto_protection_policy_binding_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.initiate_delete_auto_protection_policy_binding(request) + response = client.create_restore_verification_plan_association(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "restoreVerificationPlanAssociationId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_initiate_delete_auto_protection_policy_binding_rest_flattened(): +def test_create_restore_verification_plan_association_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -31718,12 +32375,16 @@ def test_initiate_delete_auto_protection_policy_binding_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + restore_template="restore_template_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_id_value", ) mock_args.update(sample_request) @@ -31735,20 +32396,20 @@ def test_initiate_delete_auto_protection_policy_binding_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.initiate_delete_auto_protection_policy_binding(**mock_args) + client.create_restore_verification_plan_association(**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/*/autoProtectionPolicies/*/bindings/*}:initiateDelete" + "%s/v1beta/{parent=projects/*/locations/*/restoreVerificationPlans/*}/associations" % client.transport._host, args[1], ) -def test_initiate_delete_auto_protection_policy_binding_rest_flattened_error( +def test_create_restore_verification_plan_association_rest_flattened_error( transport: str = "rest", ): client = BackupDRClient( @@ -31759,13 +32420,17 @@ def test_initiate_delete_auto_protection_policy_binding_rest_flattened_error( # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.initiate_delete_auto_protection_policy_binding( - autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), - name="name_value", + client.create_restore_verification_plan_association( + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest(), + parent="parent_value", + restore_verification_plan_association=gcb_restore_verification_plan_association.RestoreVerificationPlanAssociation( + restore_template="restore_template_value" + ), + restore_verification_plan_association_id="restore_verification_plan_association_id_value", ) -def test_get_binding_matching_resource_rest_use_cached_wrapped_rpc(): +def test_get_restore_verification_plan_association_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: @@ -31780,7 +32445,7 @@ def test_get_binding_matching_resource_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_binding_matching_resource + client._transport.get_restore_verification_plan_association in client._transport._wrapped_methods ) @@ -31790,24 +32455,24 @@ def test_get_binding_matching_resource_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.get_binding_matching_resource + client._transport.get_restore_verification_plan_association ] = mock_rpc request = {} - client.get_binding_matching_resource(request) + client.get_restore_verification_plan_association(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_binding_matching_resource(request) + client.get_restore_verification_plan_association(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_binding_matching_resource_rest_required_fields( - request_type=bindingmatchingresource.GetBindingMatchingResourceRequest, +def test_get_restore_verification_plan_association_rest_required_fields( + request_type=restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, ): transport_class = transports.BackupDRRestTransport @@ -31822,8 +32487,8 @@ def test_get_binding_matching_resource_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseGetBindingMatchingResource, - "_BaseGetBindingMatchingResource__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetRestoreVerificationPlanAssociation, + "_BaseGetRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -31846,7 +32511,9 @@ def test_get_binding_matching_resource_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = bindingmatchingresource.BindingMatchingResource() + return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) # 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 @@ -31867,7 +32534,7 @@ def test_get_binding_matching_resource_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = bindingmatchingresource.BindingMatchingResource.pb( + return_value = restore_verification_plan_association.RestoreVerificationPlanAssociation.pb( return_value ) json_return_value = json_format.MessageToJson(return_value) @@ -31876,14 +32543,14 @@ def test_get_binding_matching_resource_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_binding_matching_resource(request) + response = client.get_restore_verification_plan_association(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_binding_matching_resource_rest_flattened(): +def test_get_restore_verification_plan_association_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -31892,11 +32559,13 @@ def test_get_binding_matching_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 = bindingmatchingresource.BindingMatchingResource() + return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4/matchingResources/sample5" + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/sample4" } # get truthy value for each flattened field @@ -31909,26 +32578,32 @@ def test_get_binding_matching_resource_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = bindingmatchingresource.BindingMatchingResource.pb(return_value) + return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value._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_binding_matching_resource(**mock_args) + client.get_restore_verification_plan_association(**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/*/autoProtectionPolicies/*/bindings/*/matchingResources/*}" + "%s/v1beta/{name=projects/*/locations/*/restoreVerificationPlans/*/associations/*}" % client.transport._host, args[1], ) -def test_get_binding_matching_resource_rest_flattened_error(transport: str = "rest"): +def test_get_restore_verification_plan_association_rest_flattened_error( + transport: str = "rest", +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -31937,13 +32612,13 @@ def test_get_binding_matching_resource_rest_flattened_error(transport: str = "re # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_binding_matching_resource( - bindingmatchingresource.GetBindingMatchingResourceRequest(), + client.get_restore_verification_plan_association( + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest(), name="name_value", ) -def test_list_binding_matching_resources_rest_use_cached_wrapped_rpc(): +def test_list_restore_verification_plan_associations_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: @@ -31958,7 +32633,7 @@ def test_list_binding_matching_resources_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_binding_matching_resources + client._transport.list_restore_verification_plan_associations in client._transport._wrapped_methods ) @@ -31968,24 +32643,24 @@ def test_list_binding_matching_resources_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_binding_matching_resources + client._transport.list_restore_verification_plan_associations ] = mock_rpc request = {} - client.list_binding_matching_resources(request) + client.list_restore_verification_plan_associations(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_binding_matching_resources(request) + client.list_restore_verification_plan_associations(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_binding_matching_resources_rest_required_fields( - request_type=bindingmatchingresource.ListBindingMatchingResourcesRequest, +def test_list_restore_verification_plan_associations_rest_required_fields( + request_type=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, ): transport_class = transports.BackupDRRestTransport @@ -32000,8 +32675,8 @@ def test_list_binding_matching_resources_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListBindingMatchingResources, - "_BaseListBindingMatchingResources__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListRestoreVerificationPlanAssociations, + "_BaseListRestoreVerificationPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -32034,7 +32709,7 @@ def test_list_binding_matching_resources_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = bindingmatchingresource.ListBindingMatchingResourcesResponse() + return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() # 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 @@ -32055,10 +32730,8 @@ def test_list_binding_matching_resources_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( - return_value - ) + return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.pb( + return_value ) json_return_value = json_format.MessageToJson(return_value) @@ -32066,14 +32739,14 @@ def test_list_binding_matching_resources_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_binding_matching_resources(request) + response = client.list_restore_verification_plan_associations(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_binding_matching_resources_rest_flattened(): +def test_list_restore_verification_plan_associations_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -32082,11 +32755,11 @@ def test_list_binding_matching_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 = bindingmatchingresource.ListBindingMatchingResourcesResponse() + return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" } # get truthy value for each flattened field @@ -32099,7 +32772,7 @@ def test_list_binding_matching_resources_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.pb( return_value ) json_return_value = json_format.MessageToJson(return_value) @@ -32107,20 +32780,22 @@ def test_list_binding_matching_resources_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_binding_matching_resources(**mock_args) + client.list_restore_verification_plan_associations(**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/*/autoProtectionPolicies/*/bindings/*}/matchingResources" + "%s/v1beta/{parent=projects/*/locations/*/restoreVerificationPlans/*}/associations" % client.transport._host, args[1], ) -def test_list_binding_matching_resources_rest_flattened_error(transport: str = "rest"): +def test_list_restore_verification_plan_associations_rest_flattened_error( + transport: str = "rest", +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -32129,13 +32804,15 @@ def test_list_binding_matching_resources_rest_flattened_error(transport: str = " # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_binding_matching_resources( - bindingmatchingresource.ListBindingMatchingResourcesRequest(), + client.list_restore_verification_plan_associations( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest(), parent="parent_value", ) -def test_list_binding_matching_resources_rest_pager(transport: str = "rest"): +def test_list_restore_verification_plan_associations_rest_pager( + transport: str = "rest", +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -32147,28 +32824,28 @@ def test_list_binding_matching_resources_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="abc", ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[], + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[], next_page_token="def", ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], next_page_token="ghi", ), - bindingmatchingresource.ListBindingMatchingResourcesResponse( - matching_resources=[ - bindingmatchingresource.BindingMatchingResource(), - bindingmatchingresource.BindingMatchingResource(), + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + restore_verification_plan_associations=[ + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + restore_verification_plan_association.RestoreVerificationPlanAssociation(), ], ), ) @@ -32177,7 +32854,9 @@ def test_list_binding_matching_resources_rest_pager(transport: str = "rest"): # Wrap the values into proper Response objs response = tuple( - bindingmatchingresource.ListBindingMatchingResourcesResponse.to_json(x) + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.to_json( + x + ) for x in response ) return_values = tuple(Response() for i in response) @@ -32187,10 +32866,12 @@ def test_list_binding_matching_resources_rest_pager(transport: str = "rest"): req.side_effect = return_values sample_request = { - "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4" + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" } - pager = client.list_binding_matching_resources(request=sample_request) + pager = client.list_restore_verification_plan_associations( + request=sample_request + ) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") @@ -32198,2633 +32879,17145 @@ def test_list_binding_matching_resources_rest_pager(transport: str = "rest"): results = list(pager) assert len(results) == 6 assert all( - isinstance(i, bindingmatchingresource.BindingMatchingResource) + isinstance( + i, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) for i in results ) pages = list( - client.list_binding_matching_resources(request=sample_request).pages + client.list_restore_verification_plan_associations( + 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.BackupDRGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): +def test_delete_restore_verification_plan_association_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 = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.BackupDRGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BackupDRClient( - 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.BackupDRGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BackupDRClient( - client_options=options, - transport=transport, + # Ensure method has been cached + assert ( + client._transport.delete_restore_verification_plan_association + 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 = BackupDRClient( - 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. ) + client._transport._wrapped_methods[ + client._transport.delete_restore_verification_plan_association + ] = mock_rpc - # It is an error to provide scopes and a transport instance. - transport = transports.BackupDRGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = BackupDRClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + request = {} + client.delete_restore_verification_plan_association(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BackupDRGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = BackupDRClient(transport=transport) - assert client.transport is transport + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + client.delete_restore_verification_plan_association(request) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BackupDRGrpcTransport( - 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 - transport = transports.BackupDRGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_delete_restore_verification_plan_association_rest_required_fields( + request_type=restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport -@pytest.mark.parametrize( - "transport_class", - [ - transports.BackupDRGrpcTransport, - transports.BackupDRGrpcAsyncIOTransport, - transports.BackupDRRestTransport, - ], -) -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_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 -def test_transport_kind_grpc(): - transport = BackupDRClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() + default_values = getattr( + transport_class._BaseDeleteRestoreVerificationPlanAssociation, + "_BaseDeleteRestoreVerificationPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) - assert transport.kind == "grpc" + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_initialize_client_w_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["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. -def test_list_management_servers_empty_call_grpc(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_management_servers), "__call__" - ) as call: - call.return_value = backupdr.ListManagementServersResponse() - client.list_management_servers(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.ListManagementServersRequest() - assert args[0] == request_msg + # 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) -# 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_management_server_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.get_management_server), "__call__" - ) as call: - call.return_value = backupdr.ManagementServer() - client.get_management_server(request=None) + response = client.delete_restore_verification_plan_association(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.GetManagementServerRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_management_server_empty_call_grpc(): +def test_delete_restore_verification_plan_association_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_management_server), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_management_server(request=None) + # 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") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.CreateManagementServerRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/sample4" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_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_management_server_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # 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"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_management_server), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_management_server(request=None) + client.delete_restore_verification_plan_association(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.DeleteManagementServerRequest() - assert args[0] == request_msg + # 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/*/restoreVerificationPlans/*/associations/*}" + % client.transport._host, + args[1], + ) -# 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_backup_vault_empty_call_grpc(): +def test_delete_restore_verification_plan_association_rest_flattened_error( + transport: str = "rest", +): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup_vault(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_restore_verification_plan_association( + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest(), + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.CreateBackupVaultRequest() - assert args[0] == request_msg +def test_trigger_restore_verification_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="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_list_backup_vaults_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" - ) as call: - call.return_value = backupvault.ListBackupVaultsResponse() - client.list_backup_vaults(request=None) + # Ensure method has been cached + assert ( + client._transport.trigger_restore_verification + in client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListBackupVaultsRequest() - assert args[0] == request_msg + # 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.trigger_restore_verification + ] = mock_rpc + request = {} + client.trigger_restore_verification(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_fetch_usable_backup_vaults_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" - ) as call: - call.return_value = backupvault.FetchUsableBackupVaultsResponse() - client.fetch_usable_backup_vaults(request=None) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.FetchUsableBackupVaultsRequest() - assert args[0] == request_msg + client.trigger_restore_verification(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. -def test_get_backup_vault_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: - call.return_value = backupvault.BackupVault() - client.get_backup_vault(request=None) +def test_trigger_restore_verification_rest_required_fields( + request_type=restore_verification_plan_association.TriggerRestoreVerificationRequest, +): + transport_class = transports.BackupDRRestTransport - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetBackupVaultRequest() - assert args[0] == request_msg + 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 -# 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_backup_vault_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + default_values = getattr( + transport_class._BaseTriggerRestoreVerification, + "_BaseTriggerRestoreVerification__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_vault), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup_vault(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateBackupVaultRequest() - assert args[0] == request_msg + jsonified_request["name"] = "name_value" + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["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. -def test_delete_backup_vault_empty_call_grpc(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_vault), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup_vault(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.DeleteBackupVaultRequest() - assert args[0] == request_msg + # 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) -# 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_data_sources_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), "__call__" - ) as call: - call.return_value = backupvault.ListDataSourcesResponse() - client.list_data_sources(request=None) + response = client.trigger_restore_verification(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListDataSourcesRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_data_source_empty_call_grpc(): +def test_trigger_restore_verification_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: - call.return_value = backupvault.DataSource() - client.get_data_source(request=None) + # 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") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetDataSourceRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/sample4" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_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_update_data_source_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # 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"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_data_source(request=None) + client.trigger_restore_verification(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateDataSourceRequest() - assert args[0] == request_msg + # 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/*/restoreVerificationPlans/*/associations/*}:triggerRestoreVerification" + % client.transport._host, + args[1], + ) -# 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(): +def test_trigger_restore_verification_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_backups), "__call__") as call: - call.return_value = backupvault.ListBackupsResponse() - client.list_backups(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.trigger_restore_verification( + restore_verification_plan_association.TriggerRestoreVerificationRequest(), + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListBackupsRequest() - assert args[0] == request_msg +def test_get_restore_verification_plan_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="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_fetch_backups_for_resource_type_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" - ) as call: - call.return_value = backupvault.FetchBackupsForResourceTypeResponse() - client.fetch_backups_for_resource_type(request=None) + # Ensure method has been cached + assert ( + client._transport.get_restore_verification_plan + in client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.FetchBackupsForResourceTypeRequest() - assert args[0] == request_msg + # 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_restore_verification_plan + ] = mock_rpc + request = {} + client.get_restore_verification_plan(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_get_backup_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup), "__call__") as call: - call.return_value = backupvault.Backup() - client.get_backup(request=None) + client.get_restore_verification_plan(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetBackupRequest() - assert args[0] == request_msg + # 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. -def test_update_backup_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_get_restore_verification_plan_rest_required_fields( + request_type=restore_verification_plan.GetRestoreVerificationPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_backup), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateBackupRequest() - assert args[0] == request_msg + default_values = getattr( + transport_class._BaseGetRestoreVerificationPlan, + "_BaseGetRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["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. -def test_delete_backup_empty_call_grpc(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # 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) + # Designate an appropriate value for the returned response. + return_value = restore_verification_plan.RestoreVerificationPlan() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.DeleteBackupRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = restore_verification_plan.RestoreVerificationPlan.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_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_restore_backup_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._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, and fake the request. - with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.restore_backup(request=None) + response = client.get_restore_verification_plan(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.RestoreBackupRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_backup_plan_empty_call_grpc(): +def test_get_restore_verification_plan_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_backup_plan), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup_plan(request=None) + # 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 = restore_verification_plan.RestoreVerificationPlan() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.CreateBackupPlanRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_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_update_backup_plan_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = restore_verification_plan.RestoreVerificationPlan.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup_plan(request=None) + client.get_restore_verification_plan(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.UpdateBackupPlanRequest() - assert args[0] == request_msg + # 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/*/restoreVerificationPlans/*}" + % client.transport._host, + args[1], + ) -# 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_plan_empty_call_grpc(): +def test_get_restore_verification_plan_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: - call.return_value = backupplan.BackupPlan() - client.get_backup_plan(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_restore_verification_plan( + restore_verification_plan.GetRestoreVerificationPlanRequest(), + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.GetBackupPlanRequest() - assert args[0] == request_msg +def test_list_restore_verification_plans_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="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_list_backup_plans_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" - ) as call: - call.return_value = backupplan.ListBackupPlansResponse() - client.list_backup_plans(request=None) + # Ensure method has been cached + assert ( + client._transport.list_restore_verification_plans + in client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.ListBackupPlansRequest() - assert args[0] == request_msg + # 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_restore_verification_plans + ] = mock_rpc + request = {} + client.list_restore_verification_plans(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_plan_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup_plan(request=None) + client.list_restore_verification_plans(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.DeleteBackupPlanRequest() - assert args[0] == request_msg + # 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. -def test_get_backup_plan_revision_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_list_restore_verification_plans_rest_required_fields( + request_type=restore_verification_plan.ListRestoreVerificationPlansRequest, +): + transport_class = transports.BackupDRRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_backup_plan_revision), "__call__" - ) as call: - call.return_value = backupplan.BackupPlanRevision() - client.get_backup_plan_revision(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.GetBackupPlanRevisionRequest() - assert args[0] == request_msg + default_values = getattr( + transport_class._BaseListRestoreVerificationPlans, + "_BaseListRestoreVerificationPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_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_backup_plan_revisions_empty_call_grpc(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_revisions), "__call__" - ) as call: - call.return_value = backupplan.ListBackupPlanRevisionsResponse() - client.list_backup_plan_revisions(request=None) + # Designate an appropriate value for the returned response. + return_value = restore_verification_plan.ListRestoreVerificationPlansResponse() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.ListBackupPlanRevisionsRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_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_create_backup_plan_association_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.create_backup_plan_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup_plan_association(request=None) + response = client.list_restore_verification_plans(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_backup_plan_association_empty_call_grpc(): +def test_list_restore_verification_plans_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup_plan_association(request=None) + # 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 = restore_verification_plan.ListRestoreVerificationPlansResponse() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() - assert args[0] == request_msg + # 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) -# 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_plan_association_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" - ) as call: - call.return_value = backupplanassociation.BackupPlanAssociation() - client.get_backup_plan_association(request=None) + client.list_restore_verification_plans(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.GetBackupPlanAssociationRequest() - assert args[0] == request_msg + # 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/*}/restoreVerificationPlans" + % client.transport._host, + args[1], + ) -# 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_plan_associations_empty_call_grpc(): +def test_list_restore_verification_plans_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_associations), "__call__" - ) as call: - call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() - client.list_backup_plan_associations(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_restore_verification_plans( + restore_verification_plan.ListRestoreVerificationPlansRequest(), + parent="parent_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_fetch_backup_plan_associations_for_resource_type_empty_call_grpc(): +def test_list_restore_verification_plans_rest_pager(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", - ) as call: - call.return_value = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + # 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 = ( + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="abc", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[], + next_page_token="def", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + ], + next_page_token="ghi", + ), + restore_verification_plan.ListRestoreVerificationPlansResponse( + restore_verification_plans=[ + restore_verification_plan.RestoreVerificationPlan(), + restore_verification_plan.RestoreVerificationPlan(), + ], + ), ) - client.fetch_backup_plan_associations_for_resource_type(request=None) + # Two responses for two calls + response = response + response - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + # Wrap the values into proper Response objs + response = tuple( + restore_verification_plan.ListRestoreVerificationPlansResponse.to_json(x) + for x in response ) - assert args[0] == request_msg + 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"} -# 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_plan_association_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + pager = client.list_restore_verification_plans(request=sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan_association), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup_plan_association(request=None) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() - assert args[0] == request_msg + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, restore_verification_plan.RestoreVerificationPlan) + for i in results + ) + pages = list( + client.list_restore_verification_plans(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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_trigger_backup_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.trigger_backup(request=None) +def test_delete_restore_verification_plan_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.TriggerBackupRequest() - assert args[0] == request_msg + # 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_restore_verification_plan + in client._transport._wrapped_methods + ) -# 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_data_source_reference_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # 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_restore_verification_plan + ] = mock_rpc - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" - ) as call: - call.return_value = datasourcereference.DataSourceReference() - client.get_data_source_reference(request=None) + request = {} + client.delete_restore_verification_plan(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasourcereference.GetDataSourceReferenceRequest() - assert args[0] == request_msg + # 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() -# 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_data_source_references_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + client.delete_restore_verification_plan(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" - ) as call: - call.return_value = datasourcereference.ListDataSourceReferencesResponse() - client.list_data_source_references(request=None) + # 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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasourcereference.ListDataSourceReferencesRequest() - assert args[0] == request_msg +def test_delete_restore_verification_plan_rest_required_fields( + request_type=restore_verification_plan.DeleteRestoreVerificationPlanRequest, +): + transport_class = transports.BackupDRRestTransport -# 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_fetch_data_source_references_for_resource_type_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", - ) as call: - call.return_value = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() - ) - client.fetch_data_source_references_for_resource_type(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() - ) - assert args[0] == request_msg - + # verify fields with default values are dropped -# 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_initialize_service_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + default_values = getattr( + transport_class._BaseDeleteRestoreVerificationPlan, + "_BaseDeleteRestoreVerificationPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.initialize_service), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.initialize_service(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.InitializeServiceRequest() - assert args[0] == request_msg + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "requestId", + ) + ) + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["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. -def test_create_auto_protection_policy_empty_call_grpc(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_auto_protection_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() - assert args[0] == request_msg + # 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) -# 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_auto_protection_policies_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" - ) as call: - call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() - client.list_auto_protection_policies(request=None) + response = client.delete_restore_verification_plan(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_auto_protection_policy_empty_call_grpc(): +def test_delete_restore_verification_plan_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_auto_protection_policy), "__call__" - ) as call: - call.return_value = autoprotectionpolicy.AutoProtectionPolicy() - client.get_auto_protection_policy(request=None) + # 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") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_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_update_auto_protection_policy_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # 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"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_auto_protection_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_auto_protection_policy(request=None) + client.delete_restore_verification_plan(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() - assert args[0] == request_msg + # 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/*/restoreVerificationPlans/*}" + % client.transport._host, + args[1], + ) -# 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_auto_protection_policy_empty_call_grpc(): +def test_delete_restore_verification_plan_rest_flattened_error(transport: str = "rest"): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_auto_protection_policy), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_auto_protection_policy(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_restore_verification_plan( + restore_verification_plan.DeleteRestoreVerificationPlanRequest(), + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() - assert args[0] == request_msg +def test_create_backup_vault_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="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_create_auto_protection_policy_binding_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy_binding), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_auto_protection_policy_binding(request=None) + # Ensure method has been cached + assert ( + client._transport.create_backup_vault in client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + # 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_backup_vault] = ( + mock_rpc ) - assert args[0] == request_msg + request = {} + client.create_backup_vault(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_get_auto_protection_policy_binding_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_auto_protection_policy_binding), "__call__" - ) as call: - call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() - client.get_auto_protection_policy_binding(request=None) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() - ) - assert args[0] == request_msg + client.create_backup_vault(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. -def test_list_auto_protection_policy_bindings_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), "__call__" - ) as call: - call.return_value = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() - ) - client.list_auto_protection_policy_bindings(request=None) +def test_create_backup_vault_rest_required_fields( + request_type=backupvault.CreateBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() - ) - assert args[0] == request_msg + request_init = {} + request_init["parent"] = "" + request_init["backup_vault_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 "backupVaultId" not in jsonified_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_list_applied_auto_protection_policies_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + default_values = getattr( + transport_class._BaseCreateBackupVault, + "_BaseCreateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" - ) as call: - call.return_value = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() - ) - client.list_applied_auto_protection_policies(request=None) + # verify required fields with default values are now present + assert "backupVaultId" in jsonified_request + assert jsonified_request["backupVaultId"] == request_init["backup_vault_id"] - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + jsonified_request["parent"] = "parent_value" + jsonified_request["backupVaultId"] = "backup_vault_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backupVaultId", + "requestId", + "validateOnly", ) - assert args[0] == request_msg + ) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupVaultId" in jsonified_request + assert jsonified_request["backupVaultId"] == "backup_vault_id_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_initiate_delete_auto_protection_policy_binding_empty_call_grpc(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.initiate_delete_auto_protection_policy_binding), - "__call__", - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.initiate_delete_auto_protection_policy_binding(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() - assert args[0] == request_msg + # 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) -# 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_binding_matching_resource_empty_call_grpc(): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.get_binding_matching_resource), "__call__" - ) as call: - call.return_value = bindingmatchingresource.BindingMatchingResource() - client.get_binding_matching_resource(request=None) + response = client.create_backup_vault(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest() - assert args[0] == request_msg + expected_params = [ + ( + "backupVaultId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_binding_matching_resources_empty_call_grpc(): +def test_create_backup_vault_rest_flattened(): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), "__call__" - ) as call: - call.return_value = ( - bindingmatchingresource.ListBindingMatchingResourcesResponse() - ) - client.list_binding_matching_resources(request=None) + # 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") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() - assert args[0] == request_msg + # 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", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", + ) + mock_args.update(sample_request) -def test_transport_kind_grpc_asyncio(): - transport = BackupDRAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + # 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_backup_vault(**mock_args) -def test_initialize_client_w_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # 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/*}/backupVaults" + % client.transport._host, + args[1], + ) -# 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_management_servers_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_create_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_management_servers), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupdr.ListManagementServersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_backup_vault( + backupvault.CreateBackupVaultRequest(), + parent="parent_value", + backup_vault=backupvault.BackupVault(name="name_value"), + backup_vault_id="backup_vault_id_value", ) - await client.list_management_servers(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.ListManagementServersRequest() - assert args[0] == request_msg +def test_list_backup_vaults_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# 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_management_server_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_management_server), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupdr.ManagementServer( - name="name_value", - description="description_value", - type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, - state=backupdr.ManagementServer.InstanceState.CREATING, - etag="etag_value", - oauth2_client_id="oauth2_client_id_value", - ba_proxy_uri=["ba_proxy_uri_value"], - satisfies_pzi=True, - ) + # Ensure method has been cached + assert ( + client._transport.list_backup_vaults in client._transport._wrapped_methods ) - await client.get_management_server(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.GetManagementServerRequest() - assert args[0] == request_msg + # 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_vaults] = ( + mock_rpc + ) + request = {} + client.list_backup_vaults(request) -# 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_management_server_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_management_server), "__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_management_server(request=None) + client.list_backup_vaults(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.CreateManagementServerRequest() - assert args[0] == request_msg + # 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_delete_management_server_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_backup_vaults_rest_required_fields( + request_type=backupvault.ListBackupVaultsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_management_server), "__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_management_server(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.DeleteManagementServerRequest() - assert args[0] == request_msg + default_values = getattr( + transport_class._BaseListBackupVaults, + "_BaseListBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -# 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_backup_vault_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + jsonified_request["parent"] = "parent_value" - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_backup_vault), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "view", ) - await client.create_backup_vault(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.CreateBackupVaultRequest() - assert args[0] == request_msg + ) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_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_list_backup_vaults_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_vaults), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListBackupVaultsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_backup_vaults(request=None) + # Designate an appropriate value for the returned response. + return_value = backupvault.ListBackupVaultsResponse() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListBackupVaultsRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.ListBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_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_fetch_usable_backup_vaults_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.fetch_usable_backup_vaults), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchUsableBackupVaultsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.fetch_usable_backup_vaults(request=None) + response = client.list_backup_vaults(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.FetchUsableBackupVaultsRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_vault_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_backup_vaults_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.BackupVault( - name="name_value", - description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, - deletable=True, - etag="etag_value", - state=backupvault.BackupVault.State.CREATING, - backup_count=1278, - service_account="service_account_value", - total_stored_bytes=1946, - uid="uid_value", - access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, - ) - ) - await client.get_backup_vault(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetBackupVaultRequest() - assert args[0] == request_msg - + # 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 = backupvault.ListBackupVaultsResponse() -# 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_backup_vault_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_vault), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", ) - await client.update_backup_vault(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateBackupVaultRequest() - assert args[0] == request_msg + 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 = backupvault.ListBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-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_delete_backup_vault_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.list_backup_vaults(**mock_args) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_vault), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # 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/*}/backupVaults" + % client.transport._host, + args[1], ) - await client.delete_backup_vault(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.DeleteBackupVaultRequest() - 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_data_sources_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_backup_vaults_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_data_sources), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.ListDataSourcesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backup_vaults( + backupvault.ListBackupVaultsRequest(), + parent="parent_value", ) - await client.list_data_sources(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListDataSourcesRequest() - 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_data_source_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_list_backup_vaults_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.DataSource( - name="name_value", - state=backupvault.DataSource.State.CREATING, - backup_count=1278, - etag="etag_value", - total_stored_bytes=1946, - config_state=backupvault.BackupConfigState.ACTIVE, - backup_blocked_by_vault_access_restriction=True, - ) + # 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 = ( + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), ) - await client.get_data_source(request=None) + # Two responses for two calls + response = response + response - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetDataSourceRequest() - assert args[0] == request_msg + # Wrap the values into proper Response objs + response = tuple( + backupvault.ListBackupVaultsResponse.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"} -# 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_data_source_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + pager = client.list_backup_vaults(request=sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_data_source), "__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_data_source(request=None) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateDataSourceRequest() - assert args[0] == request_msg + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.BackupVault) for i in results) + pages = list(client.list_backup_vaults(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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 = BackupDRAsyncClient( - 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( - backupvault.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) +def test_fetch_usable_backup_vaults_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - await client.list_backups(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.ListBackupsRequest() - assert args[0] == request_msg + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# 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_fetch_backups_for_resource_type_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert ( + client._transport.fetch_usable_backup_vaults + in client._transport._wrapped_methods + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_backups_for_resource_type), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupvault.FetchBackupsForResourceTypeResponse( - next_page_token="next_page_token_value", - ) + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - await client.fetch_backups_for_resource_type(request=None) + client._transport._wrapped_methods[ + client._transport.fetch_usable_backup_vaults + ] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.FetchBackupsForResourceTypeRequest() - assert args[0] == request_msg + request = {} + client.fetch_usable_backup_vaults(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# 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 = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.fetch_usable_backup_vaults(request) - # 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( - backupvault.Backup( - name="name_value", - description="description_value", - backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, - etag="etag_value", - state=backupvault.Backup.State.CREATING, - backup_type=backupvault.Backup.BackupType.SCHEDULED, - resource_size_bytes=2056, - satisfies_pzs=True, - satisfies_pzi=True, - kms_key_versions=["kms_key_versions_value"], - ) - ) - await client.get_backup(request=None) + # 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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.GetBackupRequest() - assert args[0] == request_msg +def test_fetch_usable_backup_vaults_rest_required_fields( + request_type=backupvault.FetchUsableBackupVaultsRequest, +): + transport_class = transports.BackupDRRestTransport -# 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_backup_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_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.update_backup(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.UpdateBackupRequest() - assert args[0] == request_msg + default_values = getattr( + transport_class._BaseFetchUsableBackupVaults, + "_BaseFetchUsableBackupVaults__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -# 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 = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + jsonified_request["parent"] = "parent_value" - # 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") + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", ) - await client.delete_backup(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.DeleteBackupRequest() - assert args[0] == request_msg + ) + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_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_restore_backup_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.restore_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.restore_backup(request=None) + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchUsableBackupVaultsResponse() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupvault.RestoreBackupRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_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_create_backup_plan_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.create_backup_plan), "__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_backup_plan(request=None) + response = client.fetch_usable_backup_vaults(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.CreateBackupPlanRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_backup_plan_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_fetch_usable_backup_vaults_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan), "__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_backup_plan(request=None) + # 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 = backupvault.FetchUsableBackupVaultsResponse() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.UpdateBackupPlanRequest() - assert args[0] == request_msg + # 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) -# 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_plan_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.FetchUsableBackupVaultsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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, and fake the request. - with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlan( - name="name_value", - description="description_value", - max_custom_on_demand_retention_days=3723, - state=backupplan.BackupPlan.State.CREATING, - resource_type="resource_type_value", - etag="etag_value", - backup_vault="backup_vault_value", - backup_vault_service_account="backup_vault_service_account_value", - log_retention_days=1929, - supported_resource_types=["supported_resource_types_value"], - revision_id="revision_id_value", - revision_name="revision_name_value", - ) - ) - await client.get_backup_plan(request=None) + client.fetch_usable_backup_vaults(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.GetBackupPlanRequest() - assert args[0] == request_msg + # 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/*}/backupVaults:fetchUsable" + % client.transport._host, + args[1], + ) -# 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_plans_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_fetch_usable_backup_vaults_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plans), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlansResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_usable_backup_vaults( + backupvault.FetchUsableBackupVaultsRequest(), + parent="parent_value", ) - await client.list_backup_plans(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.ListBackupPlansRequest() - 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_plan_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_fetch_usable_backup_vaults_rest_pager(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - 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: + # 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 = ( + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + next_page_token="abc", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[], + next_page_token="def", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + ], + next_page_token="ghi", + ), + backupvault.FetchUsableBackupVaultsResponse( + backup_vaults=[ + backupvault.BackupVault(), + backupvault.BackupVault(), + ], + ), ) - await client.delete_backup_plan(request=None) + # Two responses for two calls + response = response + response - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.DeleteBackupPlanRequest() - assert args[0] == request_msg + # Wrap the values into proper Response objs + response = tuple( + backupvault.FetchUsableBackupVaultsResponse.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"} -# 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_plan_revision_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + pager = client.fetch_usable_backup_vaults(request=sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_backup_plan_revision), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.BackupPlanRevision( - name="name_value", - revision_id="revision_id_value", - state=backupplan.BackupPlanRevision.State.CREATING, - ) - ) - await client.get_backup_plan_revision(request=None) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.GetBackupPlanRevisionRequest() - assert args[0] == request_msg + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, backupvault.BackupVault) for i in results) + pages = list(client.fetch_usable_backup_vaults(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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_plan_revisions_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_revisions), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplan.ListBackupPlanRevisionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) +def test_get_backup_vault_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - await client.list_backup_plan_revisions(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplan.ListBackupPlanRevisionsRequest() - assert args[0] == request_msg + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# 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_backup_plan_association_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert client._transport.get_backup_vault in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_backup_plan_association), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # 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_vault] = ( + mock_rpc ) - await client.create_backup_plan_association(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() - assert args[0] == request_msg + request = {} + client.get_backup_vault(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# 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_backup_plan_association_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.get_backup_vault(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_backup_plan_association), "__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_backup_plan_association(request=None) + # 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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() - assert args[0] == request_msg +def test_get_backup_vault_rest_required_fields( + request_type=backupvault.GetBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport -# 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_plan_association_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + 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) ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_backup_plan_association), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.BackupPlanAssociation( - name="name_value", - resource_type="resource_type_value", - resource="resource_value", - backup_plan="backup_plan_value", - state=backupplanassociation.BackupPlanAssociation.State.CREATING, - data_source="data_source_value", - backup_plan_revision_id="backup_plan_revision_id_value", - backup_plan_revision_name="backup_plan_revision_name_value", - auto_protection_policy_binding="auto_protection_policy_binding_value", - ) - ) - await client.get_backup_plan_association(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.GetBackupPlanAssociationRequest() - assert args[0] == request_msg + default_values = getattr( + transport_class._BaseGetBackupVault, + "_BaseGetBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -# 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_plan_associations_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_backup_plan_associations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.ListBackupPlanAssociationsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_backup_plan_associations(request=None) + # Designate an appropriate value for the returned response. + return_value = backupvault.BackupVault() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.BackupVault.pb(return_value) + json_return_value = json_format.MessageToJson(return_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_fetch_backup_plan_associations_for_resource_type_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.fetch_backup_plan_associations_for_resource_type), - "__call__", - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( - next_page_token="next_page_token_value", - ) - ) - await client.fetch_backup_plan_associations_for_resource_type(request=None) + response = client.get_backup_vault(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() - ) - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_plan_association_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_get_backup_vault_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_backup_plan_association), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # 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 = backupvault.BackupVault() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", ) - await client.delete_backup_plan_association(request=None) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() - assert args[0] == request_msg + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = backupvault.BackupVault.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_vault(**mock_args) -# 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_trigger_backup_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # 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/*/backupVaults/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.trigger_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") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup_vault( + backupvault.GetBackupVaultRequest(), + name="name_value", ) - await client.trigger_backup(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupplanassociation.TriggerBackupRequest() - assert args[0] == request_msg +def test_update_backup_vault_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# 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_data_source_reference_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_data_source_reference), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.DataSourceReference( - name="name_value", - data_source="data_source_value", - data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, - data_source_backup_count=2535, - total_stored_bytes=1946, - ) + # Ensure method has been cached + assert ( + client._transport.update_backup_vault in client._transport._wrapped_methods ) - await client.get_data_source_reference(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasourcereference.GetDataSourceReferenceRequest() - assert args[0] == request_msg + # 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_backup_vault] = ( + mock_rpc + ) + request = {} + client.update_backup_vault(request) -# 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_data_source_references_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_data_source_references), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.ListDataSourceReferencesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_data_source_references(request=None) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = datasourcereference.ListDataSourceReferencesRequest() - assert args[0] == request_msg + client.update_backup_vault(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_fetch_data_source_references_for_resource_type_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_data_source_references_for_resource_type), - "__call__", - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( - next_page_token="next_page_token_value", - ) - ) - await client.fetch_data_source_references_for_resource_type(request=None) +def test_update_backup_vault_rest_required_fields( + request_type=backupvault.UpdateBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() - ) - assert args[0] == request_msg + 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 -# 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_initialize_service_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + default_values = getattr( + transport_class._BaseUpdateBackupVault, + "_BaseUpdateBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.initialize_service), "__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.initialize_service(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = backupdr.InitializeServiceRequest() - assert args[0] == request_msg + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "forceUpdateAccessRestriction", + "requestId", + "updateMask", + "validateOnly", + ) + ) + # verify required fields with non-default values are left alone -# 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_auto_protection_policy_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy), "__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_auto_protection_policy(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() - assert args[0] == request_msg + # 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) -# 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_auto_protection_policies_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.list_auto_protection_policies), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicy.ListAutoProtectionPoliciesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_auto_protection_policies(request=None) + response = client.update_backup_vault(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_auto_protection_policy_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_backup_vault_rest_flattened(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_auto_protection_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicy.AutoProtectionPolicy( - name="name_value", - description="description_value", - state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, - etag="etag_value", - ) - ) - await client.get_auto_protection_policy(request=None) + # 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") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "backup_vault": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3" + } + } + # get truthy value for each flattened field + mock_args = dict( + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) -# 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_auto_protection_policy_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # 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"} - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_auto_protection_policy), "__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_auto_protection_policy(request=None) + client.update_backup_vault(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() - assert args[0] == request_msg + # 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/{backup_vault.name=projects/*/locations/*/backupVaults/*}" + % client.transport._host, + args[1], + ) -# 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_auto_protection_policy_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_update_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_auto_protection_policy), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_backup_vault( + backupvault.UpdateBackupVaultRequest(), + backup_vault=backupvault.BackupVault(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - await client.delete_auto_protection_policy(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() - assert args[0] == request_msg +def test_delete_backup_vault_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 = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) -# 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_auto_protection_policy_binding_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_auto_protection_policy_binding), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Ensure method has been cached + assert ( + client._transport.delete_backup_vault in client._transport._wrapped_methods ) - await client.create_auto_protection_policy_binding(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + # 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_vault] = ( + mock_rpc ) - assert args[0] == request_msg + request = {} + client.delete_backup_vault(request) -# 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_auto_protection_policy_binding_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_auto_protection_policy_binding), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicybinding.AutoProtectionPolicyBinding( - name="name_value", - description="description_value", - state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, - scope="scope_value", - etag="etag_value", - ) - ) - await client.get_auto_protection_policy_binding(request=None) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() - ) - assert args[0] == request_msg + client.delete_backup_vault(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_auto_protection_policy_bindings_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_auto_protection_policy_bindings), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_auto_protection_policy_bindings(request=None) +def test_delete_backup_vault_rest_required_fields( + request_type=backupvault.DeleteBackupVaultRequest, +): + transport_class = transports.BackupDRRestTransport - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = ( - autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() - ) - assert args[0] == request_msg + 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 -# 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_applied_auto_protection_policies_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + default_values = getattr( + transport_class._BaseDeleteBackupVault, + "_BaseDeleteBackupVault__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_applied_auto_protection_policies), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_applied_auto_protection_policies(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allowMissing", + "etag", + "force", + "ignoreBackupPlanReferences", + "requestId", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_vault(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_vault_rest_flattened(): + client = BackupDRClient( + 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/backupVaults/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_backup_vault(**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/*/backupVaults/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_vault_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_vault( + backupvault.DeleteBackupVaultRequest(), + name="name_value", + ) + + +def test_list_data_sources_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 = BackupDRClient( + 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_data_sources 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_data_sources] = ( + mock_rpc + ) + + request = {} + client.list_data_sources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_sources(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_data_sources_rest_required_fields( + request_type=backupvault.ListDataSourcesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListDataSources, + "_BaseListDataSources__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.ListDataSourcesResponse() + # 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 = backupvault.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_data_sources(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_data_sources_rest_flattened(): + client = BackupDRClient( + 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 = backupvault.ListDataSourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/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 = backupvault.ListDataSourcesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_sources(**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/*/backupVaults/*}/dataSources" + % client.transport._host, + args[1], + ) + + +def test_list_data_sources_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_sources( + backupvault.ListDataSourcesRequest(), + parent="parent_value", + ) + + +def test_list_data_sources_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + backupvault.DataSource(), + ], + next_page_token="abc", + ), + backupvault.ListDataSourcesResponse( + data_sources=[], + next_page_token="def", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + ], + next_page_token="ghi", + ), + backupvault.ListDataSourcesResponse( + data_sources=[ + backupvault.DataSource(), + backupvault.DataSource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.ListDataSourcesResponse.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/backupVaults/sample3" + } + + pager = client.list_data_sources(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, backupvault.DataSource) for i in results) + + pages = list(client.list_data_sources(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_data_source_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 = BackupDRClient( + 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_data_source 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_data_source] = mock_rpc + + request = {} + client.get_data_source(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source(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_data_source_rest_required_fields( + request_type=backupvault.GetDataSourceRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetDataSource, + "_BaseGetDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.DataSource() + # 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 = backupvault.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_data_source(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_data_source_rest_flattened(): + client = BackupDRClient( + 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 = backupvault.DataSource() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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 = backupvault.DataSource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_source(**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/*/backupVaults/*/dataSources/*}" + % client.transport._host, + args[1], + ) + + +def test_get_data_source_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_source( + backupvault.GetDataSourceRequest(), + name="name_value", + ) + + +def test_update_data_source_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 = BackupDRClient( + 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_data_source 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_data_source] = ( + mock_rpc + ) + + request = {} + client.update_data_source(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_data_source(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_data_source_rest_required_fields( + request_type=backupvault.UpdateDataSourceRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateDataSource, + "_BaseUpdateDataSource__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allowMissing", + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_data_source(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_data_source_rest_flattened(): + client = BackupDRClient( + 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 = { + "data_source": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_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_data_source(**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/{data_source.name=projects/*/locations/*/backupVaults/*/dataSources/*}" + % client.transport._host, + args[1], + ) + + +def test_update_data_source_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_source( + backupvault.UpdateDataSourceRequest(), + data_source=backupvault.DataSource( + data_source_gcp_resource=backupvault.DataSourceGcpResource( + compute_instance_datasource_properties=backupvault_gce.ComputeInstanceDataSourceProperties( + name="name_value" + ) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = BackupDRClient( + 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=backupvault.ListBackupsRequest): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBackups, + "_BaseListBackups__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.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 = backupvault.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_flattened(): + client = BackupDRClient( + 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 = backupvault.ListBackupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/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 = backupvault.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/*/backupVaults/*/dataSources/*}/backups" + % client.transport._host, + args[1], + ) + + +def test_list_backups_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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( + backupvault.ListBackupsRequest(), + parent="parent_value", + ) + + +def test_list_backups_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.ListBackupsResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(backupvault.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/backupVaults/sample3/dataSources/sample4" + } + + 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, backupvault.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_fetch_backups_for_resource_type_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 = BackupDRClient( + 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.fetch_backups_for_resource_type + 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.fetch_backups_for_resource_type + ] = mock_rpc + + request = {} + client.fetch_backups_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_backups_for_resource_type(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_fetch_backups_for_resource_type_rest_required_fields( + request_type=backupvault.FetchBackupsForResourceTypeRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["resource_type"] = "" + 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 "resourceType" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchBackupsForResourceType, + "_BaseFetchBackupsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == request_init["resource_type"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["resourceType"] = "resource_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "resourceType", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.FetchBackupsForResourceTypeResponse() + # 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 = backupvault.FetchBackupsForResourceTypeResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_backups_for_resource_type(request) + + expected_params = [ + ( + "resourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_backups_for_resource_type_rest_flattened(): + client = BackupDRClient( + 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 = backupvault.FetchBackupsForResourceTypeResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + resource_type="resource_type_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 = backupvault.FetchBackupsForResourceTypeResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_backups_for_resource_type(**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/*/backupVaults/*/dataSources/*}/backups:fetchForResourceType" + % client.transport._host, + args[1], + ) + + +def test_fetch_backups_for_resource_type_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.fetch_backups_for_resource_type( + backupvault.FetchBackupsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_backups_for_resource_type_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + backupvault.Backup(), + ], + next_page_token="abc", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[], + next_page_token="def", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + ], + next_page_token="ghi", + ), + backupvault.FetchBackupsForResourceTypeResponse( + backups=[ + backupvault.Backup(), + backupvault.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupvault.FetchBackupsForResourceTypeResponse.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/backupVaults/sample3/dataSources/sample4" + } + + pager = client.fetch_backups_for_resource_type(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, backupvault.Backup) for i in results) + + pages = list( + client.fetch_backups_for_resource_type(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 = BackupDRClient( + 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=backupvault.GetBackupRequest): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBackup, + "_BaseGetBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupvault.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 = backupvault.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_flattened(): + client = BackupDRClient( + 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 = backupvault.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/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 = backupvault.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/*/backupVaults/*/dataSources/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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( + backupvault.GetBackupRequest(), + name="name_value", + ) + + +def test_update_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 = BackupDRClient( + 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_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.update_backup] = mock_rpc + + request = {} + client.update_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.update_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_update_backup_rest_required_fields( + request_type=backupvault.UpdateBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateBackup, + "_BaseUpdateBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_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_update_backup_rest_flattened(): + client = BackupDRClient( + 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 = { + "backup": { + "name": "projects/sample1/locations/sample2/backupVaults/sample3/dataSources/sample4/backups/sample5" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_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_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/{backup.name=projects/*/locations/*/backupVaults/*/dataSources/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup( + backupvault.UpdateBackupRequest(), + backup=backupvault.Backup( + compute_instance_backup_properties=backupvault_gce.ComputeInstanceBackupProperties( + description="description_value" + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = BackupDRClient( + 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=backupvault.DeleteBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteBackup, + "_BaseDeleteBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_flattened(): + client = BackupDRClient( + 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/backupVaults/sample3/dataSources/sample4/backups/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_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/*/backupVaults/*/dataSources/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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( + backupvault.DeleteBackupRequest(), + name="name_value", + ) + + +def test_restore_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 = BackupDRClient( + 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.restore_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.restore_backup] = mock_rpc + + request = {} + client.restore_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.restore_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_restore_backup_rest_required_fields( + request_type=backupvault.RestoreBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseRestoreBackup, + "_BaseRestoreBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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.restore_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_restore_backup_rest_flattened(): + client = BackupDRClient( + 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/backupVaults/sample3/dataSources/sample4/backups/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.restore_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/*/backupVaults/*/dataSources/*/backups/*}:restore" + % client.transport._host, + args[1], + ) + + +def test_restore_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.restore_backup( + backupvault.RestoreBackupRequest(), + name="name_value", + ) + + +def test_create_backup_plan_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 = BackupDRClient( + 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_backup_plan 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_backup_plan] = ( + mock_rpc + ) + + request = {} + client.create_backup_plan(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_backup_plan(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_backup_plan_rest_required_fields( + request_type=backupplan.CreateBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_plan_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 "backupPlanId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateBackupPlan, + "_BaseCreateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupPlanId" in jsonified_request + assert jsonified_request["backupPlanId"] == request_init["backup_plan_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["backupPlanId"] = "backup_plan_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backupPlanId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupPlanId" in jsonified_request + assert jsonified_request["backupPlanId"] == "backup_plan_id_value" + + client = BackupDRClient( + 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_backup_plan(request) + + expected_params = [ + ( + "backupPlanId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_backup_plan_rest_flattened(): + client = BackupDRClient( + 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", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_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_backup_plan(**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/*}/backupPlans" + % client.transport._host, + args[1], + ) + + +def test_create_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_plan( + backupplan.CreateBackupPlanRequest(), + parent="parent_value", + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + backup_plan_id="backup_plan_id_value", + ) + + +def test_update_backup_plan_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 = BackupDRClient( + 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_backup_plan 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_backup_plan] = ( + mock_rpc + ) + + request = {} + client.update_backup_plan(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_backup_plan(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_backup_plan_rest_required_fields( + request_type=backupplan.UpdateBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateBackupPlan, + "_BaseUpdateBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_backup_plan(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_backup_plan_rest_flattened(): + client = BackupDRClient( + 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 = { + "backup_plan": { + "name": "projects/sample1/locations/sample2/backupPlans/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + 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_backup_plan(**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/{backup_plan.name=projects/*/locations/*/backupPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_plan( + backupplan.UpdateBackupPlanRequest(), + backup_plan=backupplan.BackupPlan( + disk_backup_plan_properties=backupplan.DiskBackupPlanProperties( + guest_flush=True + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_backup_plan_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 = BackupDRClient( + 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_plan 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_plan] = mock_rpc + + request = {} + client.get_backup_plan(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan(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_plan_rest_required_fields( + request_type=backupplan.GetBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBackupPlan, + "_BaseGetBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlan() + # 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 = backupplan.BackupPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan(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_plan_rest_flattened(): + client = BackupDRClient( + 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 = backupplan.BackupPlan() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlans/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 = backupplan.BackupPlan.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan(**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/*/backupPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan( + backupplan.GetBackupPlanRequest(), + name="name_value", + ) + + +def test_list_backup_plans_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 = BackupDRClient( + 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_plans 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_plans] = ( + mock_rpc + ) + + request = {} + client.list_backup_plans(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plans(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_plans_rest_required_fields( + request_type=backupplan.ListBackupPlansRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBackupPlans, + "_BaseListBackupPlans__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlansResponse() + # 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 = backupplan.ListBackupPlansResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plans(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_plans_rest_flattened(): + client = BackupDRClient( + 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 = backupplan.ListBackupPlansResponse() + + # 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 = backupplan.ListBackupPlansResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plans(**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/*}/backupPlans" + % client.transport._host, + args[1], + ) + + +def test_list_backup_plans_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plans( + backupplan.ListBackupPlansRequest(), + parent="parent_value", + ) + + +def test_list_backup_plans_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[], + next_page_token="def", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlansResponse( + backup_plans=[ + backupplan.BackupPlan(), + backupplan.BackupPlan(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplan.ListBackupPlansResponse.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_plans(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, backupplan.BackupPlan) for i in results) + + pages = list(client.list_backup_plans(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_backup_plan_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 = BackupDRClient( + 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_plan 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_plan] = ( + mock_rpc + ) + + request = {} + client.delete_backup_plan(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_plan(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_plan_rest_required_fields( + request_type=backupplan.DeleteBackupPlanRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteBackupPlan, + "_BaseDeleteBackupPlan__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("requestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_plan(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_plan_rest_flattened(): + client = BackupDRClient( + 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/backupPlans/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_backup_plan(**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/*/backupPlans/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_plan_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan( + backupplan.DeleteBackupPlanRequest(), + name="name_value", + ) + + +def test_get_backup_plan_revision_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 = BackupDRClient( + 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_plan_revision + 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_plan_revision + ] = mock_rpc + + request = {} + client.get_backup_plan_revision(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan_revision(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_plan_revision_rest_required_fields( + request_type=backupplan.GetBackupPlanRevisionRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBackupPlanRevision, + "_BaseGetBackupPlanRevision__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.BackupPlanRevision() + # 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 = backupplan.BackupPlanRevision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan_revision(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_plan_revision_rest_flattened(): + client = BackupDRClient( + 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 = backupplan.BackupPlanRevision() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlans/sample3/revisions/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 = backupplan.BackupPlanRevision.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan_revision(**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/*/backupPlans/*/revisions/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_plan_revision_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_revision( + backupplan.GetBackupPlanRevisionRequest(), + name="name_value", + ) + + +def test_list_backup_plan_revisions_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 = BackupDRClient( + 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_plan_revisions + 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_plan_revisions + ] = mock_rpc + + request = {} + client.list_backup_plan_revisions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plan_revisions(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_plan_revisions_rest_required_fields( + request_type=backupplan.ListBackupPlanRevisionsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBackupPlanRevisions, + "_BaseListBackupPlanRevisions__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplan.ListBackupPlanRevisionsResponse() + # 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 = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan_revisions(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_plan_revisions_rest_flattened(): + client = BackupDRClient( + 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 = backupplan.ListBackupPlanRevisionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupPlans/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 = backupplan.ListBackupPlanRevisionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan_revisions(**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/*/backupPlans/*}/revisions" + % client.transport._host, + args[1], + ) + + +def test_list_backup_plan_revisions_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_revisions( + backupplan.ListBackupPlanRevisionsRequest(), + parent="parent_value", + ) + + +def test_list_backup_plan_revisions_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + next_page_token="abc", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[], + next_page_token="def", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + ], + next_page_token="ghi", + ), + backupplan.ListBackupPlanRevisionsResponse( + backup_plan_revisions=[ + backupplan.BackupPlanRevision(), + backupplan.BackupPlanRevision(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplan.ListBackupPlanRevisionsResponse.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/backupPlans/sample3" + } + + pager = client.list_backup_plan_revisions(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, backupplan.BackupPlanRevision) for i in results) + + pages = list(client.list_backup_plan_revisions(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_create_backup_plan_association_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 = BackupDRClient( + 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_backup_plan_association + 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_backup_plan_association + ] = mock_rpc + + request = {} + client.create_backup_plan_association(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_backup_plan_association(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_backup_plan_association_rest_required_fields( + request_type=backupplanassociation.CreateBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["backup_plan_association_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 "backupPlanAssociationId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateBackupPlanAssociation, + "_BaseCreateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "backupPlanAssociationId" in jsonified_request + assert ( + jsonified_request["backupPlanAssociationId"] + == request_init["backup_plan_association_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["backupPlanAssociationId"] = "backup_plan_association_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "backupPlanAssociationId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "backupPlanAssociationId" in jsonified_request + assert ( + jsonified_request["backupPlanAssociationId"] + == "backup_plan_association_id_value" + ) + + client = BackupDRClient( + 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_backup_plan_association(request) + + expected_params = [ + ( + "backupPlanAssociationId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_backup_plan_association_rest_flattened(): + client = BackupDRClient( + 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", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + backup_plan_association_id="backup_plan_association_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_backup_plan_association(**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/*}/backupPlanAssociations" + % client.transport._host, + args[1], + ) + + +def test_create_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_plan_association( + backupplanassociation.CreateBackupPlanAssociationRequest(), + parent="parent_value", + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + backup_plan_association_id="backup_plan_association_id_value", + ) + + +def test_update_backup_plan_association_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 = BackupDRClient( + 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_backup_plan_association + 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_backup_plan_association + ] = mock_rpc + + request = {} + client.update_backup_plan_association(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_backup_plan_association(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_backup_plan_association_rest_required_fields( + request_type=backupplanassociation.UpdateBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateBackupPlanAssociation, + "_BaseUpdateBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_backup_plan_association(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_backup_plan_association_rest_flattened(): + client = BackupDRClient( + 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 = { + "backup_plan_association": { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + 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_backup_plan_association(**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/{backup_plan_association.name=projects/*/locations/*/backupPlanAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_backup_plan_association( + backupplanassociation.UpdateBackupPlanAssociationRequest(), + backup_plan_association=backupplanassociation.BackupPlanAssociation( + cloud_sql_instance_backup_plan_association_properties=backupvault_cloudsql.CloudSqlInstanceBackupPlanAssociationProperties( + instance_create_time=timestamp_pb2.Timestamp(seconds=751) + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_get_backup_plan_association_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 = BackupDRClient( + 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_plan_association + 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_plan_association + ] = mock_rpc + + request = {} + client.get_backup_plan_association(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_plan_association(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_plan_association_rest_required_fields( + request_type=backupplanassociation.GetBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBackupPlanAssociation, + "_BaseGetBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.BackupPlanAssociation() + # 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 = backupplanassociation.BackupPlanAssociation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan_association(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_plan_association_rest_flattened(): + client = BackupDRClient( + 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 = backupplanassociation.BackupPlanAssociation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupPlanAssociations/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 = backupplanassociation.BackupPlanAssociation.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan_association(**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/*/backupPlanAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_association( + backupplanassociation.GetBackupPlanAssociationRequest(), + name="name_value", + ) + + +def test_list_backup_plan_associations_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 = BackupDRClient( + 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_plan_associations + 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_plan_associations + ] = mock_rpc + + request = {} + client.list_backup_plan_associations(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_plan_associations(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_plan_associations_rest_required_fields( + request_type=backupplanassociation.ListBackupPlanAssociationsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBackupPlanAssociations, + "_BaseListBackupPlanAssociations__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + # 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 = backupplanassociation.ListBackupPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_plan_associations(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_plan_associations_rest_flattened(): + client = BackupDRClient( + 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 = backupplanassociation.ListBackupPlanAssociationsResponse() + + # 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 = backupplanassociation.ListBackupPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_plan_associations(**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/*}/backupPlanAssociations" + % client.transport._host, + args[1], + ) + + +def test_list_backup_plan_associations_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_associations( + backupplanassociation.ListBackupPlanAssociationsRequest(), + parent="parent_value", + ) + + +def test_list_backup_plan_associations_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.ListBackupPlanAssociationsResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplanassociation.ListBackupPlanAssociationsResponse.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_plan_associations(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, backupplanassociation.BackupPlanAssociation) for i in results + ) + + pages = list(client.list_backup_plan_associations(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_backup_plan_associations_for_resource_type_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 = BackupDRClient( + 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.fetch_backup_plan_associations_for_resource_type + 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.fetch_backup_plan_associations_for_resource_type + ] = mock_rpc + + request = {} + client.fetch_backup_plan_associations_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_backup_plan_associations_for_resource_type(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_fetch_backup_plan_associations_for_resource_type_rest_required_fields( + request_type=backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["resource_type"] = "" + 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 "resourceType" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchBackupPlanAssociationsForResourceType, + "_BaseFetchBackupPlanAssociationsForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == request_init["resource_type"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["resourceType"] = "resource_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "resourceType", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + # 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 = backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_backup_plan_associations_for_resource_type(request) + + expected_params = [ + ( + "resourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_backup_plan_associations_for_resource_type_rest_flattened(): + client = BackupDRClient( + 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 = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + + # 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", + resource_type="resource_type_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 = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_backup_plan_associations_for_resource_type(**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/*}/backupPlanAssociations:fetchForResourceType" + % client.transport._host, + args[1], + ) + + +def test_fetch_backup_plan_associations_for_resource_type_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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.fetch_backup_plan_associations_for_resource_type( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_backup_plan_associations_for_resource_type_rest_pager( + transport: str = "rest", +): + client = BackupDRClient( + 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 = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="abc", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[], + next_page_token="def", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + ], + next_page_token="ghi", + ), + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + backup_plan_associations=[ + backupplanassociation.BackupPlanAssociation(), + backupplanassociation.BackupPlanAssociation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse.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.fetch_backup_plan_associations_for_resource_type( + 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, backupplanassociation.BackupPlanAssociation) for i in results + ) + + pages = list( + client.fetch_backup_plan_associations_for_resource_type( + request=sample_request + ).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_backup_plan_association_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 = BackupDRClient( + 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_plan_association + 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_plan_association + ] = mock_rpc + + request = {} + client.delete_backup_plan_association(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_plan_association(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_plan_association_rest_required_fields( + request_type=backupplanassociation.DeleteBackupPlanAssociationRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteBackupPlanAssociation, + "_BaseDeleteBackupPlanAssociation__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "autoProtectionPolicyBinding", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_plan_association(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_plan_association_rest_flattened(): + client = BackupDRClient( + 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/backupPlanAssociations/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_backup_plan_association(**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/*/backupPlanAssociations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_plan_association_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_plan_association( + backupplanassociation.DeleteBackupPlanAssociationRequest(), + name="name_value", + ) + + +def test_trigger_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 = BackupDRClient( + 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.trigger_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.trigger_backup] = mock_rpc + + request = {} + client.trigger_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.trigger_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_trigger_backup_rest_required_fields( + request_type=backupplanassociation.TriggerBackupRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseTriggerBackup, + "_BaseTriggerBackup__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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.trigger_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_trigger_backup_rest_flattened(): + client = BackupDRClient( + 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/backupPlanAssociations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + rule_id="rule_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.trigger_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/*/backupPlanAssociations/*}:triggerBackup" + % client.transport._host, + args[1], + ) + + +def test_trigger_backup_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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.trigger_backup( + backupplanassociation.TriggerBackupRequest(), + name="name_value", + rule_id="rule_id_value", + ) + + +def test_get_data_source_reference_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 = BackupDRClient( + 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_data_source_reference + 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_data_source_reference + ] = mock_rpc + + request = {} + client.get_data_source_reference(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_data_source_reference(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_data_source_reference_rest_required_fields( + request_type=datasourcereference.GetDataSourceReferenceRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetDataSourceReference, + "_BaseGetDataSourceReference__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasourcereference.DataSourceReference() + # 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 = datasourcereference.DataSourceReference.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_data_source_reference(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_data_source_reference_rest_flattened(): + client = BackupDRClient( + 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 = datasourcereference.DataSourceReference() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/dataSourceReferences/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 = datasourcereference.DataSourceReference.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_source_reference(**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/*/dataSourceReferences/*}" + % client.transport._host, + args[1], + ) + + +def test_get_data_source_reference_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_source_reference( + datasourcereference.GetDataSourceReferenceRequest(), + name="name_value", + ) + + +def test_list_data_source_references_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 = BackupDRClient( + 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_data_source_references + 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_data_source_references + ] = mock_rpc + + request = {} + client.list_data_source_references(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_data_source_references(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_data_source_references_rest_required_fields( + request_type=datasourcereference.ListDataSourceReferencesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListDataSourceReferences, + "_BaseListDataSourceReferences__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = datasourcereference.ListDataSourceReferencesResponse() + # 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 = datasourcereference.ListDataSourceReferencesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_data_source_references(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_data_source_references_rest_flattened(): + client = BackupDRClient( + 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 = datasourcereference.ListDataSourceReferencesResponse() + + # 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 = datasourcereference.ListDataSourceReferencesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_data_source_references(**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/*}/dataSourceReferences" + % client.transport._host, + args[1], + ) + + +def test_list_data_source_references_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_data_source_references( + datasourcereference.ListDataSourceReferencesRequest(), + parent="parent_value", + ) + + +def test_list_data_source_references_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.ListDataSourceReferencesResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + datasourcereference.ListDataSourceReferencesResponse.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_data_source_references(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, datasourcereference.DataSourceReference) for i in results + ) + + pages = list(client.list_data_source_references(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_data_source_references_for_resource_type_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 = BackupDRClient( + 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.fetch_data_source_references_for_resource_type + 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.fetch_data_source_references_for_resource_type + ] = mock_rpc + + request = {} + client.fetch_data_source_references_for_resource_type(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_data_source_references_for_resource_type(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_fetch_data_source_references_for_resource_type_rest_required_fields( + request_type=datasourcereference.FetchDataSourceReferencesForResourceTypeRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["resource_type"] = "" + 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 "resourceType" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchDataSourceReferencesForResourceType, + "_BaseFetchDataSourceReferencesForResourceType__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == request_init["resource_type"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["resourceType"] = "resource_type_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "resourceType", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + # 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 = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_data_source_references_for_resource_type(request) + + expected_params = [ + ( + "resourceType", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_data_source_references_for_resource_type_rest_flattened(): + client = BackupDRClient( + 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 = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + + # 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", + resource_type="resource_type_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 = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_data_source_references_for_resource_type(**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/*}/dataSourceReferences:fetchForResourceType" + % client.transport._host, + args[1], + ) + + +def test_fetch_data_source_references_for_resource_type_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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.fetch_data_source_references_for_resource_type( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest(), + parent="parent_value", + resource_type="resource_type_value", + ) + + +def test_fetch_data_source_references_for_resource_type_rest_pager( + transport: str = "rest", +): + client = BackupDRClient( + 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 = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + next_page_token="abc", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[], + next_page_token="def", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + ], + next_page_token="ghi", + ), + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + data_source_references=[ + datasourcereference.DataSourceReference(), + datasourcereference.DataSourceReference(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse.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.fetch_data_source_references_for_resource_type( + 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, datasourcereference.DataSourceReference) for i in results + ) + + pages = list( + client.fetch_data_source_references_for_resource_type( + request=sample_request + ).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_initialize_service_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 = BackupDRClient( + 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.initialize_service 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.initialize_service] = ( + mock_rpc + ) + + request = {} + client.initialize_service(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.initialize_service(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_initialize_service_rest_required_fields( + request_type=backupdr.InitializeServiceRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["name"] = "" + request_init["resource_type"] = "" + 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 + + default_values = getattr( + transport_class._BaseInitializeService, + "_BaseInitializeService__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["resourceType"] = "resource_type_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "resourceType" in jsonified_request + assert jsonified_request["resourceType"] == "resource_type_value" + + client = BackupDRClient( + 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.initialize_service(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_auto_protection_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 = BackupDRClient( + 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_auto_protection_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.create_auto_protection_policy + ] = mock_rpc + + request = {} + client.create_auto_protection_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.create_auto_protection_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_create_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.CreateAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["auto_protection_policy_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 "autoProtectionPolicyId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateAutoProtectionPolicy, + "_BaseCreateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "autoProtectionPolicyId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyId"] + == request_init["auto_protection_policy_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["autoProtectionPolicyId"] = "auto_protection_policy_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "autoProtectionPolicyId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "autoProtectionPolicyId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyId"] == "auto_protection_policy_id_value" + ) + + client = BackupDRClient( + 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_auto_protection_policy(request) + + expected_params = [ + ( + "autoProtectionPolicyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + 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", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_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_auto_protection_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/v1beta/{parent=projects/*/locations/*}/autoProtectionPolicies" + % client.transport._host, + args[1], + ) + + +def test_create_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.CreateAutoProtectionPolicyRequest(), + parent="parent_value", + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + auto_protection_policy_id="auto_protection_policy_id_value", + ) + + +def test_list_auto_protection_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: + client = BackupDRClient( + 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_auto_protection_policies + 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_auto_protection_policies + ] = mock_rpc + + request = {} + client.list_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auto_protection_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_list_auto_protection_policies_rest_required_fields( + request_type=autoprotectionpolicy.ListAutoProtectionPoliciesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListAutoProtectionPolicies, + "_BaseListAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_auto_protection_policies(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_auto_protection_policies_rest_flattened(): + client = BackupDRClient( + 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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + + # 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 = autoprotectionpolicy.ListAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_auto_protection_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/v1beta/{parent=projects/*/locations/*}/autoProtectionPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_auto_protection_policies_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policies( + autoprotectionpolicy.ListAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_auto_protection_policies_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="abc", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[], + next_page_token="def", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + auto_protection_policies=[ + autoprotectionpolicy.AutoProtectionPolicy(), + autoprotectionpolicy.AutoProtectionPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse.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_auto_protection_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, autoprotectionpolicy.AutoProtectionPolicy) for i in results + ) + + pages = list(client.list_auto_protection_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_auto_protection_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 = BackupDRClient( + 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_auto_protection_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_auto_protection_policy + ] = mock_rpc + + request = {} + client.get_auto_protection_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auto_protection_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_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.GetAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetAutoProtectionPolicy, + "_BaseGetAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicy.AutoProtectionPolicy() + # 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 = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_auto_protection_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_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + 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 = autoprotectionpolicy.AutoProtectionPolicy() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/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 = autoprotectionpolicy.AutoProtectionPolicy.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_auto_protection_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/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_get_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.GetAutoProtectionPolicyRequest(), + name="name_value", + ) + + +def test_update_auto_protection_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 = BackupDRClient( + 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_auto_protection_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_auto_protection_policy + ] = mock_rpc + + request = {} + client.update_auto_protection_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_auto_protection_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_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.UpdateAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateAutoProtectionPolicy, + "_BaseUpdateAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "requestId", + "updateMask", + ) + ) + + # verify required fields with non-default values are left alone + + client = BackupDRClient( + 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_auto_protection_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_update_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + 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 = { + "auto_protection_policy": { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_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_auto_protection_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/v1beta/{auto_protection_policy.name=projects/*/locations/*/autoProtectionPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_update_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.UpdateAutoProtectionPolicyRequest(), + auto_protection_policy=autoprotectionpolicy.AutoProtectionPolicy( + name="name_value" + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_auto_protection_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 = BackupDRClient( + 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_auto_protection_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.delete_auto_protection_policy + ] = mock_rpc + + request = {} + client.delete_auto_protection_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.delete_auto_protection_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_delete_auto_protection_policy_rest_required_fields( + request_type=autoprotectionpolicy.DeleteAutoProtectionPolicyRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteAutoProtectionPolicy, + "_BaseDeleteAutoProtectionPolicy__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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_auto_protection_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_delete_auto_protection_policy_rest_flattened(): + client = BackupDRClient( + 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/autoProtectionPolicies/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_auto_protection_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/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_auto_protection_policy_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_auto_protection_policy( + autoprotectionpolicy.DeleteAutoProtectionPolicyRequest(), + name="name_value", + ) + + +def test_create_auto_protection_policy_binding_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 = BackupDRClient( + 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_auto_protection_policy_binding + 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_auto_protection_policy_binding + ] = mock_rpc + + request = {} + client.create_auto_protection_policy_binding(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_auto_protection_policy_binding(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_auto_protection_policy_binding_rest_required_fields( + request_type=autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest, +): + transport_class = transports.BackupDRRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["auto_protection_policy_binding_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 "autoProtectionPolicyBindingId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateAutoProtectionPolicyBinding, + "_BaseCreateAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "autoProtectionPolicyBindingId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyBindingId"] + == request_init["auto_protection_policy_binding_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["autoProtectionPolicyBindingId"] = ( + "auto_protection_policy_binding_id_value" + ) + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "autoProtectionPolicyBindingId", + "requestId", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "autoProtectionPolicyBindingId" in jsonified_request + assert ( + jsonified_request["autoProtectionPolicyBindingId"] + == "auto_protection_policy_binding_id_value" + ) + + client = BackupDRClient( + 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_auto_protection_policy_binding(request) + + expected_params = [ + ( + "autoProtectionPolicyBindingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_auto_protection_policy_binding_rest_flattened(): + client = BackupDRClient( + 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/autoProtectionPolicies/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_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_auto_protection_policy_binding(**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/*/autoProtectionPolicies/*}/bindings" + % client.transport._host, + args[1], + ) + + +def test_create_auto_protection_policy_binding_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_auto_protection_policy_binding( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest(), + parent="parent_value", + auto_protection_policy_binding=autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value" + ), + auto_protection_policy_binding_id="auto_protection_policy_binding_id_value", + ) + + +def test_get_auto_protection_policy_binding_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 = BackupDRClient( + 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_auto_protection_policy_binding + 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_auto_protection_policy_binding + ] = mock_rpc + + request = {} + client.get_auto_protection_policy_binding(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auto_protection_policy_binding(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_auto_protection_policy_binding_rest_required_fields( + request_type=autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetAutoProtectionPolicyBinding, + "_BaseGetAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + # 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 = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_auto_protection_policy_binding(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_auto_protection_policy_binding_rest_flattened(): + client = BackupDRClient( + 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 = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/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 = autoprotectionpolicybinding.AutoProtectionPolicyBinding.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_auto_protection_policy_binding(**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/*/autoProtectionPolicies/*/bindings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_auto_protection_policy_binding_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_auto_protection_policy_binding( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +def test_list_auto_protection_policy_bindings_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 = BackupDRClient( + 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_auto_protection_policy_bindings + 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_auto_protection_policy_bindings + ] = mock_rpc + + request = {} + client.list_auto_protection_policy_bindings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auto_protection_policy_bindings(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_auto_protection_policy_bindings_rest_required_fields( + request_type=autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListAutoProtectionPolicyBindings, + "_BaseListAutoProtectionPolicyBindings__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + # 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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_auto_protection_policy_bindings(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_auto_protection_policy_bindings_rest_flattened(): + client = BackupDRClient( + 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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_auto_protection_policy_bindings(**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/*/autoProtectionPolicies/*}/bindings" + % client.transport._host, + args[1], + ) + + +def test_list_auto_protection_policy_bindings_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_auto_protection_policy_bindings( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest(), + parent="parent_value", + ) + + +def test_list_auto_protection_policy_bindings_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="abc", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[], + next_page_token="def", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + next_page_token="ghi", + ), + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + auto_protection_policy_bindings=[ + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + autoprotectionpolicybinding.AutoProtectionPolicyBinding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse.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/autoProtectionPolicies/sample3" + } + + pager = client.list_auto_protection_policy_bindings(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, autoprotectionpolicybinding.AutoProtectionPolicyBinding) + for i in results + ) + + pages = list( + client.list_auto_protection_policy_bindings(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_applied_auto_protection_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: + client = BackupDRClient( + 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_applied_auto_protection_policies + 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_applied_auto_protection_policies + ] = mock_rpc + + request = {} + client.list_applied_auto_protection_policies(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_applied_auto_protection_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_list_applied_auto_protection_policies_rest_required_fields( + request_type=appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListAppliedAutoProtectionPolicies, + "_BaseListAppliedAutoProtectionPolicies__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + # 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 = appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_applied_auto_protection_policies(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_applied_auto_protection_policies_rest_flattened(): + client = BackupDRClient( + 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + + # 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_applied_auto_protection_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/v1beta/{parent=projects/*/locations/*}/appliedAutoProtectionPolicies" + % client.transport._host, + args[1], + ) + + +def test_list_applied_auto_protection_policies_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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_applied_auto_protection_policies( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest(), + parent="parent_value", + ) + + +def test_list_applied_auto_protection_policies_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="abc", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[], + next_page_token="def", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + next_page_token="ghi", + ), + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + applied_auto_protection_policies=[ + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + appliedautoprotectionpolicy.AppliedAutoProtectionPolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse.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_applied_auto_protection_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, appliedautoprotectionpolicy.AppliedAutoProtectionPolicy) + for i in results + ) + + pages = list( + client.list_applied_auto_protection_policies(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_initiate_delete_auto_protection_policy_binding_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 = BackupDRClient( + 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.initiate_delete_auto_protection_policy_binding + 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.initiate_delete_auto_protection_policy_binding + ] = mock_rpc + + request = {} + client.initiate_delete_auto_protection_policy_binding(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.initiate_delete_auto_protection_policy_binding(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_initiate_delete_auto_protection_policy_binding_rest_required_fields( + request_type=autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseInitiateDeleteAutoProtectionPolicyBinding, + "_BaseInitiateDeleteAutoProtectionPolicyBinding__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + 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.initiate_delete_auto_protection_policy_binding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_initiate_delete_auto_protection_policy_binding_rest_flattened(): + client = BackupDRClient( + 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/autoProtectionPolicies/sample3/bindings/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.initiate_delete_auto_protection_policy_binding(**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/*/autoProtectionPolicies/*/bindings/*}:initiateDelete" + % client.transport._host, + args[1], + ) + + +def test_initiate_delete_auto_protection_policy_binding_rest_flattened_error( + transport: str = "rest", +): + client = BackupDRClient( + 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.initiate_delete_auto_protection_policy_binding( + autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest(), + name="name_value", + ) + + +def test_get_binding_matching_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: + client = BackupDRClient( + 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_binding_matching_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_binding_matching_resource + ] = mock_rpc + + request = {} + client.get_binding_matching_resource(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_binding_matching_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_binding_matching_resource_rest_required_fields( + request_type=bindingmatchingresource.GetBindingMatchingResourceRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetBindingMatchingResource, + "_BaseGetBindingMatchingResource__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bindingmatchingresource.BindingMatchingResource() + # 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 = bindingmatchingresource.BindingMatchingResource.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_binding_matching_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_binding_matching_resource_rest_flattened(): + client = BackupDRClient( + 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 = bindingmatchingresource.BindingMatchingResource() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/sample4/matchingResources/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 = bindingmatchingresource.BindingMatchingResource.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_binding_matching_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/v1beta/{name=projects/*/locations/*/autoProtectionPolicies/*/bindings/*/matchingResources/*}" + % client.transport._host, + args[1], + ) + + +def test_get_binding_matching_resource_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_binding_matching_resource( + bindingmatchingresource.GetBindingMatchingResourceRequest(), + name="name_value", + ) + + +def test_list_binding_matching_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: + client = BackupDRClient( + 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_binding_matching_resources + 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_binding_matching_resources + ] = mock_rpc + + request = {} + client.list_binding_matching_resources(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_binding_matching_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_binding_matching_resources_rest_required_fields( + request_type=bindingmatchingresource.ListBindingMatchingResourcesRequest, +): + transport_class = transports.BackupDRRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListBindingMatchingResources, + "_BaseListBindingMatchingResources__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = bindingmatchingresource.ListBindingMatchingResourcesResponse() + # 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 = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_binding_matching_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_binding_matching_resources_rest_flattened(): + client = BackupDRClient( + 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 = bindingmatchingresource.ListBindingMatchingResourcesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/autoProtectionPolicies/sample3/bindings/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 = bindingmatchingresource.ListBindingMatchingResourcesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_binding_matching_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/v1beta/{parent=projects/*/locations/*/autoProtectionPolicies/*/bindings/*}/matchingResources" + % client.transport._host, + args[1], + ) + + +def test_list_binding_matching_resources_rest_flattened_error(transport: str = "rest"): + client = BackupDRClient( + 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_binding_matching_resources( + bindingmatchingresource.ListBindingMatchingResourcesRequest(), + parent="parent_value", + ) + + +def test_list_binding_matching_resources_rest_pager(transport: str = "rest"): + client = BackupDRClient( + 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 = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="abc", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[], + next_page_token="def", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + ], + next_page_token="ghi", + ), + bindingmatchingresource.ListBindingMatchingResourcesResponse( + matching_resources=[ + bindingmatchingresource.BindingMatchingResource(), + bindingmatchingresource.BindingMatchingResource(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + bindingmatchingresource.ListBindingMatchingResourcesResponse.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/autoProtectionPolicies/sample3/bindings/sample4" + } + + pager = client.list_binding_matching_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, bindingmatchingresource.BindingMatchingResource) + for i in results + ) + + pages = list( + client.list_binding_matching_resources(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.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDRClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BackupDRClient( + 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 = BackupDRClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BackupDRClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BackupDRClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BackupDRGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BackupDRGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BackupDRGrpcTransport, + transports.BackupDRGrpcAsyncIOTransport, + transports.BackupDRRestTransport, + ], +) +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 = BackupDRClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = BackupDRClient( + 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_management_servers_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + call.return_value = backupdr.ListManagementServersResponse() + client.list_management_servers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.ListManagementServersRequest() + 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_management_server_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + call.return_value = backupdr.ManagementServer() + client.get_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.GetManagementServerRequest() + 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_management_server_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.CreateManagementServerRequest() + 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_management_server_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.DeleteManagementServerRequest() + 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_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.CreateRestoreTemplateRequest() + 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_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template), "__call__" + ) as call: + call.return_value = restore_template.RestoreTemplate() + client.get_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.GetRestoreTemplateRequest() + 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_restore_templates_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + call.return_value = restore_template.ListRestoreTemplatesResponse() + client.list_restore_templates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.ListRestoreTemplatesRequest() + 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_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.UpdateRestoreTemplateRequest() + 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_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.DeleteRestoreTemplateRequest() + 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_run_restore_template_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.run_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.RunRestoreTemplateRequest() + 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_restore_template_execution_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + call.return_value = restore_template_execution.RestoreTemplateExecution() + client.get_restore_template_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.GetRestoreTemplateExecutionRequest() + 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_restore_template_executions_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + call.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + client.list_restore_template_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.ListRestoreTemplateExecutionsRequest() + 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_trigger_restore_cleanup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_restore_cleanup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.TriggerRestoreCleanupRequest() + 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_restore_verification_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + ) + 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_restore_verification_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + client.get_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_associations_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + call.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + client.list_restore_verification_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + 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_restore_verification_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + 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_trigger_restore_verification_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_restore_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) + 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_restore_verification_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: + call.return_value = restore_verification_plan.RestoreVerificationPlan() + client.get_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.GetRestoreVerificationPlanRequest() + 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_restore_verification_plans_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: + call.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) + client.list_restore_verification_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.ListRestoreVerificationPlansRequest() + 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_restore_verification_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + 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_backup_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.CreateBackupVaultRequest() + 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_vaults_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + call.return_value = backupvault.ListBackupVaultsResponse() + client.list_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupVaultsRequest() + 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_fetch_usable_backup_vaults_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + call.return_value = backupvault.FetchUsableBackupVaultsResponse() + client.fetch_usable_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchUsableBackupVaultsRequest() + 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_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + call.return_value = backupvault.BackupVault() + client.get_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupVaultRequest() + 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_backup_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupVaultRequest() + 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_vault_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupVaultRequest() + 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_data_sources_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + call.return_value = backupvault.ListDataSourcesResponse() + client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListDataSourcesRequest() + 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_data_source_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + call.return_value = backupvault.DataSource() + client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetDataSourceRequest() + 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_data_source_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateDataSourceRequest() + 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 = BackupDRClient( + 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 = backupvault.ListBackupsResponse() + client.list_backups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.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_fetch_backups_for_resource_type_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + call.return_value = backupvault.FetchBackupsForResourceTypeResponse() + client.fetch_backups_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchBackupsForResourceTypeRequest() + 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 = BackupDRClient( + 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 = backupvault.Backup() + client.get_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.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_update_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupRequest() + 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 = BackupDRClient( + 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 = backupvault.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_restore_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.restore_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.restore_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.RestoreBackupRequest() + 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_backup_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.CreateBackupPlanRequest() + 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_backup_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.UpdateBackupPlanRequest() + 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_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + call.return_value = backupplan.BackupPlan() + client.get_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRequest() + 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_plans_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + call.return_value = backupplan.ListBackupPlansResponse() + client.list_backup_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlansRequest() + 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_plan_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.DeleteBackupPlanRequest() + 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_plan_revision_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + call.return_value = backupplan.BackupPlanRevision() + client.get_backup_plan_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRevisionRequest() + 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_plan_revisions_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + call.return_value = backupplan.ListBackupPlanRevisionsResponse() + client.list_backup_plan_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlanRevisionsRequest() + 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_backup_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() + 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_backup_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() + 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_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + call.return_value = backupplanassociation.BackupPlanAssociation() + client.get_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.GetBackupPlanAssociationRequest() + 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_plan_associations_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + call.return_value = backupplanassociation.ListBackupPlanAssociationsResponse() + client.list_backup_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() + 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_fetch_backup_plan_associations_for_resource_type_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + call.return_value = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse() + ) + client.fetch_backup_plan_associations_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + 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_plan_association_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() + 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_trigger_backup_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.trigger_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.trigger_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.TriggerBackupRequest() + 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_data_source_reference_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + call.return_value = datasourcereference.DataSourceReference() + client.get_data_source_reference(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.GetDataSourceReferenceRequest() + 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_data_source_references_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + call.return_value = datasourcereference.ListDataSourceReferencesResponse() + client.list_data_source_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.ListDataSourceReferencesRequest() + 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_fetch_data_source_references_for_resource_type_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + call.return_value = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse() + ) + client.fetch_data_source_references_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + ) + 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_initialize_service_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + 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_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + 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_auto_protection_policies_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.ListAutoProtectionPoliciesResponse() + client.list_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + 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_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + call.return_value = autoprotectionpolicy.AutoProtectionPolicy() + client.get_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + 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_auto_protection_policy_binding_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_binding_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + call.return_value = autoprotectionpolicybinding.AutoProtectionPolicyBinding() + client.get_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_bindings_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + call.return_value = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse() + ) + client.list_auto_protection_policy_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + 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_applied_auto_protection_policies_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + call.return_value = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse() + ) + client.list_applied_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() + ) + 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_initiate_delete_auto_protection_policy_binding_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__call__", + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.initiate_delete_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + 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_binding_matching_resource_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + call.return_value = bindingmatchingresource.BindingMatchingResource() + client.get_binding_matching_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest() + 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_binding_matching_resources_empty_call_grpc(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + call.return_value = ( + bindingmatchingresource.ListBindingMatchingResourcesResponse() + ) + client.list_binding_matching_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = BackupDRAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = BackupDRAsyncClient( + 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_management_servers_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_management_servers), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ListManagementServersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_management_servers(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.ListManagementServersRequest() + 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_management_server_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_management_server), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupdr.ManagementServer( + name="name_value", + description="description_value", + type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, + state=backupdr.ManagementServer.InstanceState.CREATING, + etag="etag_value", + oauth2_client_id="oauth2_client_id_value", + ba_proxy_uri=["ba_proxy_uri_value"], + satisfies_pzi=True, + ) + ) + await client.get_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.GetManagementServerRequest() + 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_management_server_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_management_server), "__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_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.CreateManagementServerRequest() + 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_management_server_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_management_server), "__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_management_server(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.DeleteManagementServerRequest() + 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_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__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_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.CreateRestoreTemplateRequest() + 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_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template.RestoreTemplate( + name="name_value", + description="description_value", + resource_type="resource_type_value", + state=restore_template.RestoreTemplate.State.CREATING, + etag="etag_value", + ) + ) + await client.get_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.GetRestoreTemplateRequest() + 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_restore_templates_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template.ListRestoreTemplatesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_restore_templates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.ListRestoreTemplatesRequest() + 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_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__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_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.UpdateRestoreTemplateRequest() + 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_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__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_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.DeleteRestoreTemplateRequest() + 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_run_restore_template_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__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.run_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.RunRestoreTemplateRequest() + 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_restore_template_execution_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.RestoreTemplateExecution( + name="name_value", + resource_type="resource_type_value", + type_=restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED, + phase=restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING, + state=restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING, + ) + ) + await client.get_restore_template_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.GetRestoreTemplateExecutionRequest() + 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_restore_template_executions_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_template_execution.ListRestoreTemplateExecutionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_restore_template_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.ListRestoreTemplateExecutionsRequest() + 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_trigger_restore_cleanup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__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.trigger_restore_cleanup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.TriggerRestoreCleanupRequest() + 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_restore_verification_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__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_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + ) + 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_restore_verification_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__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_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value", + description="description_value", + state=restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING, + resource_type="resource_type_value", + ) + ) + await client.get_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_associations_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_restore_verification_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + 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_restore_verification_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__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_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + 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_trigger_restore_verification_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__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.trigger_restore_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) + 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_restore_verification_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan.RestoreVerificationPlan( + name="name_value", + description="description_value", + state=restore_verification_plan.RestoreVerificationPlan.State.CREATING, + schedule="schedule_value", + time_zone="time_zone_value", + ) + ) + await client.get_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.GetRestoreVerificationPlanRequest() + 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_restore_verification_plans_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + restore_verification_plan.ListRestoreVerificationPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_restore_verification_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.ListRestoreVerificationPlansRequest() + 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_restore_verification_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan), "__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_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + 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_backup_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_vault), "__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_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.CreateBackupVaultRequest() + 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_vaults_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListBackupVaultsRequest() + 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_fetch_usable_backup_vaults_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_usable_backup_vaults), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchUsableBackupVaultsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.fetch_usable_backup_vaults(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchUsableBackupVaultsRequest() + 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_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_vault), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.BackupVault( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + deletable=True, + etag="etag_value", + state=backupvault.BackupVault.State.CREATING, + backup_count=1278, + service_account="service_account_value", + total_stored_bytes=1946, + uid="uid_value", + access_restriction=backupvault.BackupVault.AccessRestriction.WITHIN_PROJECT, + ) + ) + await client.get_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetBackupVaultRequest() + 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_backup_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_vault), "__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_backup_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupVaultRequest() + 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_vault_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_vault), "__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_vault(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.DeleteBackupVaultRequest() + 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_data_sources_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_sources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.ListDataSourcesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_data_sources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.ListDataSourcesRequest() + 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_data_source_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_data_source), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.DataSource( + name="name_value", + state=backupvault.DataSource.State.CREATING, + backup_count=1278, + etag="etag_value", + total_stored_bytes=1946, + config_state=backupvault.BackupConfigState.ACTIVE, + backup_blocked_by_vault_access_restriction=True, + ) + ) + await client.get_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.GetDataSourceRequest() + 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_data_source_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_data_source), "__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_data_source(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateDataSourceRequest() + 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 = BackupDRAsyncClient( + 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( + backupvault.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 = backupvault.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_fetch_backups_for_resource_type_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backups_for_resource_type), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupvault.FetchBackupsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_backups_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.FetchBackupsForResourceTypeRequest() + 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 = BackupDRAsyncClient( + 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( + backupvault.Backup( + name="name_value", + description="description_value", + backup_retention_inheritance=backupvault.BackupVault.BackupRetentionInheritance.INHERIT_VAULT_RETENTION, + etag="etag_value", + state=backupvault.Backup.State.CREATING, + backup_type=backupvault.Backup.BackupType.SCHEDULED, + resource_size_bytes=2056, + satisfies_pzs=True, + satisfies_pzi=True, + kms_key_versions=["kms_key_versions_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 = backupvault.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_update_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_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.update_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.UpdateBackupRequest() + 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 = BackupDRAsyncClient( + 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 = backupvault.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_restore_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.restore_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.restore_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupvault.RestoreBackupRequest() + 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_backup_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan), "__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_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.CreateBackupPlanRequest() + 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_backup_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan), "__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_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.UpdateBackupPlanRequest() + 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_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup_plan), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlan( + name="name_value", + description="description_value", + max_custom_on_demand_retention_days=3723, + state=backupplan.BackupPlan.State.CREATING, + resource_type="resource_type_value", + etag="etag_value", + backup_vault="backup_vault_value", + backup_vault_service_account="backup_vault_service_account_value", + log_retention_days=1929, + supported_resource_types=["supported_resource_types_value"], + revision_id="revision_id_value", + revision_name="revision_name_value", + ) + ) + await client.get_backup_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRequest() + 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_plans_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plans), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlansResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlansRequest() + 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_plan_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan), "__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_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.DeleteBackupPlanRequest() + 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_plan_revision_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_revision), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.BackupPlanRevision( + name="name_value", + revision_id="revision_id_value", + state=backupplan.BackupPlanRevision.State.CREATING, + ) + ) + await client.get_backup_plan_revision(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.GetBackupPlanRevisionRequest() + 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_plan_revisions_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_revisions), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplan.ListBackupPlanRevisionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_plan_revisions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplan.ListBackupPlanRevisionsRequest() + 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_backup_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_backup_plan_association), "__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_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.CreateBackupPlanAssociationRequest() + 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_backup_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_backup_plan_association), "__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_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.UpdateBackupPlanAssociationRequest() + 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_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_plan_association), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.BackupPlanAssociation( + name="name_value", + resource_type="resource_type_value", + resource="resource_value", + backup_plan="backup_plan_value", + state=backupplanassociation.BackupPlanAssociation.State.CREATING, + data_source="data_source_value", + backup_plan_revision_id="backup_plan_revision_id_value", + backup_plan_revision_name="backup_plan_revision_name_value", + auto_protection_policy_binding="auto_protection_policy_binding_value", + ) + ) + await client.get_backup_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.GetBackupPlanAssociationRequest() + 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_plan_associations_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_plan_associations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.ListBackupPlanAssociationsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.ListBackupPlanAssociationsRequest() + 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_fetch_backup_plan_associations_for_resource_type_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_backup_plan_associations_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_backup_plan_associations_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + backupplanassociation.FetchBackupPlanAssociationsForResourceTypeRequest() + ) + 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_plan_association_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_backup_plan_association), "__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_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.DeleteBackupPlanAssociationRequest() + 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_trigger_backup_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.trigger_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.trigger_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupplanassociation.TriggerBackupRequest() + 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_data_source_reference_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_data_source_reference), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.DataSourceReference( + name="name_value", + data_source="data_source_value", + data_source_backup_config_state=backupvault.BackupConfigState.ACTIVE, + data_source_backup_count=2535, + total_stored_bytes=1946, + ) + ) + await client.get_data_source_reference(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.GetDataSourceReferenceRequest() + 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_data_source_references_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_data_source_references), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.ListDataSourceReferencesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_data_source_references(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = datasourcereference.ListDataSourceReferencesRequest() + 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_fetch_data_source_references_for_resource_type_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_data_source_references_for_resource_type), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + datasourcereference.FetchDataSourceReferencesForResourceTypeResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_data_source_references_for_resource_type(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + datasourcereference.FetchDataSourceReferencesForResourceTypeRequest() + ) + 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_initialize_service_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initialize_service), "__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.initialize_service(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = backupdr.InitializeServiceRequest() + 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_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy), "__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_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.CreateAutoProtectionPolicyRequest() + 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_auto_protection_policies_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.ListAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.ListAutoProtectionPoliciesRequest() + 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_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicy.AutoProtectionPolicy( + name="name_value", + description="description_value", + state=autoprotectionpolicy.AutoProtectionPolicy.State.CREATING, + etag="etag_value", + ) + ) + await client.get_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.GetAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_auto_protection_policy), "__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_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.UpdateAutoProtectionPolicyRequest() + 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_auto_protection_policy_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auto_protection_policy), "__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_auto_protection_policy(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicy.DeleteAutoProtectionPolicyRequest() + 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_auto_protection_policy_binding_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_auto_protection_policy_binding), "__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_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.CreateAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_binding_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_auto_protection_policy_binding), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.AutoProtectionPolicyBinding( + name="name_value", + description="description_value", + state=autoprotectionpolicybinding.AutoProtectionPolicyBinding.State.CREATING, + scope="scope_value", + etag="etag_value", + ) + ) + await client.get_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.GetAutoProtectionPolicyBindingRequest() + ) + 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_auto_protection_policy_bindings_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_auto_protection_policy_bindings), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_auto_protection_policy_bindings(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + autoprotectionpolicybinding.ListAutoProtectionPolicyBindingsRequest() + ) + 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_applied_auto_protection_policies_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_applied_auto_protection_policies), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_applied_auto_protection_policies(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() _, args, _ = call.mock_calls[0] request_msg = ( appliedautoprotectionpolicy.ListAppliedAutoProtectionPoliciesRequest() ) - assert args[0] == request_msg + 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_initiate_delete_auto_protection_policy_binding_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.initiate_delete_auto_protection_policy_binding), + "__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.initiate_delete_auto_protection_policy_binding(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() + 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_binding_matching_resource_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_binding_matching_resource), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.BindingMatchingResource( + name="name_value", + resource="resource_value", + ) + ) + await client.get_binding_matching_resource(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest() + 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_binding_matching_resources_empty_call_grpc_asyncio(): + client = BackupDRAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_binding_matching_resources), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + bindingmatchingresource.ListBindingMatchingResourcesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_binding_matching_resources(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = BackupDRClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_management_servers_rest_bad_request( + request_type=backupdr.ListManagementServersRequest, +): + client = BackupDRClient( + 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_management_servers(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.ListManagementServersRequest, + dict, + ], +) +def test_list_management_servers_rest_call_success(request_type): + client = BackupDRClient( + 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 = backupdr.ListManagementServersResponse( + 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 = backupdr.ListManagementServersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_management_servers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListManagementServersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_management_servers_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_management_servers" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_management_servers_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_management_servers" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.ListManagementServersRequest.pb( + backupdr.ListManagementServersRequest() + ) + 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 = backupdr.ListManagementServersResponse.to_json( + backupdr.ListManagementServersResponse() + ) + req.return_value.content = return_value + + request = backupdr.ListManagementServersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupdr.ListManagementServersResponse() + post_with_metadata.return_value = ( + backupdr.ListManagementServersResponse(), + metadata, + ) + + client.list_management_servers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_management_server_rest_bad_request( + request_type=backupdr.GetManagementServerRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/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_management_server(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.GetManagementServerRequest, + dict, + ], +) +def test_get_management_server_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/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 = backupdr.ManagementServer( + name="name_value", + description="description_value", + type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, + state=backupdr.ManagementServer.InstanceState.CREATING, + etag="etag_value", + oauth2_client_id="oauth2_client_id_value", + ba_proxy_uri=["ba_proxy_uri_value"], + satisfies_pzi=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 = backupdr.ManagementServer.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_management_server(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, backupdr.ManagementServer) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.type_ == backupdr.ManagementServer.InstanceType.BACKUP_RESTORE + assert response.state == backupdr.ManagementServer.InstanceState.CREATING + assert response.etag == "etag_value" + assert response.oauth2_client_id == "oauth2_client_id_value" + assert response.ba_proxy_uri == ["ba_proxy_uri_value"] + assert response.satisfies_pzi is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_management_server_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_management_server" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_management_server_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_management_server" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.GetManagementServerRequest.pb( + backupdr.GetManagementServerRequest() + ) + 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 = backupdr.ManagementServer.to_json(backupdr.ManagementServer()) + req.return_value.content = return_value + + request = backupdr.GetManagementServerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = backupdr.ManagementServer() + post_with_metadata.return_value = backupdr.ManagementServer(), metadata + + client.get_management_server( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_management_server_rest_bad_request( + request_type=backupdr.CreateManagementServerRequest, +): + client = BackupDRClient( + 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_management_server(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.CreateManagementServerRequest, + dict, + ], +) +def test_create_management_server_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["management_server"] = { + "name": "name_value", + "description": "description_value", + "labels": {}, + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "type_": 1, + "management_uri": {"web_ui": "web_ui_value", "api": "api_value"}, + "workforce_identity_based_management_uri": { + "first_party_management_uri": "first_party_management_uri_value", + "third_party_management_uri": "third_party_management_uri_value", + }, + "state": 1, + "networks": [{"network": "network_value", "peering_mode": 1}], + "etag": "etag_value", + "oauth2_client_id": "oauth2_client_id_value", + "workforce_identity_based_oauth2_client_id": { + "first_party_oauth2_client_id": "first_party_oauth2_client_id_value", + "third_party_oauth2_client_id": "third_party_oauth2_client_id_value", + }, + "ba_proxy_uri": ["ba_proxy_uri_value1", "ba_proxy_uri_value2"], + "satisfies_pzs": {"value": True}, + "satisfies_pzi": 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 = backupdr.CreateManagementServerRequest.meta.fields["management_server"] + + 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["management_server"].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["management_server"][field])): + del request_init["management_server"][field][i][subfield] + else: + del request_init["management_server"][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_management_server(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_management_server_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_create_management_server" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_management_server_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_management_server" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.CreateManagementServerRequest.pb( + backupdr.CreateManagementServerRequest() + ) + 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 = backupdr.CreateManagementServerRequest() + 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_management_server( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_management_server_rest_bad_request( + request_type=backupdr.DeleteManagementServerRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/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_management_server(request) + + +@pytest.mark.parametrize( + "request_type", + [ + backupdr.DeleteManagementServerRequest, + dict, + ], +) +def test_delete_management_server_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/managementServers/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_management_server(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_management_server_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_delete_management_server" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_delete_management_server_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_management_server" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = backupdr.DeleteManagementServerRequest.pb( + backupdr.DeleteManagementServerRequest() + ) + 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 = backupdr.DeleteManagementServerRequest() + 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_management_server( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_restore_template_rest_bad_request( + request_type=gcb_restore_template.CreateRestoreTemplateRequest, +): + client = BackupDRClient( + 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_restore_template(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcb_restore_template.CreateRestoreTemplateRequest, + dict, + ], +) +def test_create_restore_template_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["restore_template"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "resource_type": "resource_type_value", + "labels": {}, + "backup_selection_config": {"data_source": "data_source_value"}, + "pre_restore_config": { + "cloud_run_job": "cloud_run_job_value", + "timeout": {"seconds": 751, "nanos": 543}, + }, + "post_restore_config": {"cloud_run_job": "cloud_run_job_value", "timeout": {}}, + "verification_config": {"cloud_run_job": "cloud_run_job_value", "timeout": {}}, + "restore_properties": {"fields": {}}, + "state": 1, + "execution_summary": { + "last_execution": "last_execution_value", + "last_execution_state": 1, + }, + "etag": "etag_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 = gcb_restore_template.CreateRestoreTemplateRequest.meta.fields[ + "restore_template" + ] + + 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["restore_template"].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["restore_template"][field])): + del request_init["restore_template"][field][i][subfield] + else: + del request_init["restore_template"][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_restore_template(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_restore_template_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_create_restore_template" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_restore_template_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_restore_template" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcb_restore_template.CreateRestoreTemplateRequest.pb( + gcb_restore_template.CreateRestoreTemplateRequest() + ) + 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 = gcb_restore_template.CreateRestoreTemplateRequest() + 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_restore_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_restore_template_rest_bad_request( + request_type=restore_template.GetRestoreTemplateRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/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_restore_template(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_template.GetRestoreTemplateRequest, + dict, + ], +) +def test_get_restore_template_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/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 = restore_template.RestoreTemplate( + name="name_value", + description="description_value", + resource_type="resource_type_value", + state=restore_template.RestoreTemplate.State.CREATING, + 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 = restore_template.RestoreTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_restore_template(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, restore_template.RestoreTemplate) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.resource_type == "resource_type_value" + assert response.state == restore_template.RestoreTemplate.State.CREATING + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_restore_template_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_restore_template" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_restore_template_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_restore_template" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_template.GetRestoreTemplateRequest.pb( + restore_template.GetRestoreTemplateRequest() + ) + 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 = restore_template.RestoreTemplate.to_json( + restore_template.RestoreTemplate() + ) + req.return_value.content = return_value + + request = restore_template.GetRestoreTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = restore_template.RestoreTemplate() + post_with_metadata.return_value = restore_template.RestoreTemplate(), metadata + + client.get_restore_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_restore_templates_rest_bad_request( + request_type=restore_template.ListRestoreTemplatesRequest, +): + client = BackupDRClient( + 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_restore_templates(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_template.ListRestoreTemplatesRequest, + dict, + ], +) +def test_list_restore_templates_rest_call_success(request_type): + client = BackupDRClient( + 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 = restore_template.ListRestoreTemplatesResponse( + 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 = restore_template.ListRestoreTemplatesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_restore_templates(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreTemplatesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_restore_templates_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_restore_templates" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_restore_templates_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_restore_templates" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_template.ListRestoreTemplatesRequest.pb( + restore_template.ListRestoreTemplatesRequest() + ) + 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 = restore_template.ListRestoreTemplatesResponse.to_json( + restore_template.ListRestoreTemplatesResponse() + ) + req.return_value.content = return_value + + request = restore_template.ListRestoreTemplatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = restore_template.ListRestoreTemplatesResponse() + post_with_metadata.return_value = ( + restore_template.ListRestoreTemplatesResponse(), + metadata, + ) + + client.list_restore_templates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_restore_template_rest_bad_request( + request_type=gcb_restore_template.UpdateRestoreTemplateRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "restore_template": { + "name": "projects/sample1/locations/sample2/restoreTemplates/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_restore_template(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcb_restore_template.UpdateRestoreTemplateRequest, + dict, + ], +) +def test_update_restore_template_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "restore_template": { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3" + } + } + request_init["restore_template"] = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "resource_type": "resource_type_value", + "labels": {}, + "backup_selection_config": {"data_source": "data_source_value"}, + "pre_restore_config": { + "cloud_run_job": "cloud_run_job_value", + "timeout": {"seconds": 751, "nanos": 543}, + }, + "post_restore_config": {"cloud_run_job": "cloud_run_job_value", "timeout": {}}, + "verification_config": {"cloud_run_job": "cloud_run_job_value", "timeout": {}}, + "restore_properties": {"fields": {}}, + "state": 1, + "execution_summary": { + "last_execution": "last_execution_value", + "last_execution_state": 1, + }, + "etag": "etag_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 = gcb_restore_template.UpdateRestoreTemplateRequest.meta.fields[ + "restore_template" + ] + + 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["restore_template"].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["restore_template"][field])): + del request_init["restore_template"][field][i][subfield] + else: + del request_init["restore_template"][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_restore_template(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_restore_template_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_update_restore_template" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_update_restore_template_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_update_restore_template" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcb_restore_template.UpdateRestoreTemplateRequest.pb( + gcb_restore_template.UpdateRestoreTemplateRequest() + ) + 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 = gcb_restore_template.UpdateRestoreTemplateRequest() + 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_restore_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_restore_template_rest_bad_request( + request_type=restore_template.DeleteRestoreTemplateRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/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_restore_template(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_template.DeleteRestoreTemplateRequest, + dict, + ], +) +def test_delete_restore_template_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/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_restore_template(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_restore_template_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_delete_restore_template" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_delete_restore_template_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_delete_restore_template" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_template.DeleteRestoreTemplateRequest.pb( + restore_template.DeleteRestoreTemplateRequest() + ) + 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 = restore_template.DeleteRestoreTemplateRequest() + 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_restore_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_run_restore_template_rest_bad_request( + request_type=restore_template.RunRestoreTemplateRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/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.run_restore_template(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_template.RunRestoreTemplateRequest, + dict, + ], +) +def test_run_restore_template_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/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.run_restore_template(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_run_restore_template_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_run_restore_template" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_run_restore_template_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_run_restore_template" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_template.RunRestoreTemplateRequest.pb( + restore_template.RunRestoreTemplateRequest() + ) + 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 = restore_template.RunRestoreTemplateRequest() + 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.run_restore_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_restore_template_execution_rest_bad_request( + request_type=restore_template_execution.GetRestoreTemplateExecutionRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/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_restore_template_execution(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_template_execution.GetRestoreTemplateExecutionRequest, + dict, + ], +) +def test_get_restore_template_execution_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/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 = restore_template_execution.RestoreTemplateExecution( + name="name_value", + resource_type="resource_type_value", + type_=restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED, + phase=restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING, + state=restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING, + ) + + # 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 = restore_template_execution.RestoreTemplateExecution.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_restore_template_execution(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, restore_template_execution.RestoreTemplateExecution) + assert response.name == "name_value" + assert response.resource_type == "resource_type_value" + assert ( + response.type_ + == restore_template_execution.RestoreTemplateExecution.ExecutionType.SCHEDULED + ) + assert ( + response.phase + == restore_template_execution.RestoreTemplateExecution.ExecutionPhase.PREPARING + ) + assert ( + response.state + == restore_template_execution.RestoreTemplateExecution.ExecutionState.RUNNING + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_restore_template_execution_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_restore_template_execution" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_restore_template_execution_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_restore_template_execution" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_template_execution.GetRestoreTemplateExecutionRequest.pb( + restore_template_execution.GetRestoreTemplateExecutionRequest() + ) + 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 = restore_template_execution.RestoreTemplateExecution.to_json( + restore_template_execution.RestoreTemplateExecution() + ) + req.return_value.content = return_value + + request = restore_template_execution.GetRestoreTemplateExecutionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = restore_template_execution.RestoreTemplateExecution() + post_with_metadata.return_value = ( + restore_template_execution.RestoreTemplateExecution(), + metadata, + ) + + client.get_restore_template_execution( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_restore_template_executions_rest_bad_request( + request_type=restore_template_execution.ListRestoreTemplateExecutionsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/restoreTemplates/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_restore_template_executions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_template_execution.ListRestoreTemplateExecutionsRequest, + dict, + ], +) +def test_list_restore_template_executions_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/restoreTemplates/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 = restore_template_execution.ListRestoreTemplateExecutionsResponse( + 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 = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_restore_template_executions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreTemplateExecutionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_restore_template_executions_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_list_restore_template_executions" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_restore_template_executions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_list_restore_template_executions" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_template_execution.ListRestoreTemplateExecutionsRequest.pb( + restore_template_execution.ListRestoreTemplateExecutionsRequest() + ) + 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 = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse.to_json( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + ) + req.return_value.content = return_value + + request = restore_template_execution.ListRestoreTemplateExecutionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse() + ) + post_with_metadata.return_value = ( + restore_template_execution.ListRestoreTemplateExecutionsResponse(), + metadata, + ) + + client.list_restore_template_executions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_trigger_restore_cleanup_rest_bad_request( + request_type=restore_template_execution.TriggerRestoreCleanupRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/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.trigger_restore_cleanup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_template_execution.TriggerRestoreCleanupRequest, + dict, + ], +) +def test_trigger_restore_cleanup_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreTemplates/sample3/executions/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.trigger_restore_cleanup(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_trigger_restore_cleanup_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_trigger_restore_cleanup" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_trigger_restore_cleanup_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_trigger_restore_cleanup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_template_execution.TriggerRestoreCleanupRequest.pb( + restore_template_execution.TriggerRestoreCleanupRequest() + ) + 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 = restore_template_execution.TriggerRestoreCleanupRequest() + 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.trigger_restore_cleanup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_restore_verification_plan_rest_bad_request( + request_type=gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, +): + client = BackupDRClient( + 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_restore_verification_plan(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest, + dict, + ], +) +def test_create_restore_verification_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["restore_verification_plan"] = { + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "state": 1, + "schedule": "schedule_value", + "time_zone": "time_zone_value", + "success_cleanup_rule": { + "cleanup_delay": {"seconds": 751, "nanos": 543}, + "skip_cleanup": True, + }, + "failure_cleanup_rule": {}, + } + # 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 = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest.meta.fields[ + "restore_verification_plan" + ] + ) + + 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[ + "restore_verification_plan" + ].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["restore_verification_plan"][field]) + ): + del request_init["restore_verification_plan"][field][i][subfield] + else: + del request_init["restore_verification_plan"][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_restore_verification_plan(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_restore_verification_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_create_restore_verification_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_restore_verification_plan_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_create_restore_verification_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest.pb( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + ) + ) + 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 = gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + 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_restore_verification_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_restore_verification_plan_association_rest_bad_request( + request_type=gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/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.create_restore_verification_plan_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest, + dict, + ], +) +def test_create_restore_verification_plan_association_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" + } + request_init["restore_verification_plan_association"] = { + "restore_template": "restore_template_value", + "name": "name_value", + "description": "description_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "state": 1, + "trigger_summary": { + "last_trigger_time": {}, + "next_trigger_time": {}, + "last_trigger_error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "last_verification_execution": "last_verification_execution_value", + }, + "resource_type": "resource_type_value", + "labels": {}, + } + # 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 = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest.meta.fields[ + "restore_verification_plan_association" + ] + + 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[ + "restore_verification_plan_association" + ].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["restore_verification_plan_association"][field]) + ): + del request_init["restore_verification_plan_association"][field][i][ + subfield + ] + else: + del request_init["restore_verification_plan_association"][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_restore_verification_plan_association(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_restore_verification_plan_association_rest_interceptors( + null_interceptor, +): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, + "post_create_restore_verification_plan_association", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_create_restore_verification_plan_association_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_create_restore_verification_plan_association", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest.pb( + gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + ) + 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 = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_restore_verification_plan_association_rest_bad_request( + request_type=restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/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_restore_verification_plan_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest, + dict, + ], +) +def test_get_restore_verification_plan_association_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/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 = restore_verification_plan_association.RestoreVerificationPlanAssociation( + name="name_value", + description="description_value", + state=restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING, + resource_type="resource_type_value", + restore_template="restore_template_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 = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_restore_verification_plan_association(request) + + # Establish that the response is the type that we expect. + assert isinstance( + response, + restore_verification_plan_association.RestoreVerificationPlanAssociation, + ) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan_association.RestoreVerificationPlanAssociation.State.CREATING + ) + assert response.resource_type == "resource_type_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_restore_verification_plan_association_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, + "post_get_restore_verification_plan_association", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_restore_verification_plan_association_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_get_restore_verification_plan_association", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest.pb( + restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + ) + 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 = restore_verification_plan_association.RestoreVerificationPlanAssociation.to_json( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + req.return_value.content = return_value + + request = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation() + ) + post_with_metadata.return_value = ( + restore_verification_plan_association.RestoreVerificationPlanAssociation(), + metadata, + ) + + client.get_restore_verification_plan_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_restore_verification_plan_associations_rest_bad_request( + request_type=restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/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_restore_verification_plan_associations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest, + dict, + ], +) +def test_list_restore_verification_plan_associations_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/restoreVerificationPlans/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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse( + 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 -# 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_initiate_delete_auto_protection_policy_binding_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # Convert return value to protobuf type + return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_restore_verification_plan_associations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRestoreVerificationPlanAssociationsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_restore_verification_plan_associations_rest_interceptors( + null_interceptor, +): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), ) + client = BackupDRClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.initiate_delete_auto_protection_policy_binding), - "__call__", - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_restore_verification_plan_associations", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_list_restore_verification_plan_associations_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_list_restore_verification_plan_associations", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest.pb( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() ) - await client.initiate_delete_auto_protection_policy_binding(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = autoprotectionpolicybinding.InitiateDeleteAutoProtectionPolicyBindingRequest() - assert args[0] == request_msg + 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 = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse.to_json( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + ) + req.return_value.content = return_value + + request = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse() + post_with_metadata.return_value = ( + restore_verification_plan_association.ListRestoreVerificationPlanAssociationsResponse(), + metadata, + ) + client.list_restore_verification_plan_associations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -# 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_binding_matching_resource_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_restore_verification_plan_association_rest_bad_request( + request_type=restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/sample4" + } + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_binding_matching_resource), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bindingmatchingresource.BindingMatchingResource( - name="name_value", - resource="resource_value", - ) + # 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_restore_verification_plan_association(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest, + dict, + ], +) +def test_delete_restore_verification_plan_association_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/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_restore_verification_plan_association(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_restore_verification_plan_association_rest_interceptors( + null_interceptor, +): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, + "post_delete_restore_verification_plan_association", + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_delete_restore_verification_plan_association_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, + "pre_delete_restore_verification_plan_association", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest.pb( + restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() ) - await client.get_binding_matching_resource(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bindingmatchingresource.GetBindingMatchingResourceRequest() - assert args[0] == request_msg + 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 = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + 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 -# 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_binding_matching_resources_empty_call_grpc_asyncio(): - client = BackupDRAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client.delete_restore_verification_plan_association( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_trigger_restore_verification_rest_bad_request( + request_type=restore_verification_plan_association.TriggerRestoreVerificationRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/sample4" + } + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_binding_matching_resources), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - bindingmatchingresource.ListBindingMatchingResourcesResponse( - next_page_token="next_page_token_value", - ) + # 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.trigger_restore_verification(request) + + +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan_association.TriggerRestoreVerificationRequest, + dict, + ], +) +def test_trigger_restore_verification_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3/associations/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.trigger_restore_verification(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_trigger_restore_verification_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_trigger_restore_verification" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_trigger_restore_verification_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_trigger_restore_verification" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_verification_plan_association.TriggerRestoreVerificationRequest.pb( + restore_verification_plan_association.TriggerRestoreVerificationRequest() ) - await client.list_binding_matching_resources(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = bindingmatchingresource.ListBindingMatchingResourcesRequest() - assert args[0] == request_msg + 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 = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) + 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 -def test_transport_kind_rest(): - transport = BackupDRClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() + client.trigger_restore_verification( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_restore_verification_plan_rest_bad_request( + request_type=restore_verification_plan.GetRestoreVerificationPlanRequest, +): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - assert transport.kind == "rest" + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/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_restore_verification_plan(request) -def test_list_management_servers_rest_bad_request( - request_type=backupdr.ListManagementServersRequest, +@pytest.mark.parametrize( + "request_type", + [ + restore_verification_plan.GetRestoreVerificationPlanRequest, + dict, + ], +) +def test_get_restore_verification_plan_rest_call_success(request_type): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/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 = restore_verification_plan.RestoreVerificationPlan( + name="name_value", + description="description_value", + state=restore_verification_plan.RestoreVerificationPlan.State.CREATING, + schedule="schedule_value", + time_zone="time_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 = restore_verification_plan.RestoreVerificationPlan.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_restore_verification_plan(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, restore_verification_plan.RestoreVerificationPlan) + assert response.name == "name_value" + assert response.description == "description_value" + assert ( + response.state + == restore_verification_plan.RestoreVerificationPlan.State.CREATING + ) + assert response.schedule == "schedule_value" + assert response.time_zone == "time_zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_restore_verification_plan_rest_interceptors(null_interceptor): + transport = transports.BackupDRRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), + ) + client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_restore_verification_plan" + ) as post, + mock.patch.object( + transports.BackupDRRestInterceptor, + "post_get_restore_verification_plan_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.BackupDRRestInterceptor, "pre_get_restore_verification_plan" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = restore_verification_plan.GetRestoreVerificationPlanRequest.pb( + restore_verification_plan.GetRestoreVerificationPlanRequest() + ) + 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 = restore_verification_plan.RestoreVerificationPlan.to_json( + restore_verification_plan.RestoreVerificationPlan() + ) + req.return_value.content = return_value + + request = restore_verification_plan.GetRestoreVerificationPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = restore_verification_plan.RestoreVerificationPlan() + post_with_metadata.return_value = ( + restore_verification_plan.RestoreVerificationPlan(), + metadata, + ) + + client.get_restore_verification_plan( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_restore_verification_plans_rest_bad_request( + request_type=restore_verification_plan.ListRestoreVerificationPlansRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -34846,17 +50039,17 @@ def test_list_management_servers_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_management_servers(request) + client.list_restore_verification_plans(request) @pytest.mark.parametrize( "request_type", [ - backupdr.ListManagementServersRequest, + restore_verification_plan.ListRestoreVerificationPlansRequest, dict, ], ) -def test_list_management_servers_rest_call_success(request_type): +def test_list_restore_verification_plans_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -34868,7 +50061,7 @@ def test_list_management_servers_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 = backupdr.ListManagementServersResponse( + return_value = restore_verification_plan.ListRestoreVerificationPlansResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) @@ -34878,21 +50071,25 @@ def test_list_management_servers_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = backupdr.ListManagementServersResponse.pb(return_value) + return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_management_servers(request) + response = client.list_restore_verification_plans(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListManagementServersPager) + assert isinstance(response, pagers.ListRestoreVerificationPlansPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_management_servers_rest_interceptors(null_interceptor): +def test_list_restore_verification_plans_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -34903,21 +50100,21 @@ def test_list_management_servers_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.BackupDRRestInterceptor, "post_list_management_servers" + transports.BackupDRRestInterceptor, "post_list_restore_verification_plans" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_list_management_servers_with_metadata", + "post_list_restore_verification_plans_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_list_management_servers" + transports.BackupDRRestInterceptor, "pre_list_restore_verification_plans" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupdr.ListManagementServersRequest.pb( - backupdr.ListManagementServersRequest() + pb_message = restore_verification_plan.ListRestoreVerificationPlansRequest.pb( + restore_verification_plan.ListRestoreVerificationPlansRequest() ) transcode.return_value = { "method": "post", @@ -34929,386 +50126,28 @@ def test_list_management_servers_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 = backupdr.ListManagementServersResponse.to_json( - backupdr.ListManagementServersResponse() + return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse.to_json( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) ) req.return_value.content = return_value - request = backupdr.ListManagementServersRequest() + request = restore_verification_plan.ListRestoreVerificationPlansRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = backupdr.ListManagementServersResponse() + post.return_value = ( + restore_verification_plan.ListRestoreVerificationPlansResponse() + ) post_with_metadata.return_value = ( - backupdr.ListManagementServersResponse(), + restore_verification_plan.ListRestoreVerificationPlansResponse(), metadata, ) - client.list_management_servers( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_management_server_rest_bad_request( - request_type=backupdr.GetManagementServerRequest, -): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/managementServers/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_management_server(request) - - -@pytest.mark.parametrize( - "request_type", - [ - backupdr.GetManagementServerRequest, - dict, - ], -) -def test_get_management_server_rest_call_success(request_type): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/managementServers/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 = backupdr.ManagementServer( - name="name_value", - description="description_value", - type_=backupdr.ManagementServer.InstanceType.BACKUP_RESTORE, - state=backupdr.ManagementServer.InstanceState.CREATING, - etag="etag_value", - oauth2_client_id="oauth2_client_id_value", - ba_proxy_uri=["ba_proxy_uri_value"], - satisfies_pzi=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 = backupdr.ManagementServer.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value.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_management_server(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, backupdr.ManagementServer) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.type_ == backupdr.ManagementServer.InstanceType.BACKUP_RESTORE - assert response.state == backupdr.ManagementServer.InstanceState.CREATING - assert response.etag == "etag_value" - assert response.oauth2_client_id == "oauth2_client_id_value" - assert response.ba_proxy_uri == ["ba_proxy_uri_value"] - assert response.satisfies_pzi is True - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_management_server_rest_interceptors(null_interceptor): - transport = transports.BackupDRRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), - ) - client = BackupDRClient(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.BackupDRRestInterceptor, "post_get_management_server" - ) as post, - mock.patch.object( - transports.BackupDRRestInterceptor, - "post_get_management_server_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.BackupDRRestInterceptor, "pre_get_management_server" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = backupdr.GetManagementServerRequest.pb( - backupdr.GetManagementServerRequest() - ) - 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 = backupdr.ManagementServer.to_json(backupdr.ManagementServer()) - req.return_value.content = return_value - - request = backupdr.GetManagementServerRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = backupdr.ManagementServer() - post_with_metadata.return_value = backupdr.ManagementServer(), metadata - - client.get_management_server( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_create_management_server_rest_bad_request( - request_type=backupdr.CreateManagementServerRequest, -): - client = BackupDRClient( - 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_management_server(request) - - -@pytest.mark.parametrize( - "request_type", - [ - backupdr.CreateManagementServerRequest, - dict, - ], -) -def test_create_management_server_rest_call_success(request_type): - client = BackupDRClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["management_server"] = { - "name": "name_value", - "description": "description_value", - "labels": {}, - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "type_": 1, - "management_uri": {"web_ui": "web_ui_value", "api": "api_value"}, - "workforce_identity_based_management_uri": { - "first_party_management_uri": "first_party_management_uri_value", - "third_party_management_uri": "third_party_management_uri_value", - }, - "state": 1, - "networks": [{"network": "network_value", "peering_mode": 1}], - "etag": "etag_value", - "oauth2_client_id": "oauth2_client_id_value", - "workforce_identity_based_oauth2_client_id": { - "first_party_oauth2_client_id": "first_party_oauth2_client_id_value", - "third_party_oauth2_client_id": "third_party_oauth2_client_id_value", - }, - "ba_proxy_uri": ["ba_proxy_uri_value1", "ba_proxy_uri_value2"], - "satisfies_pzs": {"value": True}, - "satisfies_pzi": 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 = backupdr.CreateManagementServerRequest.meta.fields["management_server"] - - 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["management_server"].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["management_server"][field])): - del request_init["management_server"][field][i][subfield] - else: - del request_init["management_server"][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_management_server(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_management_server_rest_interceptors(null_interceptor): - transport = transports.BackupDRRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), - ) - client = BackupDRClient(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.BackupDRRestInterceptor, "post_create_management_server" - ) as post, - mock.patch.object( - transports.BackupDRRestInterceptor, - "post_create_management_server_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.BackupDRRestInterceptor, "pre_create_management_server" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = backupdr.CreateManagementServerRequest.pb( - backupdr.CreateManagementServerRequest() - ) - 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 = backupdr.CreateManagementServerRequest() - 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_management_server( + client.list_restore_verification_plans( request, metadata=[ ("key", "val"), @@ -35321,15 +50160,15 @@ def test_create_management_server_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_management_server_rest_bad_request( - request_type=backupdr.DeleteManagementServerRequest, +def test_delete_restore_verification_plan_rest_bad_request( + request_type=restore_verification_plan.DeleteRestoreVerificationPlanRequest, ): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/managementServers/sample3" + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" } request = request_type(**request_init) @@ -35346,24 +50185,24 @@ def test_delete_management_server_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_management_server(request) + client.delete_restore_verification_plan(request) @pytest.mark.parametrize( "request_type", [ - backupdr.DeleteManagementServerRequest, + restore_verification_plan.DeleteRestoreVerificationPlanRequest, dict, ], ) -def test_delete_management_server_rest_call_success(request_type): +def test_delete_restore_verification_plan_rest_call_success(request_type): client = BackupDRClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/managementServers/sample3" + "name": "projects/sample1/locations/sample2/restoreVerificationPlans/sample3" } request = request_type(**request_init) @@ -35379,14 +50218,14 @@ def test_delete_management_server_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_management_server(request) + response = client.delete_restore_verification_plan(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_management_server_rest_interceptors(null_interceptor): +def test_delete_restore_verification_plan_rest_interceptors(null_interceptor): transport = transports.BackupDRRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.BackupDRRestInterceptor(), @@ -35398,21 +50237,21 @@ def test_delete_management_server_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.BackupDRRestInterceptor, "post_delete_management_server" + transports.BackupDRRestInterceptor, "post_delete_restore_verification_plan" ) as post, mock.patch.object( transports.BackupDRRestInterceptor, - "post_delete_management_server_with_metadata", + "post_delete_restore_verification_plan_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.BackupDRRestInterceptor, "pre_delete_management_server" + transports.BackupDRRestInterceptor, "pre_delete_restore_verification_plan" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = backupdr.DeleteManagementServerRequest.pb( - backupdr.DeleteManagementServerRequest() + pb_message = restore_verification_plan.DeleteRestoreVerificationPlanRequest.pb( + restore_verification_plan.DeleteRestoreVerificationPlanRequest() ) transcode.return_value = { "method": "post", @@ -35427,7 +50266,7 @@ def test_delete_management_server_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = backupdr.DeleteManagementServerRequest() + request = restore_verification_plan.DeleteRestoreVerificationPlanRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -35436,7 +50275,7 @@ def test_delete_management_server_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_management_server( + client.delete_restore_verification_plan( request, metadata=[ ("key", "val"), @@ -37638,6 +52477,11 @@ def test_update_backup_rest_call_success(request_type): "satisfies_pzs": True, "satisfies_pzi": True, "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + "verification_summary": { + "last_verification_time": {}, + "last_verification_state": 1, + "last_verification_execution": "last_verification_execution_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 @@ -43530,6 +58374,388 @@ def test_delete_management_server_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_create_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_template), "__call__" + ) as call: + client.create_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.CreateRestoreTemplateRequest() + 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_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template), "__call__" + ) as call: + client.get_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.GetRestoreTemplateRequest() + 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_restore_templates_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_templates), "__call__" + ) as call: + client.list_restore_templates(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.ListRestoreTemplatesRequest() + 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_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_restore_template), "__call__" + ) as call: + client.update_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_template.UpdateRestoreTemplateRequest() + 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_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_template), "__call__" + ) as call: + client.delete_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.DeleteRestoreTemplateRequest() + 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_run_restore_template_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.run_restore_template), "__call__" + ) as call: + client.run_restore_template(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template.RunRestoreTemplateRequest() + 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_restore_template_execution_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_template_execution), "__call__" + ) as call: + client.get_restore_template_execution(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.GetRestoreTemplateExecutionRequest() + 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_restore_template_executions_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_template_executions), "__call__" + ) as call: + client.list_restore_template_executions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.ListRestoreTemplateExecutionsRequest() + 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_trigger_restore_cleanup_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_cleanup), "__call__" + ) as call: + client.trigger_restore_cleanup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_template_execution.TriggerRestoreCleanupRequest() + 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_restore_verification_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan), "__call__" + ) as call: + client.create_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + gcb_restore_verification_plan.CreateRestoreVerificationPlanRequest() + ) + 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_restore_verification_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_restore_verification_plan_association), "__call__" + ) as call: + client.create_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = gcb_restore_verification_plan_association.CreateRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan_association), "__call__" + ) as call: + client.get_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.GetRestoreVerificationPlanAssociationRequest() + 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_restore_verification_plan_associations_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plan_associations), "__call__" + ) as call: + client.list_restore_verification_plan_associations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.ListRestoreVerificationPlanAssociationsRequest() + 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_restore_verification_plan_association_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan_association), "__call__" + ) as call: + client.delete_restore_verification_plan_association(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan_association.DeleteRestoreVerificationPlanAssociationRequest() + 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_trigger_restore_verification_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.trigger_restore_verification), "__call__" + ) as call: + client.trigger_restore_verification(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + restore_verification_plan_association.TriggerRestoreVerificationRequest() + ) + 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_restore_verification_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_restore_verification_plan), "__call__" + ) as call: + client.get_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.GetRestoreVerificationPlanRequest() + 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_restore_verification_plans_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_restore_verification_plans), "__call__" + ) as call: + client.list_restore_verification_plans(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.ListRestoreVerificationPlansRequest() + 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_restore_verification_plan_empty_call_rest(): + client = BackupDRClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_restore_verification_plan), "__call__" + ) as call: + client.delete_restore_verification_plan(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = restore_verification_plan.DeleteRestoreVerificationPlanRequest() + 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_backup_vault_empty_call_rest(): @@ -44526,6 +59752,24 @@ def test_backup_dr_base_transport(): "get_management_server", "create_management_server", "delete_management_server", + "create_restore_template", + "get_restore_template", + "list_restore_templates", + "update_restore_template", + "delete_restore_template", + "run_restore_template", + "get_restore_template_execution", + "list_restore_template_executions", + "trigger_restore_cleanup", + "create_restore_verification_plan", + "create_restore_verification_plan_association", + "get_restore_verification_plan_association", + "list_restore_verification_plan_associations", + "delete_restore_verification_plan_association", + "trigger_restore_verification", + "get_restore_verification_plan", + "list_restore_verification_plans", + "delete_restore_verification_plan", "create_backup_vault", "list_backup_vaults", "fetch_usable_backup_vaults", @@ -44871,6 +60115,60 @@ def test_backup_dr_client_transport_session_collision(transport_name): session1 = client1.transport.delete_management_server._session session2 = client2.transport.delete_management_server._session assert session1 != session2 + session1 = client1.transport.create_restore_template._session + session2 = client2.transport.create_restore_template._session + assert session1 != session2 + session1 = client1.transport.get_restore_template._session + session2 = client2.transport.get_restore_template._session + assert session1 != session2 + session1 = client1.transport.list_restore_templates._session + session2 = client2.transport.list_restore_templates._session + assert session1 != session2 + session1 = client1.transport.update_restore_template._session + session2 = client2.transport.update_restore_template._session + assert session1 != session2 + session1 = client1.transport.delete_restore_template._session + session2 = client2.transport.delete_restore_template._session + assert session1 != session2 + session1 = client1.transport.run_restore_template._session + session2 = client2.transport.run_restore_template._session + assert session1 != session2 + session1 = client1.transport.get_restore_template_execution._session + session2 = client2.transport.get_restore_template_execution._session + assert session1 != session2 + session1 = client1.transport.list_restore_template_executions._session + session2 = client2.transport.list_restore_template_executions._session + assert session1 != session2 + session1 = client1.transport.trigger_restore_cleanup._session + session2 = client2.transport.trigger_restore_cleanup._session + assert session1 != session2 + session1 = client1.transport.create_restore_verification_plan._session + session2 = client2.transport.create_restore_verification_plan._session + assert session1 != session2 + session1 = client1.transport.create_restore_verification_plan_association._session + session2 = client2.transport.create_restore_verification_plan_association._session + assert session1 != session2 + session1 = client1.transport.get_restore_verification_plan_association._session + session2 = client2.transport.get_restore_verification_plan_association._session + assert session1 != session2 + session1 = client1.transport.list_restore_verification_plan_associations._session + session2 = client2.transport.list_restore_verification_plan_associations._session + assert session1 != session2 + session1 = client1.transport.delete_restore_verification_plan_association._session + session2 = client2.transport.delete_restore_verification_plan_association._session + assert session1 != session2 + session1 = client1.transport.trigger_restore_verification._session + session2 = client2.transport.trigger_restore_verification._session + assert session1 != session2 + session1 = client1.transport.get_restore_verification_plan._session + session2 = client2.transport.get_restore_verification_plan._session + assert session1 != session2 + session1 = client1.transport.list_restore_verification_plans._session + session2 = client2.transport.list_restore_verification_plans._session + assert session1 != session2 + session1 = client1.transport.delete_restore_verification_plan._session + session2 = client2.transport.delete_restore_verification_plan._session + assert session1 != session2 session1 = client1.transport.create_backup_vault._session session2 = client2.transport.create_backup_vault._session assert session1 != session2 @@ -45581,9 +60879,38 @@ def test_parse_data_source_reference_path(): assert expected == actual -def test_instance_path(): +def test_execution_path(): project = "winkle" - instance = "nautilus" + location = "nautilus" + job = "scallop" + execution = "abalone" + expected = "projects/{project}/locations/{location}/jobs/{job}/executions/{execution}".format( + project=project, + location=location, + job=job, + execution=execution, + ) + actual = BackupDRClient.execution_path(project, location, job, execution) + assert expected == actual + + +def test_parse_execution_path(): + expected = { + "project": "squid", + "location": "clam", + "job": "whelk", + "execution": "octopus", + } + path = BackupDRClient.execution_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_execution_path(path) + assert expected == actual + + +def test_instance_path(): + project = "oyster" + instance = "nudibranch" expected = "projects/{project}/instances/{instance}".format( project=project, instance=instance, @@ -45594,8 +60921,8 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "scallop", - "instance": "abalone", + "project": "cuttlefish", + "instance": "mussel", } path = BackupDRClient.instance_path(**expected) @@ -45604,10 +60931,36 @@ def test_parse_instance_path(): assert expected == actual +def test_job_path(): + project = "winkle" + location = "nautilus" + job = "scallop" + expected = "projects/{project}/locations/{location}/jobs/{job}".format( + project=project, + location=location, + job=job, + ) + actual = BackupDRClient.job_path(project, location, job) + assert expected == actual + + +def test_parse_job_path(): + expected = { + "project": "abalone", + "location": "squid", + "job": "clam", + } + path = BackupDRClient.job_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_job_path(path) + assert expected == actual + + def test_management_server_path(): - project = "squid" - location = "clam" - managementserver = "whelk" + project = "whelk" + location = "octopus" + managementserver = "oyster" expected = "projects/{project}/locations/{location}/managementServers/{managementserver}".format( project=project, location=location, @@ -45619,9 +60972,9 @@ def test_management_server_path(): def test_parse_management_server_path(): expected = { - "project": "octopus", - "location": "oyster", - "managementserver": "nudibranch", + "project": "nudibranch", + "location": "cuttlefish", + "managementserver": "mussel", } path = BackupDRClient.management_server_path(**expected) @@ -45630,10 +60983,126 @@ def test_parse_management_server_path(): assert expected == actual +def test_restore_template_path(): + project = "winkle" + location = "nautilus" + restore_template = "scallop" + expected = "projects/{project}/locations/{location}/restoreTemplates/{restore_template}".format( + project=project, + location=location, + restore_template=restore_template, + ) + actual = BackupDRClient.restore_template_path(project, location, restore_template) + assert expected == actual + + +def test_parse_restore_template_path(): + expected = { + "project": "abalone", + "location": "squid", + "restore_template": "clam", + } + path = BackupDRClient.restore_template_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_restore_template_path(path) + assert expected == actual + + +def test_restore_template_execution_path(): + project = "whelk" + location = "octopus" + restore_template = "oyster" + execution = "nudibranch" + expected = "projects/{project}/locations/{location}/restoreTemplates/{restore_template}/executions/{execution}".format( + project=project, + location=location, + restore_template=restore_template, + execution=execution, + ) + actual = BackupDRClient.restore_template_execution_path( + project, location, restore_template, execution + ) + assert expected == actual + + +def test_parse_restore_template_execution_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "restore_template": "winkle", + "execution": "nautilus", + } + path = BackupDRClient.restore_template_execution_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_restore_template_execution_path(path) + assert expected == actual + + +def test_restore_verification_plan_path(): + project = "scallop" + location = "abalone" + restoreVerificationPlan = "squid" + expected = "projects/{project}/locations/{location}/restoreVerificationPlans/{restoreVerificationPlan}".format( + project=project, + location=location, + restoreVerificationPlan=restoreVerificationPlan, + ) + actual = BackupDRClient.restore_verification_plan_path( + project, location, restoreVerificationPlan + ) + assert expected == actual + + +def test_parse_restore_verification_plan_path(): + expected = { + "project": "clam", + "location": "whelk", + "restoreVerificationPlan": "octopus", + } + path = BackupDRClient.restore_verification_plan_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_restore_verification_plan_path(path) + assert expected == actual + + +def test_restore_verification_plan_association_path(): + project = "oyster" + location = "nudibranch" + restore_verification_plan = "cuttlefish" + association = "mussel" + expected = "projects/{project}/locations/{location}/restoreVerificationPlans/{restore_verification_plan}/associations/{association}".format( + project=project, + location=location, + restore_verification_plan=restore_verification_plan, + association=association, + ) + actual = BackupDRClient.restore_verification_plan_association_path( + project, location, restore_verification_plan, association + ) + assert expected == actual + + +def test_parse_restore_verification_plan_association_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "restore_verification_plan": "scallop", + "association": "abalone", + } + path = BackupDRClient.restore_verification_plan_association_path(**expected) + + # Check that the path construction is reversible. + actual = BackupDRClient.parse_restore_verification_plan_association_path(path) + assert expected == actual + + def test_storage_pool_path(): - project = "cuttlefish" - zone = "mussel" - storage_pool = "winkle" + project = "squid" + zone = "clam" + storage_pool = "whelk" expected = "projects/{project}/zones/{zone}/storagePools/{storage_pool}".format( project=project, zone=zone, @@ -45645,9 +61114,9 @@ def test_storage_pool_path(): def test_parse_storage_pool_path(): expected = { - "project": "nautilus", - "zone": "scallop", - "storage_pool": "abalone", + "project": "octopus", + "zone": "oyster", + "storage_pool": "nudibranch", } path = BackupDRClient.storage_pool_path(**expected) @@ -45657,7 +61126,7 @@ def test_parse_storage_pool_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "cuttlefish" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -45667,7 +61136,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "mussel", } path = BackupDRClient.common_billing_account_path(**expected) @@ -45677,7 +61146,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "winkle" expected = "folders/{folder}".format( folder=folder, ) @@ -45687,7 +61156,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "nautilus", } path = BackupDRClient.common_folder_path(**expected) @@ -45697,7 +61166,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "scallop" expected = "organizations/{organization}".format( organization=organization, ) @@ -45707,7 +61176,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "abalone", } path = BackupDRClient.common_organization_path(**expected) @@ -45717,7 +61186,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "squid" expected = "projects/{project}".format( project=project, ) @@ -45727,7 +61196,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "clam", } path = BackupDRClient.common_project_path(**expected) @@ -45737,8 +61206,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -45749,8 +61218,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "oyster", + "location": "nudibranch", } path = BackupDRClient.common_location_path(**expected) 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 1fa580ab6bb4..322ab57e05fc 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 @@ -1229,6 +1229,16 @@ class InstanceSelection(proto.Message): have the same preference. This field is a member of `oneof`_ ``_rank``. + disks (MutableSequence[google.cloud.batch_v1alpha.types.AllocationPolicy.AttachedDisk]): + Optional. List of disks to be attached to + instances created from this selection. They + override the disks specified in the instance + properties. + boot_disk (google.cloud.batch_v1alpha.types.AllocationPolicy.Disk): + Optional. Boot disk to be created and attached to instances + created from this selection. It overrides the boot disk + specified in the instance properties. (e.g., overriding + ``boot`` disk type to Hyperdisk for 4th-gen machine types) """ machine_types: MutableSequence[str] = proto.RepeatedField( @@ -1240,6 +1250,16 @@ class InstanceSelection(proto.Message): number=2, optional=True, ) + disks: MutableSequence["AllocationPolicy.AttachedDisk"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="AllocationPolicy.AttachedDisk", + ) + boot_disk: "AllocationPolicy.Disk" = proto.Field( + proto.MESSAGE, + number=4, + message="AllocationPolicy.Disk", + ) location: LocationPolicy = proto.Field( proto.MESSAGE, diff --git a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/types/cloudbuild.py b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/types/cloudbuild.py index c344d0c00478..09b018bf70dd 100644 --- a/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/types/cloudbuild.py +++ b/packages/google-cloud-build/google/cloud/devtools/cloudbuild_v1/types/cloudbuild.py @@ -3685,10 +3685,15 @@ class VerifyOption(proto.Enum): Not a verifiable build (the default). VERIFIED (1): Build must be verified. + BEST_EFFORT (3): + Build verification is best effort. If + provenance generation fails, the build will + still succeed. """ NOT_VERIFIED = 0 VERIFIED = 1 + BEST_EFFORT = 3 class MachineType(proto.Enum): r"""Supported Compute Engine machine types. For more information, see @@ -3802,8 +3807,9 @@ class DefaultLogsBucketBehavior(proto.Enum): write to Cloud Storage buckets in the build project. LEGACY_BUCKET (2): - Bucket is located in a Google-owned project - and is not regionalized. + Deprecated: Use ``REGIONAL_USER_OWNED_BUCKET`` instead. + Bucket is located in a Google-owned project and is not + regionalized. """ DEFAULT_LOGS_BUCKET_BEHAVIOR_UNSPECIFIED = 0 @@ -4246,8 +4252,9 @@ class PrivatePoolV1Config(proto.Message): network_config (google.cloud.devtools.cloudbuild_v1.types.PrivatePoolV1Config.NetworkConfig): Network configuration for the pool. private_service_connect (google.cloud.devtools.cloudbuild_v1.types.PrivatePoolV1Config.PrivateServiceConnect): - Immutable. Private Service Connect(PSC) - Network configuration for the pool. + Immutable. Deprecated: Private Service + Connect is no longer supported. Private Service + Connect(PSC) Network configuration for the pool. """ class WorkerConfig(proto.Message): @@ -4360,7 +4367,8 @@ class EgressOption(proto.Enum): ) class PrivateServiceConnect(proto.Message): - r"""Defines the Private Service Connect network configuration for + r"""Deprecated: Private Service Connect is no longer supported. + Defines the Private Service Connect network configuration for the pool. Attributes: 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 f98bc9cb8bdc..06d03e6e97b4 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 @@ -23338,6 +23338,9 @@ class BackendServiceHAPolicy(proto.Message): Advertisement(RA) packet (IPv6). Google Cloud immediately but temporarily associates the forwarding rule IP address with that VM, and both new and in-flight packets are quickly delivered to that VM. + - HA_CONTROLLER: The Backend Service is managed by a High Availability + Controller. Failover and leader election are exclusively managed by the + HA Controller service. Note the important properties of the Fast IP Move functionality: @@ -23439,6 +23442,9 @@ class FastIPMove(proto.Enum): Advertisement(RA) packet (IPv6). Google Cloud immediately but temporarily associates the forwarding rule IP address with that VM, and both new and in-flight packets are quickly delivered to that VM. + - HA_CONTROLLER: The Backend Service is managed by a High Availability + Controller. Failover and leader election are exclusively managed by the + HA Controller service. Note the important properties of the Fast IP Move functionality: @@ -25584,8 +25590,14 @@ class BulkInsertInstanceResource(proto.Message): This field is a member of `oneof`_ ``_count``. instance_flexibility_policy (google.cloud.compute_v1beta.types.InstanceFlexibilityPolicy): - A flexible specification of machine type of - instances to create. + A specification of alternative machine types + to use when creating instances. A single + bulkInsert request can create instances with + multiple different machine types based on + capacity and quota availability. This field is + supported only for regional bulkInsert requests. + For more information, see About + instance flexibility for VMs created in bulk. This field is a member of `oneof`_ ``_instance_flexibility_policy``. instance_properties (google.cloud.compute_v1beta.types.InstanceProperties): @@ -26115,9 +26127,11 @@ class CacheInvalidationRule(proto.Message): This field is a member of `oneof`_ ``_content_type``. host (str): - If set, this invalidation rule will only - apply to requests with a Host header matching - host. + If set, this invalidation rule will only apply to requests + with a Host header matching host. This field also accepts + wildcards (\*) to replace the leftmost (or first) label of a + hostname. For example, \*.example.com will match + www.example.com, but not sub1.dev.example.com. This field is a member of `oneof`_ ``_host``. http_status (int): @@ -28719,6 +28733,8 @@ class Type(proto.Enum): No description available. COMPUTE_OPTIMIZED_H4D (383251320): No description available. + COMPUTE_OPTIMIZED_H4D_3TB (443379866): + CUD bucket for COMPUTE_OPTIMIZED_H4D_3TB machines. GENERAL_PURPOSE (299793543): No description available. GENERAL_PURPOSE_C4 (301911817): @@ -28816,6 +28832,7 @@ class Type(proto.Enum): COMPUTE_OPTIMIZED_C3D = 383246484 COMPUTE_OPTIMIZED_H3 = 428004939 COMPUTE_OPTIMIZED_H4D = 383251320 + COMPUTE_OPTIMIZED_H4D_3TB = 443379866 GENERAL_PURPOSE = 299793543 GENERAL_PURPOSE_C4 = 301911817 GENERAL_PURPOSE_C4A = 232460888 @@ -68013,17 +68030,8 @@ class InstanceFlexibilityPolicy(proto.Message): Attributes: instance_selections (MutableMapping[str, google.cloud.compute_v1beta.types.InstanceFlexibilityPolicyInstanceSelection]): - Specification of alternative, flexible - instance subsets. One of them will be selected - to create the instances based on various - criteria, like: - - - ranks, - - location policy, - - current capacity, - - available reservations (you can specify - affinity in InstanceProperties), - - SWAN/GOOSE limitations. + Specifies named instance selections that + define properties for instances created in bulk. Key is an arbitrary, unique RFC1035 string that identifies the instance selection. """ @@ -144073,6 +144081,15 @@ class RouterBgpPeer(proto.Message): Cloud Platform. This field is a member of `oneof`_ ``_ipv6_nexthop_address``. + linked_custom_hardware (str): + The linked custom hardware resource. + The URI of the custom hardware link attachment + is where you will establish the BGP session from + the Cloud Router. This link attachment must + reside in the same subnetwork as the associated + router interface. + + This field is a member of `oneof`_ ``_linked_custom_hardware``. management_type (str): Output only. [Output Only] The resource that configures and manages this BGP peer. @@ -144316,6 +144333,11 @@ class ManagementType(proto.Enum): number=27968211, optional=True, ) + linked_custom_hardware: str = proto.Field( + proto.STRING, + number=139494608, + optional=True, + ) management_type: str = proto.Field( proto.STRING, number=173703606, @@ -145742,6 +145764,14 @@ class RouterStatusBgpPeerStatus(proto.Message): interface. This field is a member of `oneof`_ ``_ipv6_nexthop_address``. + linked_custom_hardware (str): + Output only. The URI of the linked custom + hardware resource, CustomHardwareLinkAttachment. + This CustomHardwareLinkAttachment resource is + the one that will establish the BGP session from + the Cloud Router. + + This field is a member of `oneof`_ ``_linked_custom_hardware``. linked_vpn_tunnel (str): Output only. URL of the VPN tunnel that this BGP peer controls. @@ -145908,6 +145938,11 @@ class StatusReason(proto.Enum): number=27968211, optional=True, ) + linked_custom_hardware: str = proto.Field( + proto.STRING, + number=139494608, + optional=True, + ) linked_vpn_tunnel: str = proto.Field( proto.STRING, number=352296953, @@ -147252,10 +147287,15 @@ class Scheduling(proto.Message): This field is a member of `oneof`_ ``_provisioning_model``. skip_guest_os_shutdown (bool): - Default is false and there will be 120 + Defines whether GCE ACPI G2 Soft + Off signal should be skipped during shutdown + operation of VM. + + Default is false, meaning there will be 120 seconds between GCE ACPI G2 Soft Off and ACPI G3 - Mechanical Off for Standard VMs and 30 seconds - for Spot VMs. + Mechanical + Off for Standard VMs and 30 seconds for Spot + VMs. This field is a member of `oneof`_ ``_skip_guest_os_shutdown``. termination_time (str): @@ -172095,7 +172135,7 @@ class MinimalAction(proto.Enum): Engine acts based on the minimum action that the updated properties require. Additional supported values which may be not listed in the enum directly due to technical reasons: INVALID NO_EFFECT REFRESH - RESTART + RESTART RESTART_IN_PLACE Values: UNDEFINED_MINIMAL_ACTION (0): @@ -172112,7 +172152,7 @@ class MostDisruptiveAllowedAction(proto.Enum): the instance update. Valid options from lowest to highest are NO_EFFECT, REFRESH, and RESTART. Additional supported values which may be not listed in the enum directly due to technical reasons: - INVALID NO_EFFECT REFRESH RESTART + INVALID NO_EFFECT REFRESH RESTART RESTART_IN_PLACE Values: UNDEFINED_MOST_DISRUPTIVE_ALLOWED_ACTION (0): @@ -177633,9 +177673,11 @@ class VpnTunnelCipherSuite(proto.Message): Attributes: phase1 (google.cloud.compute_v1beta.types.VpnTunnelPhase1Algorithms): + Cipher algorithms for IKE phase 1. This field is a member of `oneof`_ ``_phase1``. phase2 (google.cloud.compute_v1beta.types.VpnTunnelPhase2Algorithms): + Cipher algorithms for IKE phase 2. This field is a member of `oneof`_ ``_phase2``. """ @@ -177765,13 +177807,14 @@ class VpnTunnelPhase1Algorithms(proto.Message): Attributes: dh (MutableSequence[str]): - + Diffie-Hellman groups for IKE phase 1. encryption (MutableSequence[str]): - + Encryption algorithms for IKE phase 1. integrity (MutableSequence[str]): - + Integrity algorithms for IKE phase 1. prf (MutableSequence[str]): - + Pseudo-random functions (PRF) for IKE phase + 1. """ dh: MutableSequence[str] = proto.RepeatedField( @@ -177797,11 +177840,12 @@ class VpnTunnelPhase2Algorithms(proto.Message): Attributes: encryption (MutableSequence[str]): - + Encryption algorithms for IKE phase 2. integrity (MutableSequence[str]): - + Integrity algorithms for IKE phase 2. pfs (MutableSequence[str]): - + Perfect Forward Secrecy (PFS) groups for IKE + phase 2. """ encryption: MutableSequence[str] = proto.RepeatedField( @@ -179231,8 +179275,33 @@ class WorkloadIdentityConfig(proto.Message): identity_certificate_enabled (bool): This field is a member of `oneof`_ ``_identity_certificate_enabled``. + identity_type (str): + Check the IdentityType enum for the list of + possible values. + + This field is a member of `oneof`_ ``_identity_type``. """ + class IdentityType(proto.Enum): + r""" + + Values: + UNDEFINED_IDENTITY_TYPE (0): + A value indicating that the enum field is not + set. + AGENT_IDENTITY (71547096): + No description available. + IDENTITY_TYPE_UNSPECIFIED (157537011): + No description available. + SERVICE_ACCOUNT (178301539): + No description available. + """ + + UNDEFINED_IDENTITY_TYPE = 0 + AGENT_IDENTITY = 71547096 + IDENTITY_TYPE_UNSPECIFIED = 157537011 + SERVICE_ACCOUNT = 178301539 + identity: str = proto.Field( proto.STRING, number=401109182, @@ -179243,6 +179312,11 @@ class WorkloadIdentityConfig(proto.Message): number=342892440, optional=True, ) + identity_type: str = proto.Field( + proto.STRING, + number=25665051, + optional=True, + ) class XpnHostList(proto.Message): 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 99e163f19c61..e84eeb1ee403 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 @@ -3805,6 +3805,7 @@ def test_insert_rest_call_success(request_type): "workload_identity_config": { "identity": "identity_value", "identity_certificate_enabled": True, + "identity_type": "identity_type_value", }, }, "region": "region_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 89eb8e37955c..16c9efc4a1a5 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 @@ -22753,6 +22753,7 @@ def test_bulk_insert_rest_call_success(request_type): "workload_identity_config": { "identity": "identity_value", "identity_certificate_enabled": True, + "identity_type": "identity_type_value", }, }, "location_policy": { @@ -25355,6 +25356,7 @@ def test_insert_rest_call_success(request_type): "workload_identity_config": { "identity": "identity_value", "identity_certificate_enabled": True, + "identity_type": "identity_type_value", }, "zone": "zone_value", } @@ -32503,6 +32505,7 @@ def test_update_rest_call_success(request_type): "workload_identity_config": { "identity": "identity_value", "identity_certificate_enabled": True, + "identity_type": "identity_type_value", }, "zone": "zone_value", } diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py index e727f896f0ec..211ed5435c7a 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 @@ -3758,6 +3758,7 @@ def test_insert_rest_call_success(request_type): "workload_identity_config": { "identity": "identity_value", "identity_certificate_enabled": True, + "identity_type": "identity_type_value", }, }, "kind": "kind_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py index b969f7acf1ff..4dccced55ac3 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 @@ -2807,6 +2807,7 @@ def test_insert_rest_call_success(request_type): "workload_identity_config": { "identity": "identity_value", "identity_certificate_enabled": True, + "identity_type": "identity_type_value", }, }, "region": "region_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 b9fad5efca33..db3bab1f3953 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 @@ -1630,6 +1630,7 @@ def test_bulk_insert_rest_call_success(request_type): "workload_identity_config": { "identity": "identity_value", "identity_certificate_enabled": True, + "identity_type": "identity_type_value", }, }, "location_policy": { 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 32b9106be4a1..024bb5d9e236 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 @@ -9305,6 +9305,7 @@ def test_insert_rest_call_success(request_type): "ip_address": "ip_address_value", "ipv4_nexthop_address": "ipv4_nexthop_address_value", "ipv6_nexthop_address": "ipv6_nexthop_address_value", + "linked_custom_hardware": "linked_custom_hardware_value", "management_type": "management_type_value", "md5_authentication_key_name": "md5_authentication_key_name_value", "name": "name_value", @@ -10224,6 +10225,7 @@ def test_patch_rest_call_success(request_type): "ip_address": "ip_address_value", "ipv4_nexthop_address": "ipv4_nexthop_address_value", "ipv6_nexthop_address": "ipv6_nexthop_address_value", + "linked_custom_hardware": "linked_custom_hardware_value", "management_type": "management_type_value", "md5_authentication_key_name": "md5_authentication_key_name_value", "name": "name_value", @@ -11109,6 +11111,7 @@ def test_preview_rest_call_success(request_type): "ip_address": "ip_address_value", "ipv4_nexthop_address": "ipv4_nexthop_address_value", "ipv6_nexthop_address": "ipv6_nexthop_address_value", + "linked_custom_hardware": "linked_custom_hardware_value", "management_type": "management_type_value", "md5_authentication_key_name": "md5_authentication_key_name_value", "name": "name_value", @@ -11647,6 +11650,7 @@ def test_update_rest_call_success(request_type): "ip_address": "ip_address_value", "ipv4_nexthop_address": "ipv4_nexthop_address_value", "ipv6_nexthop_address": "ipv6_nexthop_address_value", + "linked_custom_hardware": "linked_custom_hardware_value", "management_type": "management_type_value", "md5_authentication_key_name": "md5_authentication_key_name_value", "name": "name_value", 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 26e8bcc8aba7..53f620840dba 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 @@ -21218,6 +21218,9 @@ class BackendServiceHAPolicy(proto.Message): Advertisement(RA) packet (IPv6). Google Cloud immediately but temporarily associates the forwarding rule IP address with that VM, and both new and in-flight packets are quickly delivered to that VM. + - HA_CONTROLLER: The Backend Service is managed by a High Availability + Controller. Failover and leader election are exclusively managed by the + HA Controller service. Note the important properties of the Fast IP Move functionality: @@ -21319,6 +21322,9 @@ class FastIPMove(proto.Enum): Advertisement(RA) packet (IPv6). Google Cloud immediately but temporarily associates the forwarding rule IP address with that VM, and both new and in-flight packets are quickly delivered to that VM. + - HA_CONTROLLER: The Backend Service is managed by a High Availability + Controller. Failover and leader election are exclusively managed by the + HA Controller service. Note the important properties of the Fast IP Move functionality: @@ -23440,8 +23446,14 @@ class BulkInsertInstanceResource(proto.Message): This field is a member of `oneof`_ ``_count``. instance_flexibility_policy (google.cloud.compute_v1.types.InstanceFlexibilityPolicy): - A flexible specification of machine type of - instances to create. + A specification of alternative machine types + to use when creating instances. A single + bulkInsert request can create instances with + multiple different machine types based on + capacity and quota availability. This field is + supported only for regional bulkInsert requests. + For more information, see About + instance flexibility for VMs created in bulk. This field is a member of `oneof`_ ``_instance_flexibility_policy``. instance_properties (google.cloud.compute_v1.types.InstanceProperties): @@ -23952,9 +23964,11 @@ class CacheInvalidationRule(proto.Message): Up to 10 tags can be specified in a single invalidation request. host (str): - If set, this invalidation rule will only - apply to requests with a Host header matching - host. + If set, this invalidation rule will only apply to requests + with a Host header matching host. This field also accepts + wildcards (\*) to replace the leftmost (or first) label of a + hostname. For example, \*.example.com will match + www.example.com, but not sub1.dev.example.com. This field is a member of `oneof`_ ``_host``. path (str): @@ -26385,6 +26399,12 @@ class Type(proto.Enum): No description available. MEMORY_OPTIMIZED_M4 (276301373): No description available. + MEMORY_OPTIMIZED_M4N (512278961): + CUD bucket for M4N machines with less than + 6TB of memory. + MEMORY_OPTIMIZED_M4N_6TB (69895574): + CUD bucket for M4N machines with 6TB of + memory. MEMORY_OPTIMIZED_M4_6TB (210543650): No description available. MEMORY_OPTIMIZED_X4_1440_24T (206669823): @@ -26466,6 +26486,8 @@ class Type(proto.Enum): MEMORY_OPTIMIZED = 281753417 MEMORY_OPTIMIZED_M3 = 276301372 MEMORY_OPTIMIZED_M4 = 276301373 + MEMORY_OPTIMIZED_M4N = 512278961 + MEMORY_OPTIMIZED_M4N_6TB = 69895574 MEMORY_OPTIMIZED_M4_6TB = 210543650 MEMORY_OPTIMIZED_X4_1440_24T = 206669823 MEMORY_OPTIMIZED_X4_16TB = 183089120 @@ -62609,17 +62631,8 @@ class InstanceFlexibilityPolicy(proto.Message): Attributes: instance_selections (MutableMapping[str, google.cloud.compute_v1.types.InstanceFlexibilityPolicyInstanceSelection]): - Specification of alternative, flexible - instance subsets. One of them will be selected - to create the instances based on various - criteria, like: - - - ranks, - - location policy, - - current capacity, - - available reservations (you can specify - affinity in InstanceProperties), - - SWAN/GOOSE limitations. + Specifies named instance selections that + define properties for instances created in bulk. Key is an arbitrary, unique RFC1035 string that identifies the instance selection. """ @@ -132518,10 +132531,15 @@ class Scheduling(proto.Message): This field is a member of `oneof`_ ``_provisioning_model``. skip_guest_os_shutdown (bool): - Default is false and there will be 120 + Defines whether GCE ACPI G2 Soft + Off signal should be skipped during shutdown + operation of VM. + + Default is false, meaning there will be 120 seconds between GCE ACPI G2 Soft Off and ACPI G3 - Mechanical Off for Standard VMs and 30 seconds - for Spot VMs. + Mechanical + Off for Standard VMs and 30 seconds for Spot + VMs. This field is a member of `oneof`_ ``_skip_guest_os_shutdown``. termination_time (str): @@ -159953,9 +159971,11 @@ class VpnTunnelCipherSuite(proto.Message): Attributes: phase1 (google.cloud.compute_v1.types.VpnTunnelPhase1Algorithms): + Cipher algorithms for IKE phase 1. This field is a member of `oneof`_ ``_phase1``. phase2 (google.cloud.compute_v1.types.VpnTunnelPhase2Algorithms): + Cipher algorithms for IKE phase 2. This field is a member of `oneof`_ ``_phase2``. """ @@ -160085,13 +160105,14 @@ class VpnTunnelPhase1Algorithms(proto.Message): Attributes: dh (MutableSequence[str]): - + Diffie-Hellman groups for IKE phase 1. encryption (MutableSequence[str]): - + Encryption algorithms for IKE phase 1. integrity (MutableSequence[str]): - + Integrity algorithms for IKE phase 1. prf (MutableSequence[str]): - + Pseudo-random functions (PRF) for IKE phase + 1. """ dh: MutableSequence[str] = proto.RepeatedField( @@ -160117,11 +160138,12 @@ class VpnTunnelPhase2Algorithms(proto.Message): Attributes: encryption (MutableSequence[str]): - + Encryption algorithms for IKE phase 2. integrity (MutableSequence[str]): - + Integrity algorithms for IKE phase 2. pfs (MutableSequence[str]): - + Perfect Forward Secrecy (PFS) groups for IKE + phase 2. """ encryption: MutableSequence[str] = proto.RepeatedField( diff --git a/packages/google-cloud-dataform/google/cloud/dataform/__init__.py b/packages/google-cloud-dataform/google/cloud/dataform/__init__.py index 183901fe27d7..39d2ea531267 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform/__init__.py +++ b/packages/google-cloud-dataform/google/cloud/dataform/__init__.py @@ -40,6 +40,7 @@ ComputeRepositoryAccessTokenStatusRequest, ComputeRepositoryAccessTokenStatusResponse, Config, + CreateCompilationResultMetadata, CreateCompilationResultRequest, CreateFolderRequest, CreateReleaseConfigRequest, @@ -81,6 +82,8 @@ FetchRepositoryHistoryResponse, FetchWorkspaceBranchesRequest, FetchWorkspaceBranchesResponse, + FetchWorkspaceHistoryRequest, + FetchWorkspaceHistoryResponse, FileSearchResult, FilesystemEntryMetadata, Folder, @@ -202,6 +205,7 @@ "ComputeRepositoryAccessTokenStatusRequest", "ComputeRepositoryAccessTokenStatusResponse", "Config", + "CreateCompilationResultMetadata", "CreateCompilationResultRequest", "CreateFolderRequest", "CreateReleaseConfigRequest", @@ -242,6 +246,8 @@ "FetchRepositoryHistoryResponse", "FetchWorkspaceBranchesRequest", "FetchWorkspaceBranchesResponse", + "FetchWorkspaceHistoryRequest", + "FetchWorkspaceHistoryResponse", "FileSearchResult", "FilesystemEntryMetadata", "Folder", diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/__init__.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/__init__.py index adec3ad84f5d..6079206ec133 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/__init__.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/__init__.py @@ -48,6 +48,7 @@ ComputeRepositoryAccessTokenStatusRequest, ComputeRepositoryAccessTokenStatusResponse, Config, + CreateCompilationResultMetadata, CreateCompilationResultRequest, CreateFolderRequest, CreateReleaseConfigRequest, @@ -192,6 +193,7 @@ "ComputeRepositoryAccessTokenStatusRequest", "ComputeRepositoryAccessTokenStatusResponse", "Config", + "CreateCompilationResultMetadata", "CreateCompilationResultRequest", "CreateFolderRequest", "CreateReleaseConfigRequest", diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/gapic_metadata.json b/packages/google-cloud-dataform/google/cloud/dataform_v1/gapic_metadata.json index 5e1e3e3aca54..1839d726b99d 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/gapic_metadata.json +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/gapic_metadata.json @@ -35,6 +35,11 @@ "create_compilation_result" ] }, + "CreateCompilationResultLongRunning": { + "methods": [ + "create_compilation_result_long_running" + ] + }, "CreateFolder": { "methods": [ "create_folder" @@ -405,6 +410,11 @@ "create_compilation_result" ] }, + "CreateCompilationResultLongRunning": { + "methods": [ + "create_compilation_result_long_running" + ] + }, "CreateFolder": { "methods": [ "create_folder" @@ -775,6 +785,11 @@ "create_compilation_result" ] }, + "CreateCompilationResultLongRunning": { + "methods": [ + "create_compilation_result_long_running" + ] + }, "CreateFolder": { "methods": [ "create_folder" diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py index 3d33f902ee0e..325acbe0bdc1 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/async_client.py @@ -6384,6 +6384,147 @@ async def sample_create_compilation_result(): # Done; return the response. return response + async def create_compilation_result_long_running( + self, + request: Optional[Union[dataform.CreateCompilationResultRequest, dict]] = None, + *, + parent: Optional[str] = None, + compilation_result: Optional[dataform.CompilationResult] = 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"""Creates a new CompilationResult in a given project + and location asynchronously. + + .. 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 dataform_v1 + + async def sample_create_compilation_result_long_running(): + # Create a client + client = dataform_v1.DataformAsyncClient() + + # Initialize request argument(s) + compilation_result = dataform_v1.CompilationResult() + compilation_result.git_commitish = "git_commitish_value" + + request = dataform_v1.CreateCompilationResultRequest( + parent="parent_value", + compilation_result=compilation_result, + ) + + # Make the request + operation = await client.create_compilation_result_long_running(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dataform_v1.types.CreateCompilationResultRequest, dict]]): + The request object. ``CreateCompilationResult`` request message. + parent (:class:`str`): + Required. The repository in which to create the + compilation result. Must be in the format + ``projects/*/locations/*/repositories/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + compilation_result (:class:`google.cloud.dataform_v1.types.CompilationResult`): + Required. The compilation result to + create. + + This corresponds to the ``compilation_result`` 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.dataform_v1.types.CompilationResult` + Represents the result of compiling a Dataform project. + + """ + # 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, compilation_result] + 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, dataform.CreateCompilationResultRequest): + request = dataform.CreateCompilationResultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if compilation_result is not None: + request.compilation_result = compilation_result + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_compilation_result_long_running + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dataform.CompilationResult, + metadata_type=dataform.CreateCompilationResultMetadata, + ) + + # Done; return the response. + return response + async def query_compilation_result_actions( self, request: Optional[ diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py index ad48de2022ab..052a2dfa9238 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/client.py @@ -6822,6 +6822,146 @@ def sample_create_compilation_result(): # Done; return the response. return response + def create_compilation_result_long_running( + self, + request: Optional[Union[dataform.CreateCompilationResultRequest, dict]] = None, + *, + parent: Optional[str] = None, + compilation_result: Optional[dataform.CompilationResult] = 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"""Creates a new CompilationResult in a given project + and location asynchronously. + + .. 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 dataform_v1 + + def sample_create_compilation_result_long_running(): + # Create a client + client = dataform_v1.DataformClient() + + # Initialize request argument(s) + compilation_result = dataform_v1.CompilationResult() + compilation_result.git_commitish = "git_commitish_value" + + request = dataform_v1.CreateCompilationResultRequest( + parent="parent_value", + compilation_result=compilation_result, + ) + + # Make the request + operation = client.create_compilation_result_long_running(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dataform_v1.types.CreateCompilationResultRequest, dict]): + The request object. ``CreateCompilationResult`` request message. + parent (str): + Required. The repository in which to create the + compilation result. Must be in the format + ``projects/*/locations/*/repositories/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + compilation_result (google.cloud.dataform_v1.types.CompilationResult): + Required. The compilation result to + create. + + This corresponds to the ``compilation_result`` 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.dataform_v1.types.CompilationResult` + Represents the result of compiling a Dataform project. + + """ + # 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, compilation_result] + 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, dataform.CreateCompilationResultRequest): + request = dataform.CreateCompilationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if compilation_result is not None: + request.compilation_result = compilation_result + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_compilation_result_long_running + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dataform.CompilationResult, + metadata_type=dataform.CreateCompilationResultMetadata, + ) + + # Done; return the response. + return response + def query_compilation_result_actions( self, request: Optional[ diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/base.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/base.py index d407df9f39db..59f34a045228 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/base.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/base.py @@ -432,6 +432,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_compilation_result_long_running: gapic_v1.method.wrap_method( + self.create_compilation_result_long_running, + default_timeout=None, + client_info=client_info, + ), self.query_compilation_result_actions: gapic_v1.method.wrap_method( self.query_compilation_result_actions, default_timeout=None, @@ -1138,6 +1143,15 @@ def create_compilation_result( ]: raise NotImplementedError() + @property + def create_compilation_result_long_running( + self, + ) -> Callable[ + [dataform.CreateCompilationResultRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def query_compilation_result_actions( self, diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/grpc.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/grpc.py index fb4cb2587d90..464e86ce3932 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/grpc.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/grpc.py @@ -1905,6 +1905,36 @@ def create_compilation_result( ) return self._stubs["create_compilation_result"] + @property + def create_compilation_result_long_running( + self, + ) -> Callable[[dataform.CreateCompilationResultRequest], operations_pb2.Operation]: + r"""Return a callable for the create compilation result long + running method over gRPC. + + Creates a new CompilationResult in a given project + and location asynchronously. + + Returns: + Callable[[~.CreateCompilationResultRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_compilation_result_long_running" not in self._stubs: + self._stubs["create_compilation_result_long_running"] = ( + self._logged_channel.unary_unary( + "/google.cloud.dataform.v1.Dataform/CreateCompilationResultLongRunning", + request_serializer=dataform.CreateCompilationResultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_compilation_result_long_running"] + @property def query_compilation_result_actions( self, diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/grpc_asyncio.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/grpc_asyncio.py index 7f3348ed7d52..ea74e76cf6ae 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/grpc_asyncio.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/grpc_asyncio.py @@ -1955,6 +1955,38 @@ def create_compilation_result( ) return self._stubs["create_compilation_result"] + @property + def create_compilation_result_long_running( + self, + ) -> Callable[ + [dataform.CreateCompilationResultRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create compilation result long + running method over gRPC. + + Creates a new CompilationResult in a given project + and location asynchronously. + + Returns: + Callable[[~.CreateCompilationResultRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_compilation_result_long_running" not in self._stubs: + self._stubs["create_compilation_result_long_running"] = ( + self._logged_channel.unary_unary( + "/google.cloud.dataform.v1.Dataform/CreateCompilationResultLongRunning", + request_serializer=dataform.CreateCompilationResultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_compilation_result_long_running"] + @property def query_compilation_result_actions( self, @@ -2752,6 +2784,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_compilation_result_long_running: self._wrap_method( + self.create_compilation_result_long_running, + default_timeout=None, + client_info=client_info, + ), self.query_compilation_result_actions: self._wrap_method( self.query_compilation_result_actions, default_timeout=None, diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/rest.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/rest.py index f7e4304f1b77..538ca31fa380 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/rest.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/rest.py @@ -121,6 +121,14 @@ def post_create_compilation_result(self, response): logging.log(f"Received response: {response}") return response + def pre_create_compilation_result_long_running(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_compilation_result_long_running(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_folder(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -896,6 +904,54 @@ def post_create_compilation_result_with_metadata( """ return response, metadata + def pre_create_compilation_result_long_running( + self, + request: dataform.CreateCompilationResultRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dataform.CreateCompilationResultRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_compilation_result_long_running + + Override in a subclass to manipulate the request or metadata + before they are sent to the Dataform server. + """ + return request, metadata + + def post_create_compilation_result_long_running( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_compilation_result_long_running + + DEPRECATED. Please use the `post_create_compilation_result_long_running_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Dataform server but before + it is returned to user code. This `post_create_compilation_result_long_running` interceptor runs + before the `post_create_compilation_result_long_running_with_metadata` interceptor. + """ + return response + + def post_create_compilation_result_long_running_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_compilation_result_long_running + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Dataform server but before it is returned to user code. + + We recommend only using this `post_create_compilation_result_long_running_with_metadata` + interceptor in new development instead of the `post_create_compilation_result_long_running` interceptor. + When both interceptors are used, this `post_create_compilation_result_long_running_with_metadata` interceptor runs after the + `post_create_compilation_result_long_running` interceptor. The (possibly modified) response returned by + `post_create_compilation_result_long_running` will be passed to + `post_create_compilation_result_long_running_with_metadata`. + """ + return response, metadata + def pre_create_folder( self, request: dataform.CreateFolderRequest, @@ -4969,6 +5025,162 @@ def __call__( ) return resp + class _CreateCompilationResultLongRunning( + _BaseDataformRestTransport._BaseCreateCompilationResultLongRunning, + DataformRestStub, + ): + def __hash__(self): + return hash("DataformRestTransport.CreateCompilationResultLongRunning") + + @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: dataform.CreateCompilationResultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create compilation result + long running method over HTTP. + + Args: + request (~.dataform.CreateCompilationResultRequest): + The request object. ``CreateCompilationResult`` request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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 = _BaseDataformRestTransport._BaseCreateCompilationResultLongRunning._get_http_options() + request, metadata = ( + self._interceptor.pre_create_compilation_result_long_running( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataformRestTransport._BaseCreateCompilationResultLongRunning, + "_BaseCreateCompilationResultLongRunning__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.dataform_v1.DataformClient.CreateCompilationResultLongRunning", + extra={ + "serviceName": "google.cloud.dataform.v1.Dataform", + "rpcName": "CreateCompilationResultLongRunning", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DataformRestTransport._CreateCompilationResultLongRunning._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_compilation_result_long_running(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_compilation_result_long_running_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.dataform_v1.DataformClient.create_compilation_result_long_running", + extra={ + "serviceName": "google.cloud.dataform.v1.Dataform", + "rpcName": "CreateCompilationResultLongRunning", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _CreateFolder(_BaseDataformRestTransport._BaseCreateFolder, DataformRestStub): def __hash__(self): return hash("DataformRestTransport.CreateFolder") @@ -14990,6 +15202,16 @@ def create_compilation_result( self._session, self._host, self._interceptor ) # type: ignore + @property + def create_compilation_result_long_running( + self, + ) -> Callable[[dataform.CreateCompilationResultRequest], 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._CreateCompilationResultLongRunning( + self._session, self._host, self._interceptor + ) # type: ignore + @property def create_folder( self, diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/rest_base.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/rest_base.py index 16168982393c..e4e12e0c8825 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/rest_base.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/services/dataform/transports/rest_base.py @@ -180,6 +180,23 @@ def _get_http_options(): ] return http_options + class _BaseCreateCompilationResultLongRunning: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/repositories/*}/compilationResults:createLongRunning", + "body": "compilation_result", + }, + ] + return http_options + class _BaseCreateFolder: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/types/__init__.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/types/__init__.py index ed81c76fd4a3..f88e7958ba16 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/types/__init__.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/types/__init__.py @@ -29,6 +29,7 @@ ComputeRepositoryAccessTokenStatusRequest, ComputeRepositoryAccessTokenStatusResponse, Config, + CreateCompilationResultMetadata, CreateCompilationResultRequest, CreateFolderRequest, CreateReleaseConfigRequest, @@ -172,6 +173,7 @@ "ComputeRepositoryAccessTokenStatusRequest", "ComputeRepositoryAccessTokenStatusResponse", "Config", + "CreateCompilationResultMetadata", "CreateCompilationResultRequest", "CreateFolderRequest", "CreateReleaseConfigRequest", diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py b/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py index 36322da763fd..d24a46f1769b 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1/types/dataform.py @@ -115,6 +115,7 @@ "ListCompilationResultsResponse", "GetCompilationResultRequest", "CreateCompilationResultRequest", + "CreateCompilationResultMetadata", "Target", "RelationDescriptor", "CompilationResultAction", @@ -1971,7 +1972,7 @@ class FileSearchResult(proto.Message): Attributes: path (str): - File system path relative to the workspace + File system path relative to the file tree root. """ @@ -3067,6 +3068,68 @@ class CreateCompilationResultRequest(proto.Message): ) +class CreateCompilationResultMetadata(proto.Message): + r"""Represents the metadata of the + ``CreateCompilationResultLongRunning`` operation. + + Attributes: + id (str): + Output only. The ID of the LRO. + target (str): + Output only. Server-defined resource path for + the target of the operation. + state (google.cloud.dataform_v1.types.CreateCompilationResultMetadata.State): + Output only. The state of the LRO. + create_compilation_result_request (google.cloud.dataform_v1.types.CreateCompilationResultRequest): + Output only. The CreateCompilationResult + requested. + """ + + class State(proto.Enum): + r"""State of the LRO. + + Values: + STATE_UNSPECIFIED (0): + The state is unspecified. + CREATED (1): + The LRO has been created. + RUNNING (2): + The LRO is in progress. + FINISHED (3): + The RPC call has finished. + SUCCEEDED (4): + The LRO has succeeded. + FAILED (5): + The LRO has failed. + """ + + STATE_UNSPECIFIED = 0 + CREATED = 1 + RUNNING = 2 + FINISHED = 3 + SUCCEEDED = 4 + FAILED = 5 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + target: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + create_compilation_result_request: "CreateCompilationResultRequest" = proto.Field( + proto.MESSAGE, + number=4, + message="CreateCompilationResultRequest", + ) + + class Target(proto.Message): r"""Represents an action identifier. If the action writes output, the output will be written to the referenced database object. @@ -3190,6 +3253,10 @@ class CompilationResultAction(proto.Message): data_preparation (google.cloud.dataform_v1.types.CompilationResultAction.DataPreparation): The data preparation executed by this action. + This field is a member of `oneof`_ ``compiled_object``. + bigquery_unit_test (google.cloud.dataform_v1.types.CompilationResultAction.BigQueryUnitTest): + The unit test executed by this action. + This field is a member of `oneof`_ ``compiled_object``. target (google.cloud.dataform_v1.types.Target): This action's identifier. Unique within the @@ -3725,6 +3792,53 @@ class ErrorTable(proto.Message): number=4, ) + class BigQueryUnitTest(proto.Message): + r"""Represents a BigQuery unit test. + + Attributes: + dependency_targets (MutableSequence[google.cloud.dataform_v1.types.Target]): + A list of actions that this action depends + on. + disabled (bool): + Whether this action is disabled (i.e. should + not be run). + tags (MutableSequence[str]): + Arbitrary, user-defined tags on this action. + display_name (str): + The name of the unit test. + test_query (str): + Test query to execute. + expected_output_query (str): + Expected output query to compare against the + test query. + """ + + dependency_targets: MutableSequence["Target"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Target", + ) + disabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + test_query: str = proto.Field( + proto.STRING, + number=5, + ) + expected_output_query: str = proto.Field( + proto.STRING, + number=6, + ) + class LoadConfig(proto.Message): r"""Simplified load configuration for actions @@ -3834,6 +3948,12 @@ class IncrementalLoadMode(proto.Message): oneof="compiled_object", message=DataPreparation, ) + bigquery_unit_test: BigQueryUnitTest = proto.Field( + proto.MESSAGE, + number=11, + oneof="compiled_object", + message=BigQueryUnitTest, + ) target: "Target" = proto.Field( proto.MESSAGE, number=1, @@ -4098,9 +4218,8 @@ class InvocationConfig(proto.Message): Optional. The service account to run workflow invocations under. end_user_auth_config (google.cloud.dataform_v1.types.InvocationConfig.EndUserAuthenticationConfig): - Optional. Configuration for end user authentication. Note - that this should not be set when ``service_account`` is - used. + Optional. Configuration for end user authentication. Do not + set if ``service_account`` is used. query_priority (google.cloud.dataform_v1.types.InvocationConfig.QueryPriority): Optional. Specifies the priority for query execution in BigQuery. More information can be @@ -4108,6 +4227,14 @@ class InvocationConfig(proto.Message): https://cloud.google.com/bigquery/docs/running-queries#queries. This field is a member of `oneof`_ ``_query_priority``. + concurrent_actions_limit (int): + Optional. Maximum number of actions that can + be executed concurrently. + + This field is a member of `oneof`_ ``_concurrent_actions_limit``. + execution_mode (google.cloud.dataform_v1.types.InvocationConfig.ExecutionMode): + Optional. Specifies the execution mode for + the workflow invocation. """ class QueryPriority(proto.Enum): @@ -4131,6 +4258,27 @@ class QueryPriority(proto.Enum): INTERACTIVE = 1 BATCH = 2 + class ExecutionMode(proto.Enum): + r"""Execution mode for the workflow invocation. + Determines whether to run actions or unit tests. + + Values: + EXECUTION_MODE_UNSPECIFIED (0): + Default value. + DEFAULT (1): + Default execution mode, which runs all actions except unit + tests. Same as ALL_EXCEPT_UNIT_TESTS. + ALL_EXCEPT_UNIT_TESTS (2): + Run all actions except unit tests. + UNIT_TESTS_ONLY (3): + Run unit tests only. + """ + + EXECUTION_MODE_UNSPECIFIED = 0 + DEFAULT = 1 + ALL_EXCEPT_UNIT_TESTS = 2 + UNIT_TESTS_ONLY = 3 + class EndUserAuthenticationConfig(proto.Message): r"""Includes configuration options for end user authentication. @@ -4189,6 +4337,16 @@ class EndUserAuthenticationConfig(proto.Message): optional=True, enum=QueryPriority, ) + concurrent_actions_limit: int = proto.Field( + proto.INT32, + number=10, + optional=True, + ) + execution_mode: ExecutionMode = proto.Field( + proto.ENUM, + number=16, + enum=ExecutionMode, + ) class ListWorkflowConfigsRequest(proto.Message): @@ -4672,6 +4830,11 @@ class WorkflowInvocationAction(proto.Message): Output only. The workflow action's data preparation action details. + This field is a member of `oneof`_ ``action``. + bigquery_unit_test_action (google.cloud.dataform_v1.types.WorkflowInvocationAction.BigQueryUnitTestAction): + Output only. The workflow action's unit test + details. + This field is a member of `oneof`_ ``action``. target (google.cloud.dataform_v1.types.Target): Output only. This action's identifier. Unique @@ -4723,6 +4886,9 @@ class State(proto.Enum): The action was cancelled. A terminal state. FAILED (6): The action failed. A terminal state. + QUEUED (7): + Execution of the action was queued waiting + for an available concurrency slot. """ PENDING = 0 @@ -4732,6 +4898,7 @@ class State(proto.Enum): SUCCEEDED = 4 CANCELLED = 5 FAILED = 6 + QUEUED = 7 class BigQueryAction(proto.Message): r"""Represents a workflow action that will run against BigQuery. @@ -4963,6 +5130,56 @@ class ActionIncrementalLoadMode(proto.Message): number=4, ) + class BigQueryUnitTestAction(proto.Message): + r"""Represents a workflow action that will run a BigQuery unit + test. + + Attributes: + actual_results_job_id (str): + Output only. Job ID for the actual results. + actual_results_sql_script (str): + Output only. SQL script for the actual + results. + expected_results_job_id (str): + Output only. Job ID for the expected results. + expected_results_sql_script (str): + Output only. SQL script for the expected + results. + total_processed_bytes (int): + Output only. Total bytes processed for this + action. Combined total for actual and expected + jobs. + total_billed_bytes (int): + Output only. Total bytes billed for this + action. Combined total for actual and expected + jobs. + """ + + actual_results_job_id: str = proto.Field( + proto.STRING, + number=1, + ) + actual_results_sql_script: str = proto.Field( + proto.STRING, + number=2, + ) + expected_results_job_id: str = proto.Field( + proto.STRING, + number=3, + ) + expected_results_sql_script: str = proto.Field( + proto.STRING, + number=4, + ) + total_processed_bytes: int = proto.Field( + proto.INT64, + number=5, + ) + total_billed_bytes: int = proto.Field( + proto.INT64, + number=6, + ) + bigquery_action: BigQueryAction = proto.Field( proto.MESSAGE, number=6, @@ -4981,6 +5198,12 @@ class ActionIncrementalLoadMode(proto.Message): oneof="action", message=DataPreparationAction, ) + bigquery_unit_test_action: BigQueryUnitTestAction = proto.Field( + proto.MESSAGE, + number=12, + oneof="action", + message=BigQueryUnitTestAction, + ) target: "Target" = proto.Field( proto.MESSAGE, number=1, diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/__init__.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/__init__.py index f6794cf2994e..d94ea1bbb564 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/__init__.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/__init__.py @@ -50,6 +50,7 @@ ComputeRepositoryAccessTokenStatusRequest, ComputeRepositoryAccessTokenStatusResponse, Config, + CreateCompilationResultMetadata, CreateCompilationResultRequest, CreateFolderRequest, CreateReleaseConfigRequest, @@ -91,6 +92,8 @@ FetchRepositoryHistoryResponse, FetchWorkspaceBranchesRequest, FetchWorkspaceBranchesResponse, + FetchWorkspaceHistoryRequest, + FetchWorkspaceHistoryResponse, FileSearchResult, FilesystemEntryMetadata, Folder, @@ -211,6 +214,7 @@ "ComputeRepositoryAccessTokenStatusRequest", "ComputeRepositoryAccessTokenStatusResponse", "Config", + "CreateCompilationResultMetadata", "CreateCompilationResultRequest", "CreateFolderRequest", "CreateReleaseConfigRequest", @@ -253,6 +257,8 @@ "FetchRepositoryHistoryResponse", "FetchWorkspaceBranchesRequest", "FetchWorkspaceBranchesResponse", + "FetchWorkspaceHistoryRequest", + "FetchWorkspaceHistoryResponse", "FileSearchResult", "FilesystemEntryMetadata", "Folder", diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/gapic_metadata.json b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/gapic_metadata.json index 8e76fbd62811..2f529100e784 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/gapic_metadata.json +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/gapic_metadata.json @@ -40,6 +40,11 @@ "create_compilation_result" ] }, + "CreateCompilationResultLongRunning": { + "methods": [ + "create_compilation_result_long_running" + ] + }, "CreateFolder": { "methods": [ "create_folder" @@ -165,6 +170,11 @@ "fetch_workspace_branches" ] }, + "FetchWorkspaceHistory": { + "methods": [ + "fetch_workspace_history" + ] + }, "GetCompilationResult": { "methods": [ "get_compilation_result" @@ -440,6 +450,11 @@ "create_compilation_result" ] }, + "CreateCompilationResultLongRunning": { + "methods": [ + "create_compilation_result_long_running" + ] + }, "CreateFolder": { "methods": [ "create_folder" @@ -565,6 +580,11 @@ "fetch_workspace_branches" ] }, + "FetchWorkspaceHistory": { + "methods": [ + "fetch_workspace_history" + ] + }, "GetCompilationResult": { "methods": [ "get_compilation_result" @@ -840,6 +860,11 @@ "create_compilation_result" ] }, + "CreateCompilationResultLongRunning": { + "methods": [ + "create_compilation_result_long_running" + ] + }, "CreateFolder": { "methods": [ "create_folder" @@ -965,6 +990,11 @@ "fetch_workspace_branches" ] }, + "FetchWorkspaceHistory": { + "methods": [ + "fetch_workspace_history" + ] + }, "GetCompilationResult": { "methods": [ "get_compilation_result" diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/async_client.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/async_client.py index bd18c0c8dc5f..ff73d6d3b418 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/async_client.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/async_client.py @@ -90,6 +90,10 @@ class DataformAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = DataformClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = DataformClient._DEFAULT_UNIVERSE + account_connector_path = staticmethod(DataformClient.account_connector_path) + parse_account_connector_path = staticmethod( + DataformClient.parse_account_connector_path + ) compilation_result_path = staticmethod(DataformClient.compilation_result_path) parse_compilation_result_path = staticmethod( DataformClient.parse_compilation_result_path @@ -4921,6 +4925,105 @@ async def sample_fetch_git_ahead_behind(): # Done; return the response. return response + async def fetch_workspace_history( + self, + request: Optional[Union[dataform.FetchWorkspaceHistoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchWorkspaceHistoryAsyncPager: + r"""Fetches a Workspace's history of commits. + + .. 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 dataform_v1beta1 + + async def sample_fetch_workspace_history(): + # Create a client + client = dataform_v1beta1.DataformAsyncClient() + + # Initialize request argument(s) + request = dataform_v1beta1.FetchWorkspaceHistoryRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_workspace_history(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryRequest, dict]]): + The request object. ``FetchWorkspaceHistory`` request message. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.dataform_v1beta1.services.dataform.pagers.FetchWorkspaceHistoryAsyncPager: + FetchWorkspaceHistory response message. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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, dataform.FetchWorkspaceHistoryRequest): + request = dataform.FetchWorkspaceHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_workspace_history + ] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchWorkspaceHistoryAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def commit_workspace_changes( self, request: Optional[Union[dataform.CommitWorkspaceChangesRequest, dict]] = None, @@ -6953,6 +7056,147 @@ async def sample_create_compilation_result(): # Done; return the response. return response + async def create_compilation_result_long_running( + self, + request: Optional[Union[dataform.CreateCompilationResultRequest, dict]] = None, + *, + parent: Optional[str] = None, + compilation_result: Optional[dataform.CompilationResult] = 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"""Creates a new CompilationResult in a given project + and location asynchronously. + + .. 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 dataform_v1beta1 + + async def sample_create_compilation_result_long_running(): + # Create a client + client = dataform_v1beta1.DataformAsyncClient() + + # Initialize request argument(s) + compilation_result = dataform_v1beta1.CompilationResult() + compilation_result.git_commitish = "git_commitish_value" + + request = dataform_v1beta1.CreateCompilationResultRequest( + parent="parent_value", + compilation_result=compilation_result, + ) + + # Make the request + operation = await client.create_compilation_result_long_running(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.dataform_v1beta1.types.CreateCompilationResultRequest, dict]]): + The request object. ``CreateCompilationResult`` request message. + parent (:class:`str`): + Required. The repository in which to create the + compilation result. Must be in the format + ``projects/*/locations/*/repositories/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + compilation_result (:class:`google.cloud.dataform_v1beta1.types.CompilationResult`): + Required. The compilation result to + create. + + This corresponds to the ``compilation_result`` 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.dataform_v1beta1.types.CompilationResult` + Represents the result of compiling a Dataform project. + + """ + # 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, compilation_result] + 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, dataform.CreateCompilationResultRequest): + request = dataform.CreateCompilationResultRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if compilation_result is not None: + request.compilation_result = compilation_result + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_compilation_result_long_running + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + dataform.CompilationResult, + metadata_type=dataform.CreateCompilationResultMetadata, + ) + + # Done; return the response. + return response + async def query_compilation_result_actions( self, request: Optional[ diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/client.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/client.py index 1143655c6059..fcc1c9f10a81 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/client.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/client.py @@ -186,6 +186,28 @@ def transport(self) -> DataformTransport: """ return self._transport + @staticmethod + def account_connector_path( + project: str, + location: str, + account_connector: str, + ) -> str: + """Returns a fully-qualified account_connector string.""" + return "projects/{project}/locations/{location}/accountConnectors/{account_connector}".format( + project=project, + location=location, + account_connector=account_connector, + ) + + @staticmethod + def parse_account_connector_path(path: str) -> Dict[str, str]: + """Parses a account_connector path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/accountConnectors/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def compilation_result_path( project: str, @@ -5398,6 +5420,103 @@ def sample_fetch_git_ahead_behind(): # Done; return the response. return response + def fetch_workspace_history( + self, + request: Optional[Union[dataform.FetchWorkspaceHistoryRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.FetchWorkspaceHistoryPager: + r"""Fetches a Workspace's history of commits. + + .. 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 dataform_v1beta1 + + def sample_fetch_workspace_history(): + # Create a client + client = dataform_v1beta1.DataformClient() + + # Initialize request argument(s) + request = dataform_v1beta1.FetchWorkspaceHistoryRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_workspace_history(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryRequest, dict]): + The request object. ``FetchWorkspaceHistory`` request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.dataform_v1beta1.services.dataform.pagers.FetchWorkspaceHistoryPager: + FetchWorkspaceHistory response message. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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, dataform.FetchWorkspaceHistoryRequest): + request = dataform.FetchWorkspaceHistoryRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.fetch_workspace_history] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchWorkspaceHistoryPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def commit_workspace_changes( self, request: Optional[Union[dataform.CommitWorkspaceChangesRequest, dict]] = None, @@ -7384,6 +7503,146 @@ def sample_create_compilation_result(): # Done; return the response. return response + def create_compilation_result_long_running( + self, + request: Optional[Union[dataform.CreateCompilationResultRequest, dict]] = None, + *, + parent: Optional[str] = None, + compilation_result: Optional[dataform.CompilationResult] = 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"""Creates a new CompilationResult in a given project + and location asynchronously. + + .. 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 dataform_v1beta1 + + def sample_create_compilation_result_long_running(): + # Create a client + client = dataform_v1beta1.DataformClient() + + # Initialize request argument(s) + compilation_result = dataform_v1beta1.CompilationResult() + compilation_result.git_commitish = "git_commitish_value" + + request = dataform_v1beta1.CreateCompilationResultRequest( + parent="parent_value", + compilation_result=compilation_result, + ) + + # Make the request + operation = client.create_compilation_result_long_running(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.dataform_v1beta1.types.CreateCompilationResultRequest, dict]): + The request object. ``CreateCompilationResult`` request message. + parent (str): + Required. The repository in which to create the + compilation result. Must be in the format + ``projects/*/locations/*/repositories/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + compilation_result (google.cloud.dataform_v1beta1.types.CompilationResult): + Required. The compilation result to + create. + + This corresponds to the ``compilation_result`` 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.dataform_v1beta1.types.CompilationResult` + Represents the result of compiling a Dataform project. + + """ + # 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, compilation_result] + 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, dataform.CreateCompilationResultRequest): + request = dataform.CreateCompilationResultRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if compilation_result is not None: + request.compilation_result = compilation_result + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_compilation_result_long_running + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + dataform.CompilationResult, + metadata_type=dataform.CreateCompilationResultMetadata, + ) + + # Done; return the response. + return response + def query_compilation_result_actions( self, request: Optional[ diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/pagers.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/pagers.py index 74e9450d03d4..60a102df6285 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/pagers.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/pagers.py @@ -1467,6 +1467,162 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class FetchWorkspaceHistoryPager: + """A pager for iterating through ``fetch_workspace_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryResponse` object, and + provides an ``__iter__`` method to iterate through its + ``commits`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchWorkspaceHistory`` requests and continue to iterate + through the ``commits`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryResponse` + 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[..., dataform.FetchWorkspaceHistoryResponse], + request: dataform.FetchWorkspaceHistoryRequest, + response: dataform.FetchWorkspaceHistoryResponse, + *, + 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.dataform_v1beta1.types.FetchWorkspaceHistoryRequest): + The initial request object. + response (google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryResponse): + 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 = dataform.FetchWorkspaceHistoryRequest(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[dataform.FetchWorkspaceHistoryResponse]: + 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[dataform.CommitLogEntry]: + for page in self.pages: + yield from page.commits + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchWorkspaceHistoryAsyncPager: + """A pager for iterating through ``fetch_workspace_history`` requests. + + This class thinly wraps an initial + :class:`google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``commits`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchWorkspaceHistory`` requests and continue to iterate + through the ``commits`` field on the + corresponding responses. + + All the usual :class:`google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryResponse` + 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[dataform.FetchWorkspaceHistoryResponse]], + request: dataform.FetchWorkspaceHistoryRequest, + response: dataform.FetchWorkspaceHistoryResponse, + *, + 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.dataform_v1beta1.types.FetchWorkspaceHistoryRequest): + The initial request object. + response (google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryResponse): + 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 = dataform.FetchWorkspaceHistoryRequest(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[dataform.FetchWorkspaceHistoryResponse]: + 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[dataform.CommitLogEntry]: + async def async_generator(): + async for page in self.pages: + for response in page.commits: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class QueryDirectoryContentsPager: """A pager for iterating through ``query_directory_contents`` requests. diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/base.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/base.py index 5057a2adca36..9ba3f6f37043 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/base.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/base.py @@ -362,6 +362,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.fetch_workspace_history: gapic_v1.method.wrap_method( + self.fetch_workspace_history, + default_timeout=None, + client_info=client_info, + ), self.commit_workspace_changes: gapic_v1.method.wrap_method( self.commit_workspace_changes, default_timeout=None, @@ -462,6 +467,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_compilation_result_long_running: gapic_v1.method.wrap_method( + self.create_compilation_result_long_running, + default_timeout=None, + client_info=client_info, + ), self.query_compilation_result_actions: gapic_v1.method.wrap_method( self.query_compilation_result_actions, default_timeout=None, @@ -1027,6 +1037,18 @@ def fetch_git_ahead_behind( ]: raise NotImplementedError() + @property + def fetch_workspace_history( + self, + ) -> Callable[ + [dataform.FetchWorkspaceHistoryRequest], + Union[ + dataform.FetchWorkspaceHistoryResponse, + Awaitable[dataform.FetchWorkspaceHistoryResponse], + ], + ]: + raise NotImplementedError() + @property def commit_workspace_changes( self, @@ -1231,6 +1253,15 @@ def create_compilation_result( ]: raise NotImplementedError() + @property + def create_compilation_result_long_running( + self, + ) -> Callable[ + [dataform.CreateCompilationResultRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def query_compilation_result_actions( self, diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/grpc.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/grpc.py index 2b83c70a3720..bab42db6c42c 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/grpc.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/grpc.py @@ -1527,6 +1527,34 @@ def fetch_git_ahead_behind( ) return self._stubs["fetch_git_ahead_behind"] + @property + def fetch_workspace_history( + self, + ) -> Callable[ + [dataform.FetchWorkspaceHistoryRequest], dataform.FetchWorkspaceHistoryResponse + ]: + r"""Return a callable for the fetch workspace history method over gRPC. + + Fetches a Workspace's history of commits. + + Returns: + Callable[[~.FetchWorkspaceHistoryRequest], + ~.FetchWorkspaceHistoryResponse]: + 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 "fetch_workspace_history" not in self._stubs: + self._stubs["fetch_workspace_history"] = self._logged_channel.unary_unary( + "/google.cloud.dataform.v1beta1.Dataform/FetchWorkspaceHistory", + request_serializer=dataform.FetchWorkspaceHistoryRequest.serialize, + response_deserializer=dataform.FetchWorkspaceHistoryResponse.deserialize, + ) + return self._stubs["fetch_workspace_history"] + @property def commit_workspace_changes( self, @@ -2075,6 +2103,36 @@ def create_compilation_result( ) return self._stubs["create_compilation_result"] + @property + def create_compilation_result_long_running( + self, + ) -> Callable[[dataform.CreateCompilationResultRequest], operations_pb2.Operation]: + r"""Return a callable for the create compilation result long + running method over gRPC. + + Creates a new CompilationResult in a given project + and location asynchronously. + + Returns: + Callable[[~.CreateCompilationResultRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_compilation_result_long_running" not in self._stubs: + self._stubs["create_compilation_result_long_running"] = ( + self._logged_channel.unary_unary( + "/google.cloud.dataform.v1beta1.Dataform/CreateCompilationResultLongRunning", + request_serializer=dataform.CreateCompilationResultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_compilation_result_long_running"] + @property def query_compilation_result_actions( self, diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/grpc_asyncio.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/grpc_asyncio.py index 67e5084375b5..ef63e0cb31e3 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/grpc_asyncio.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/grpc_asyncio.py @@ -1563,6 +1563,35 @@ def fetch_git_ahead_behind( ) return self._stubs["fetch_git_ahead_behind"] + @property + def fetch_workspace_history( + self, + ) -> Callable[ + [dataform.FetchWorkspaceHistoryRequest], + Awaitable[dataform.FetchWorkspaceHistoryResponse], + ]: + r"""Return a callable for the fetch workspace history method over gRPC. + + Fetches a Workspace's history of commits. + + Returns: + Callable[[~.FetchWorkspaceHistoryRequest], + Awaitable[~.FetchWorkspaceHistoryResponse]]: + 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 "fetch_workspace_history" not in self._stubs: + self._stubs["fetch_workspace_history"] = self._logged_channel.unary_unary( + "/google.cloud.dataform.v1beta1.Dataform/FetchWorkspaceHistory", + request_serializer=dataform.FetchWorkspaceHistoryRequest.serialize, + response_deserializer=dataform.FetchWorkspaceHistoryResponse.deserialize, + ) + return self._stubs["fetch_workspace_history"] + @property def commit_workspace_changes( self, @@ -2131,6 +2160,38 @@ def create_compilation_result( ) return self._stubs["create_compilation_result"] + @property + def create_compilation_result_long_running( + self, + ) -> Callable[ + [dataform.CreateCompilationResultRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the create compilation result long + running method over gRPC. + + Creates a new CompilationResult in a given project + and location asynchronously. + + Returns: + Callable[[~.CreateCompilationResultRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_compilation_result_long_running" not in self._stubs: + self._stubs["create_compilation_result_long_running"] = ( + self._logged_channel.unary_unary( + "/google.cloud.dataform.v1beta1.Dataform/CreateCompilationResultLongRunning", + request_serializer=dataform.CreateCompilationResultRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + ) + return self._stubs["create_compilation_result_long_running"] + @property def query_compilation_result_actions( self, @@ -2858,6 +2919,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.fetch_workspace_history: self._wrap_method( + self.fetch_workspace_history, + default_timeout=None, + client_info=client_info, + ), self.commit_workspace_changes: self._wrap_method( self.commit_workspace_changes, default_timeout=None, @@ -2958,6 +3024,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.create_compilation_result_long_running: self._wrap_method( + self.create_compilation_result_long_running, + default_timeout=None, + client_info=client_info, + ), self.query_compilation_result_actions: self._wrap_method( self.query_compilation_result_actions, default_timeout=None, diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/rest.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/rest.py index 5350f104d22f..f2413f643b38 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/rest.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/rest.py @@ -125,6 +125,14 @@ def post_create_compilation_result(self, response): logging.log(f"Received response: {response}") return response + def pre_create_compilation_result_long_running(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_compilation_result_long_running(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_folder(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -297,6 +305,14 @@ def post_fetch_workspace_branches(self, response): logging.log(f"Received response: {response}") return response + def pre_fetch_workspace_history(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_workspace_history(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_compilation_result(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -954,6 +970,54 @@ def post_create_compilation_result_with_metadata( """ return response, metadata + def pre_create_compilation_result_long_running( + self, + request: dataform.CreateCompilationResultRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dataform.CreateCompilationResultRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_compilation_result_long_running + + Override in a subclass to manipulate the request or metadata + before they are sent to the Dataform server. + """ + return request, metadata + + def post_create_compilation_result_long_running( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_compilation_result_long_running + + DEPRECATED. Please use the `post_create_compilation_result_long_running_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Dataform server but before + it is returned to user code. This `post_create_compilation_result_long_running` interceptor runs + before the `post_create_compilation_result_long_running_with_metadata` interceptor. + """ + return response + + def post_create_compilation_result_long_running_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_compilation_result_long_running + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Dataform server but before it is returned to user code. + + We recommend only using this `post_create_compilation_result_long_running_with_metadata` + interceptor in new development instead of the `post_create_compilation_result_long_running` interceptor. + When both interceptors are used, this `post_create_compilation_result_long_running_with_metadata` interceptor runs after the + `post_create_compilation_result_long_running` interceptor. The (possibly modified) response returned by + `post_create_compilation_result_long_running` will be passed to + `post_create_compilation_result_long_running_with_metadata`. + """ + return response, metadata + def pre_create_folder( self, request: dataform.CreateFolderRequest, @@ -1921,6 +1985,56 @@ def post_fetch_workspace_branches_with_metadata( """ return response, metadata + def pre_fetch_workspace_history( + self, + request: dataform.FetchWorkspaceHistoryRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dataform.FetchWorkspaceHistoryRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for fetch_workspace_history + + Override in a subclass to manipulate the request or metadata + before they are sent to the Dataform server. + """ + return request, metadata + + def post_fetch_workspace_history( + self, response: dataform.FetchWorkspaceHistoryResponse + ) -> dataform.FetchWorkspaceHistoryResponse: + """Post-rpc interceptor for fetch_workspace_history + + DEPRECATED. Please use the `post_fetch_workspace_history_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Dataform server but before + it is returned to user code. This `post_fetch_workspace_history` interceptor runs + before the `post_fetch_workspace_history_with_metadata` interceptor. + """ + return response + + def post_fetch_workspace_history_with_metadata( + self, + response: dataform.FetchWorkspaceHistoryResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + dataform.FetchWorkspaceHistoryResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for fetch_workspace_history + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Dataform server but before it is returned to user code. + + We recommend only using this `post_fetch_workspace_history_with_metadata` + interceptor in new development instead of the `post_fetch_workspace_history` interceptor. + When both interceptors are used, this `post_fetch_workspace_history_with_metadata` interceptor runs after the + `post_fetch_workspace_history` interceptor. The (possibly modified) response returned by + `post_fetch_workspace_history` will be passed to + `post_fetch_workspace_history_with_metadata`. + """ + return response, metadata + def pre_get_compilation_result( self, request: dataform.GetCompilationResultRequest, @@ -5383,6 +5497,162 @@ def __call__( ) return resp + class _CreateCompilationResultLongRunning( + _BaseDataformRestTransport._BaseCreateCompilationResultLongRunning, + DataformRestStub, + ): + def __hash__(self): + return hash("DataformRestTransport.CreateCompilationResultLongRunning") + + @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: dataform.CreateCompilationResultRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create compilation result + long running method over HTTP. + + Args: + request (~.dataform.CreateCompilationResultRequest): + The request object. ``CreateCompilationResult`` request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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 = _BaseDataformRestTransport._BaseCreateCompilationResultLongRunning._get_http_options() + request, metadata = ( + self._interceptor.pre_create_compilation_result_long_running( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataformRestTransport._BaseCreateCompilationResultLongRunning, + "_BaseCreateCompilationResultLongRunning__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.dataform_v1beta1.DataformClient.CreateCompilationResultLongRunning", + extra={ + "serviceName": "google.cloud.dataform.v1beta1.Dataform", + "rpcName": "CreateCompilationResultLongRunning", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DataformRestTransport._CreateCompilationResultLongRunning._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_compilation_result_long_running(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_create_compilation_result_long_running_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.dataform_v1beta1.DataformClient.create_compilation_result_long_running", + extra={ + "serviceName": "google.cloud.dataform.v1beta1.Dataform", + "rpcName": "CreateCompilationResultLongRunning", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _CreateFolder(_BaseDataformRestTransport._BaseCreateFolder, DataformRestStub): def __hash__(self): return hash("DataformRestTransport.CreateFolder") @@ -8831,6 +9101,153 @@ def __call__( ) return resp + class _FetchWorkspaceHistory( + _BaseDataformRestTransport._BaseFetchWorkspaceHistory, DataformRestStub + ): + def __hash__(self): + return hash("DataformRestTransport.FetchWorkspaceHistory") + + @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: dataform.FetchWorkspaceHistoryRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> dataform.FetchWorkspaceHistoryResponse: + r"""Call the fetch workspace history method over HTTP. + + Args: + request (~.dataform.FetchWorkspaceHistoryRequest): + The request object. ``FetchWorkspaceHistory`` request message. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.dataform.FetchWorkspaceHistoryResponse: + ``FetchWorkspaceHistory`` response message. + """ + + http_options = _BaseDataformRestTransport._BaseFetchWorkspaceHistory._get_http_options() + request, metadata = self._interceptor.pre_fetch_workspace_history( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDataformRestTransport._BaseFetchWorkspaceHistory, + "_BaseFetchWorkspaceHistory__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.dataform_v1beta1.DataformClient.FetchWorkspaceHistory", + extra={ + "serviceName": "google.cloud.dataform.v1beta1.Dataform", + "rpcName": "FetchWorkspaceHistory", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DataformRestTransport._FetchWorkspaceHistory._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 = dataform.FetchWorkspaceHistoryResponse() + pb_resp = dataform.FetchWorkspaceHistoryResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_workspace_history(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_fetch_workspace_history_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = dataform.FetchWorkspaceHistoryResponse.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.dataform_v1beta1.DataformClient.fetch_workspace_history", + extra={ + "serviceName": "google.cloud.dataform.v1beta1.Dataform", + "rpcName": "FetchWorkspaceHistory", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _GetCompilationResult( _BaseDataformRestTransport._BaseGetCompilationResult, DataformRestStub ): @@ -16161,6 +16578,16 @@ def create_compilation_result( self._session, self._host, self._interceptor ) # type: ignore + @property + def create_compilation_result_long_running( + self, + ) -> Callable[[dataform.CreateCompilationResultRequest], 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._CreateCompilationResultLongRunning( + self._session, self._host, self._interceptor + ) # type: ignore + @property def create_folder( self, @@ -16392,6 +16819,16 @@ def fetch_workspace_branches( self._session, self._host, self._interceptor ) # type: ignore + @property + def fetch_workspace_history( + self, + ) -> Callable[ + [dataform.FetchWorkspaceHistoryRequest], dataform.FetchWorkspaceHistoryResponse + ]: + # 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._FetchWorkspaceHistory(self._session, self._host, self._interceptor) # type: ignore + @property def get_compilation_result( self, diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/rest_base.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/rest_base.py index 8d640ae2a497..cd8b1e27709f 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/rest_base.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/services/dataform/transports/rest_base.py @@ -197,6 +197,23 @@ def _get_http_options(): ] return http_options + class _BaseCreateCompilationResultLongRunning: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta1/{parent=projects/*/locations/*/repositories/*}/compilationResults:createLongRunning", + "body": "compilation_result", + }, + ] + return http_options + class _BaseCreateFolder: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -618,6 +635,22 @@ def _get_http_options(): ] return http_options + class _BaseFetchWorkspaceHistory: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta1/{name=projects/*/locations/*/repositories/*/workspaces/*}:fetchHistory", + }, + ] + return http_options + class _BaseGetCompilationResult: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/types/__init__.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/types/__init__.py index 9b4201f848a4..be83eed9c3c6 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/types/__init__.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/types/__init__.py @@ -31,6 +31,7 @@ ComputeRepositoryAccessTokenStatusRequest, ComputeRepositoryAccessTokenStatusResponse, Config, + CreateCompilationResultMetadata, CreateCompilationResultRequest, CreateFolderRequest, CreateReleaseConfigRequest, @@ -72,6 +73,8 @@ FetchRepositoryHistoryResponse, FetchWorkspaceBranchesRequest, FetchWorkspaceBranchesResponse, + FetchWorkspaceHistoryRequest, + FetchWorkspaceHistoryResponse, FileSearchResult, FilesystemEntryMetadata, Folder, @@ -191,6 +194,7 @@ "ComputeRepositoryAccessTokenStatusRequest", "ComputeRepositoryAccessTokenStatusResponse", "Config", + "CreateCompilationResultMetadata", "CreateCompilationResultRequest", "CreateFolderRequest", "CreateReleaseConfigRequest", @@ -231,6 +235,8 @@ "FetchRepositoryHistoryResponse", "FetchWorkspaceBranchesRequest", "FetchWorkspaceBranchesResponse", + "FetchWorkspaceHistoryRequest", + "FetchWorkspaceHistoryResponse", "FileSearchResult", "FilesystemEntryMetadata", "Folder", diff --git a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/types/dataform.py b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/types/dataform.py index c644ae0181a7..1bac2361d4f7 100644 --- a/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/types/dataform.py +++ b/packages/google-cloud-dataform/google/cloud/dataform_v1beta1/types/dataform.py @@ -75,6 +75,8 @@ "FetchFileGitStatusesResponse", "FetchGitAheadBehindRequest", "FetchGitAheadBehindResponse", + "FetchWorkspaceHistoryRequest", + "FetchWorkspaceHistoryResponse", "CommitWorkspaceChangesRequest", "CommitWorkspaceChangesResponse", "ResetWorkspaceChangesRequest", @@ -127,6 +129,7 @@ "ListCompilationResultsResponse", "GetCompilationResultRequest", "CreateCompilationResultRequest", + "CreateCompilationResultMetadata", "Target", "RelationDescriptor", "CompilationResultAction", @@ -330,6 +333,12 @@ class GitRemoteSettings(proto.Message): ssh_authentication_config (google.cloud.dataform_v1beta1.types.Repository.GitRemoteSettings.SshAuthenticationConfig): Optional. Authentication fields for remote uris using SSH protocol. + account_connector (str): + Optional. Resource name for the Account Connector used for + personal authentication. Must be in the format + ``projects/*/locations/*/accountConnectors/*`` + + This field is a member of `oneof`_ ``_account_connector``. git_repository_link (str): Optional. Resource name for the ``GitRepositoryLink`` used for machine credentials. Must be in the format @@ -409,6 +418,11 @@ class SshAuthenticationConfig(proto.Message): number=5, message="Repository.GitRemoteSettings.SshAuthenticationConfig", ) + account_connector: str = proto.Field( + proto.STRING, + number=6, + optional=True, + ) git_repository_link: str = proto.Field( proto.STRING, number=7, @@ -1306,7 +1320,7 @@ class Workspace(proto.Message): Git repository will be created as a shallow clone with the given depth, otherwise a full clone will be performed. This field is available - only for GitHub, Gitlab and 1p repositories with + only for GitHub, GitLab and 1p repositories with enabled branch management. shallow (bool): Output only. If set to true, the workspace @@ -1836,6 +1850,77 @@ class FetchGitAheadBehindResponse(proto.Message): ) +class FetchWorkspaceHistoryRequest(proto.Message): + r"""``FetchWorkspaceHistory`` request message. + + Attributes: + name (str): + Required. The workspace's name. + page_size (int): + Optional. Maximum number of commits to + return. The server may return fewer items than + requested. If unspecified, the server will pick + an appropriate default. + page_token (str): + Optional. Page token received from a previous + ``FetchWorkspaceHistory`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``FetchWorkspaceHistory``, with the exception of + ``page_size``, must match the call that provided the page + token. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=5, + ) + + +class FetchWorkspaceHistoryResponse(proto.Message): + r"""``FetchWorkspaceHistory`` response message. + + Attributes: + commits (MutableSequence[google.cloud.dataform_v1beta1.types.CommitLogEntry]): + A list of commit logs, ordered by 'git log' + default order. + next_page_token (str): + Optional. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + reaches_shallow_boundary (bool): + Whether this response reaches the shallow + boundary of the repository. + """ + + @property + def raw_page(self): + return self + + commits: MutableSequence["CommitLogEntry"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="CommitLogEntry", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + reaches_shallow_boundary: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class CommitWorkspaceChangesRequest(proto.Message): r"""``CommitWorkspaceChanges`` request message. @@ -2204,7 +2289,7 @@ class FileSearchResult(proto.Message): Attributes: path (str): - File system path relative to the workspace + File system path relative to the file tree root. """ @@ -3457,6 +3542,68 @@ class CreateCompilationResultRequest(proto.Message): ) +class CreateCompilationResultMetadata(proto.Message): + r"""Represents the metadata of the + ``CreateCompilationResultLongRunning`` operation. + + Attributes: + id (str): + Output only. The ID of the LRO. + target (str): + Output only. Server-defined resource path for + the target of the operation. + state (google.cloud.dataform_v1beta1.types.CreateCompilationResultMetadata.State): + Output only. The state of the LRO. + create_compilation_result_request (google.cloud.dataform_v1beta1.types.CreateCompilationResultRequest): + Output only. The CreateCompilationResult + requested. + """ + + class State(proto.Enum): + r"""State of the LRO. + + Values: + STATE_UNSPECIFIED (0): + The state is unspecified. + CREATED (1): + The LRO has been created. + RUNNING (2): + The LRO is in progress. + FINISHED (3): + The RPC call has finished. + SUCCEEDED (4): + The LRO has succeeded. + FAILED (5): + The LRO has failed. + """ + + STATE_UNSPECIFIED = 0 + CREATED = 1 + RUNNING = 2 + FINISHED = 3 + SUCCEEDED = 4 + FAILED = 5 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + target: str = proto.Field( + proto.STRING, + number=2, + ) + state: State = proto.Field( + proto.ENUM, + number=3, + enum=State, + ) + create_compilation_result_request: "CreateCompilationResultRequest" = proto.Field( + proto.MESSAGE, + number=4, + message="CreateCompilationResultRequest", + ) + + class Target(proto.Message): r"""Represents an action identifier. If the action writes output, the output will be written to the referenced database object. @@ -3580,6 +3727,10 @@ class CompilationResultAction(proto.Message): data_preparation (google.cloud.dataform_v1beta1.types.CompilationResultAction.DataPreparation): The data preparation executed by this action. + This field is a member of `oneof`_ ``compiled_object``. + bigquery_unit_test (google.cloud.dataform_v1beta1.types.CompilationResultAction.BigQueryUnitTest): + The unit test executed by this action. + This field is a member of `oneof`_ ``compiled_object``. target (google.cloud.dataform_v1beta1.types.Target): This action's identifier. Unique within the @@ -4115,6 +4266,53 @@ class ErrorTable(proto.Message): number=4, ) + class BigQueryUnitTest(proto.Message): + r"""Represents a BigQuery unit test. + + Attributes: + dependency_targets (MutableSequence[google.cloud.dataform_v1beta1.types.Target]): + A list of actions that this action depends + on. + disabled (bool): + Whether this action is disabled (i.e. should + not be run). + tags (MutableSequence[str]): + Arbitrary, user-defined tags on this action. + display_name (str): + The name of the unit test. + test_query (str): + Test query to execute. + expected_output_query (str): + Expected output query to compare against the + test query. + """ + + dependency_targets: MutableSequence["Target"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Target", + ) + disabled: bool = proto.Field( + proto.BOOL, + number=2, + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + display_name: str = proto.Field( + proto.STRING, + number=4, + ) + test_query: str = proto.Field( + proto.STRING, + number=5, + ) + expected_output_query: str = proto.Field( + proto.STRING, + number=6, + ) + class LoadConfig(proto.Message): r"""Simplified load configuration for actions @@ -4224,6 +4422,12 @@ class IncrementalLoadMode(proto.Message): oneof="compiled_object", message=DataPreparation, ) + bigquery_unit_test: BigQueryUnitTest = proto.Field( + proto.MESSAGE, + number=11, + oneof="compiled_object", + message=BigQueryUnitTest, + ) target: "Target" = proto.Field( proto.MESSAGE, number=1, @@ -4497,9 +4701,8 @@ class InvocationConfig(proto.Message): Optional. The service account to run workflow invocations under. end_user_auth_config (google.cloud.dataform_v1beta1.types.InvocationConfig.EndUserAuthenticationConfig): - Optional. Configuration for end user authentication. Note - that this should not be set when ``service_account`` is - used. + Optional. Configuration for end user authentication. Do not + set if ``service_account`` is used. query_priority (google.cloud.dataform_v1beta1.types.InvocationConfig.QueryPriority): Optional. Specifies the priority for query execution in BigQuery. More information can be @@ -4507,6 +4710,14 @@ class InvocationConfig(proto.Message): https://cloud.google.com/bigquery/docs/running-queries#queries. This field is a member of `oneof`_ ``_query_priority``. + concurrent_actions_limit (int): + Optional. Maximum number of actions that can + be executed concurrently. + + This field is a member of `oneof`_ ``_concurrent_actions_limit``. + execution_mode (google.cloud.dataform_v1beta1.types.InvocationConfig.ExecutionMode): + Optional. Specifies the execution mode for + the workflow invocation. """ class QueryPriority(proto.Enum): @@ -4530,6 +4741,27 @@ class QueryPriority(proto.Enum): INTERACTIVE = 1 BATCH = 2 + class ExecutionMode(proto.Enum): + r"""Execution mode for the workflow invocation. + Determines whether to run actions or unit tests. + + Values: + EXECUTION_MODE_UNSPECIFIED (0): + Default value. + DEFAULT (1): + Default execution mode, which runs all actions except unit + tests. Same as ALL_EXCEPT_UNIT_TESTS. + ALL_EXCEPT_UNIT_TESTS (2): + Run all actions except unit tests. + UNIT_TESTS_ONLY (3): + Run unit tests only. + """ + + EXECUTION_MODE_UNSPECIFIED = 0 + DEFAULT = 1 + ALL_EXCEPT_UNIT_TESTS = 2 + UNIT_TESTS_ONLY = 3 + class EndUserAuthenticationConfig(proto.Message): r"""Includes configuration options for end user authentication. @@ -4588,6 +4820,16 @@ class EndUserAuthenticationConfig(proto.Message): optional=True, enum=QueryPriority, ) + concurrent_actions_limit: int = proto.Field( + proto.INT32, + number=10, + optional=True, + ) + execution_mode: ExecutionMode = proto.Field( + proto.ENUM, + number=16, + enum=ExecutionMode, + ) class ListWorkflowConfigsRequest(proto.Message): @@ -5071,6 +5313,11 @@ class WorkflowInvocationAction(proto.Message): Output only. The workflow action's data preparation action details. + This field is a member of `oneof`_ ``action``. + bigquery_unit_test_action (google.cloud.dataform_v1beta1.types.WorkflowInvocationAction.BigQueryUnitTestAction): + Output only. The workflow action's unit test + details. + This field is a member of `oneof`_ ``action``. target (google.cloud.dataform_v1beta1.types.Target): Output only. This action's identifier. Unique @@ -5122,6 +5369,9 @@ class State(proto.Enum): The action was cancelled. A terminal state. FAILED (6): The action failed. A terminal state. + QUEUED (7): + Execution of the action was queued waiting + for an available concurrency slot. """ PENDING = 0 @@ -5131,6 +5381,7 @@ class State(proto.Enum): SUCCEEDED = 4 CANCELLED = 5 FAILED = 6 + QUEUED = 7 class BigQueryAction(proto.Message): r"""Represents a workflow action that will run against BigQuery. @@ -5362,6 +5613,56 @@ class ActionIncrementalLoadMode(proto.Message): number=4, ) + class BigQueryUnitTestAction(proto.Message): + r"""Represents a workflow action that will run a BigQuery unit + test. + + Attributes: + actual_results_job_id (str): + Output only. Job ID for the actual results. + actual_results_sql_script (str): + Output only. SQL script for the actual + results. + expected_results_job_id (str): + Output only. Job ID for the expected results. + expected_results_sql_script (str): + Output only. SQL script for the expected + results. + total_processed_bytes (int): + Output only. Total bytes processed for this + action. Combined total for actual and expected + jobs. + total_billed_bytes (int): + Output only. Total bytes billed for this + action. Combined total for actual and expected + jobs. + """ + + actual_results_job_id: str = proto.Field( + proto.STRING, + number=1, + ) + actual_results_sql_script: str = proto.Field( + proto.STRING, + number=2, + ) + expected_results_job_id: str = proto.Field( + proto.STRING, + number=3, + ) + expected_results_sql_script: str = proto.Field( + proto.STRING, + number=4, + ) + total_processed_bytes: int = proto.Field( + proto.INT64, + number=5, + ) + total_billed_bytes: int = proto.Field( + proto.INT64, + number=6, + ) + bigquery_action: BigQueryAction = proto.Field( proto.MESSAGE, number=6, @@ -5380,6 +5681,12 @@ class ActionIncrementalLoadMode(proto.Message): oneof="action", message=DataPreparationAction, ) + bigquery_unit_test_action: BigQueryUnitTestAction = proto.Field( + proto.MESSAGE, + number=12, + oneof="action", + message=BigQueryUnitTestAction, + ) target: "Target" = proto.Field( proto.MESSAGE, number=1, diff --git a/packages/google-cloud-dataform/samples/generated_samples/dataform_v1_generated_dataform_create_compilation_result_long_running_async.py b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1_generated_dataform_create_compilation_result_long_running_async.py new file mode 100644 index 000000000000..2690b15769c6 --- /dev/null +++ b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1_generated_dataform_create_compilation_result_long_running_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCompilationResultLongRunning +# 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-dataform + + +# [START dataform_v1_generated_Dataform_CreateCompilationResultLongRunning_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 dataform_v1 + + +async def sample_create_compilation_result_long_running(): + # Create a client + client = dataform_v1.DataformAsyncClient() + + # Initialize request argument(s) + compilation_result = dataform_v1.CompilationResult() + compilation_result.git_commitish = "git_commitish_value" + + request = dataform_v1.CreateCompilationResultRequest( + parent="parent_value", + compilation_result=compilation_result, + ) + + # Make the request + operation = await client.create_compilation_result_long_running(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END dataform_v1_generated_Dataform_CreateCompilationResultLongRunning_async] diff --git a/packages/google-cloud-dataform/samples/generated_samples/dataform_v1_generated_dataform_create_compilation_result_long_running_sync.py b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1_generated_dataform_create_compilation_result_long_running_sync.py new file mode 100644 index 000000000000..58b70da7ace5 --- /dev/null +++ b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1_generated_dataform_create_compilation_result_long_running_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCompilationResultLongRunning +# 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-dataform + + +# [START dataform_v1_generated_Dataform_CreateCompilationResultLongRunning_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 dataform_v1 + + +def sample_create_compilation_result_long_running(): + # Create a client + client = dataform_v1.DataformClient() + + # Initialize request argument(s) + compilation_result = dataform_v1.CompilationResult() + compilation_result.git_commitish = "git_commitish_value" + + request = dataform_v1.CreateCompilationResultRequest( + parent="parent_value", + compilation_result=compilation_result, + ) + + # Make the request + operation = client.create_compilation_result_long_running(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END dataform_v1_generated_Dataform_CreateCompilationResultLongRunning_sync] diff --git a/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_create_compilation_result_long_running_async.py b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_create_compilation_result_long_running_async.py new file mode 100644 index 000000000000..8e5a55cb1025 --- /dev/null +++ b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_create_compilation_result_long_running_async.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCompilationResultLongRunning +# 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-dataform + + +# [START dataform_v1beta1_generated_Dataform_CreateCompilationResultLongRunning_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 dataform_v1beta1 + + +async def sample_create_compilation_result_long_running(): + # Create a client + client = dataform_v1beta1.DataformAsyncClient() + + # Initialize request argument(s) + compilation_result = dataform_v1beta1.CompilationResult() + compilation_result.git_commitish = "git_commitish_value" + + request = dataform_v1beta1.CreateCompilationResultRequest( + parent="parent_value", + compilation_result=compilation_result, + ) + + # Make the request + operation = await client.create_compilation_result_long_running(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END dataform_v1beta1_generated_Dataform_CreateCompilationResultLongRunning_async] diff --git a/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_create_compilation_result_long_running_sync.py b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_create_compilation_result_long_running_sync.py new file mode 100644 index 000000000000..528a3984c776 --- /dev/null +++ b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_create_compilation_result_long_running_sync.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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateCompilationResultLongRunning +# 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-dataform + + +# [START dataform_v1beta1_generated_Dataform_CreateCompilationResultLongRunning_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 dataform_v1beta1 + + +def sample_create_compilation_result_long_running(): + # Create a client + client = dataform_v1beta1.DataformClient() + + # Initialize request argument(s) + compilation_result = dataform_v1beta1.CompilationResult() + compilation_result.git_commitish = "git_commitish_value" + + request = dataform_v1beta1.CreateCompilationResultRequest( + parent="parent_value", + compilation_result=compilation_result, + ) + + # Make the request + operation = client.create_compilation_result_long_running(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END dataform_v1beta1_generated_Dataform_CreateCompilationResultLongRunning_sync] diff --git a/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_fetch_workspace_history_async.py b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_fetch_workspace_history_async.py new file mode 100644 index 000000000000..e400d29b38d2 --- /dev/null +++ b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_fetch_workspace_history_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 FetchWorkspaceHistory +# 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-dataform + + +# [START dataform_v1beta1_generated_Dataform_FetchWorkspaceHistory_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 dataform_v1beta1 + + +async def sample_fetch_workspace_history(): + # Create a client + client = dataform_v1beta1.DataformAsyncClient() + + # Initialize request argument(s) + request = dataform_v1beta1.FetchWorkspaceHistoryRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_workspace_history(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END dataform_v1beta1_generated_Dataform_FetchWorkspaceHistory_async] diff --git a/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_fetch_workspace_history_sync.py b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_fetch_workspace_history_sync.py new file mode 100644 index 000000000000..9db2ac2c0a72 --- /dev/null +++ b/packages/google-cloud-dataform/samples/generated_samples/dataform_v1beta1_generated_dataform_fetch_workspace_history_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 FetchWorkspaceHistory +# 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-dataform + + +# [START dataform_v1beta1_generated_Dataform_FetchWorkspaceHistory_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 dataform_v1beta1 + + +def sample_fetch_workspace_history(): + # Create a client + client = dataform_v1beta1.DataformClient() + + # Initialize request argument(s) + request = dataform_v1beta1.FetchWorkspaceHistoryRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_workspace_history(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END dataform_v1beta1_generated_Dataform_FetchWorkspaceHistory_sync] diff --git a/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1.json b/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1.json index 4952c9bddbe9..17db13bc4f85 100644 --- a/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1.json +++ b/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1.json @@ -623,6 +623,175 @@ ], "title": "dataform_v1_generated_dataform_compute_repository_access_token_status_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dataform_v1.DataformAsyncClient", + "shortName": "DataformAsyncClient" + }, + "fullName": "google.cloud.dataform_v1.DataformAsyncClient.create_compilation_result_long_running", + "method": { + "fullName": "google.cloud.dataform.v1.Dataform.CreateCompilationResultLongRunning", + "service": { + "fullName": "google.cloud.dataform.v1.Dataform", + "shortName": "Dataform" + }, + "shortName": "CreateCompilationResultLongRunning" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataform_v1.types.CreateCompilationResultRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "compilation_result", + "type": "google.cloud.dataform_v1.types.CompilationResult" + }, + { + "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_compilation_result_long_running" + }, + "description": "Sample for CreateCompilationResultLongRunning", + "file": "dataform_v1_generated_dataform_create_compilation_result_long_running_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataform_v1_generated_Dataform_CreateCompilationResultLongRunning_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataform_v1_generated_dataform_create_compilation_result_long_running_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataform_v1.DataformClient", + "shortName": "DataformClient" + }, + "fullName": "google.cloud.dataform_v1.DataformClient.create_compilation_result_long_running", + "method": { + "fullName": "google.cloud.dataform.v1.Dataform.CreateCompilationResultLongRunning", + "service": { + "fullName": "google.cloud.dataform.v1.Dataform", + "shortName": "Dataform" + }, + "shortName": "CreateCompilationResultLongRunning" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataform_v1.types.CreateCompilationResultRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "compilation_result", + "type": "google.cloud.dataform_v1.types.CompilationResult" + }, + { + "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_compilation_result_long_running" + }, + "description": "Sample for CreateCompilationResultLongRunning", + "file": "dataform_v1_generated_dataform_create_compilation_result_long_running_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataform_v1_generated_Dataform_CreateCompilationResultLongRunning_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataform_v1_generated_dataform_create_compilation_result_long_running_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1beta1.json b/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1beta1.json index a57a4a5531c6..5302dce953e2 100644 --- a/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1beta1.json +++ b/packages/google-cloud-dataform/samples/generated_samples/snippet_metadata_google.cloud.dataform.v1beta1.json @@ -770,6 +770,175 @@ ], "title": "dataform_v1beta1_generated_dataform_compute_repository_access_token_status_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dataform_v1beta1.DataformAsyncClient", + "shortName": "DataformAsyncClient" + }, + "fullName": "google.cloud.dataform_v1beta1.DataformAsyncClient.create_compilation_result_long_running", + "method": { + "fullName": "google.cloud.dataform.v1beta1.Dataform.CreateCompilationResultLongRunning", + "service": { + "fullName": "google.cloud.dataform.v1beta1.Dataform", + "shortName": "Dataform" + }, + "shortName": "CreateCompilationResultLongRunning" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataform_v1beta1.types.CreateCompilationResultRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "compilation_result", + "type": "google.cloud.dataform_v1beta1.types.CompilationResult" + }, + { + "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_compilation_result_long_running" + }, + "description": "Sample for CreateCompilationResultLongRunning", + "file": "dataform_v1beta1_generated_dataform_create_compilation_result_long_running_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataform_v1beta1_generated_Dataform_CreateCompilationResultLongRunning_async", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataform_v1beta1_generated_dataform_create_compilation_result_long_running_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataform_v1beta1.DataformClient", + "shortName": "DataformClient" + }, + "fullName": "google.cloud.dataform_v1beta1.DataformClient.create_compilation_result_long_running", + "method": { + "fullName": "google.cloud.dataform.v1beta1.Dataform.CreateCompilationResultLongRunning", + "service": { + "fullName": "google.cloud.dataform.v1beta1.Dataform", + "shortName": "Dataform" + }, + "shortName": "CreateCompilationResultLongRunning" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataform_v1beta1.types.CreateCompilationResultRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "compilation_result", + "type": "google.cloud.dataform_v1beta1.types.CompilationResult" + }, + { + "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_compilation_result_long_running" + }, + "description": "Sample for CreateCompilationResultLongRunning", + "file": "dataform_v1beta1_generated_dataform_create_compilation_result_long_running_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataform_v1beta1_generated_Dataform_CreateCompilationResultLongRunning_sync", + "segments": [ + { + "end": 59, + "start": 27, + "type": "FULL" + }, + { + "end": 59, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 56, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 60, + "start": 57, + "type": "RESPONSE_HANDLING" + } + ], + "title": "dataform_v1beta1_generated_dataform_create_compilation_result_long_running_sync.py" + }, { "canonical": true, "clientMethod": { @@ -4970,6 +5139,159 @@ ], "title": "dataform_v1beta1_generated_dataform_fetch_workspace_branches_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.dataform_v1beta1.DataformAsyncClient", + "shortName": "DataformAsyncClient" + }, + "fullName": "google.cloud.dataform_v1beta1.DataformAsyncClient.fetch_workspace_history", + "method": { + "fullName": "google.cloud.dataform.v1beta1.Dataform.FetchWorkspaceHistory", + "service": { + "fullName": "google.cloud.dataform.v1beta1.Dataform", + "shortName": "Dataform" + }, + "shortName": "FetchWorkspaceHistory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dataform_v1beta1.services.dataform.pagers.FetchWorkspaceHistoryAsyncPager", + "shortName": "fetch_workspace_history" + }, + "description": "Sample for FetchWorkspaceHistory", + "file": "dataform_v1beta1_generated_dataform_fetch_workspace_history_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataform_v1beta1_generated_Dataform_FetchWorkspaceHistory_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": "dataform_v1beta1_generated_dataform_fetch_workspace_history_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.dataform_v1beta1.DataformClient", + "shortName": "DataformClient" + }, + "fullName": "google.cloud.dataform_v1beta1.DataformClient.fetch_workspace_history", + "method": { + "fullName": "google.cloud.dataform.v1beta1.Dataform.FetchWorkspaceHistory", + "service": { + "fullName": "google.cloud.dataform.v1beta1.Dataform", + "shortName": "Dataform" + }, + "shortName": "FetchWorkspaceHistory" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.dataform_v1beta1.types.FetchWorkspaceHistoryRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.dataform_v1beta1.services.dataform.pagers.FetchWorkspaceHistoryPager", + "shortName": "fetch_workspace_history" + }, + "description": "Sample for FetchWorkspaceHistory", + "file": "dataform_v1beta1_generated_dataform_fetch_workspace_history_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "dataform_v1beta1_generated_Dataform_FetchWorkspaceHistory_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": "dataform_v1beta1_generated_dataform_fetch_workspace_history_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py index c77d26eecaeb..d5c0ec7aa02e 100644 --- a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py +++ b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1/test_dataform.py @@ -20749,6 +20749,373 @@ async def test_create_compilation_result_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + dataform.CreateCompilationResultRequest(), + {}, + ], +) +def test_create_compilation_result_long_running(request_type, transport: str = "grpc"): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_compilation_result_long_running(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dataform.CreateCompilationResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_compilation_result_long_running_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 = DataformClient( + 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 = dataform.CreateCompilationResultRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_compilation_result_long_running(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.CreateCompilationResultRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_compilation_result_long_running_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 = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_compilation_result_long_running + 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_compilation_result_long_running + ] = mock_rpc + request = {} + client.create_compilation_result_long_running(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.create_compilation_result_long_running(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_compilation_result_long_running_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 = DataformAsyncClient( + 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.create_compilation_result_long_running + 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.create_compilation_result_long_running + ] = mock_rpc + + request = {} + await client.create_compilation_result_long_running(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.create_compilation_result_long_running(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", + [ + dataform.CreateCompilationResultRequest(), + {}, + ], +) +async def test_create_compilation_result_long_running_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataformAsyncClient( + 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.create_compilation_result_long_running), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_compilation_result_long_running(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dataform.CreateCompilationResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_compilation_result_long_running_field_headers(): + client = DataformClient( + 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 = dataform.CreateCompilationResultRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_compilation_result_long_running(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_compilation_result_long_running_field_headers_async(): + client = DataformAsyncClient( + 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 = dataform.CreateCompilationResultRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_compilation_result_long_running(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_compilation_result_long_running_flattened(): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_compilation_result_long_running( + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_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].compilation_result + mock_val = dataform.CompilationResult(git_commitish="git_commitish_value") + assert arg == mock_val + + +def test_create_compilation_result_long_running_flattened_error(): + client = DataformClient( + 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_compilation_result_long_running( + dataform.CreateCompilationResultRequest(), + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_compilation_result_long_running_flattened_async(): + client = DataformAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_compilation_result_long_running( + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_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].compilation_result + mock_val = dataform.CompilationResult(git_commitish="git_commitish_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_compilation_result_long_running_flattened_error_async(): + client = DataformAsyncClient( + 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_compilation_result_long_running( + dataform.CreateCompilationResultRequest(), + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_value" + ), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -36486,6 +36853,190 @@ def test_create_compilation_result_rest_flattened_error(transport: str = "rest") ) +def test_create_compilation_result_long_running_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 = DataformClient( + 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_compilation_result_long_running + 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_compilation_result_long_running + ] = mock_rpc + + request = {} + client.create_compilation_result_long_running(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_compilation_result_long_running(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_compilation_result_long_running_rest_required_fields( + request_type=dataform.CreateCompilationResultRequest, +): + transport_class = transports.DataformRestTransport + + 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 + + default_values = getattr( + transport_class._BaseCreateCompilationResultLongRunning, + "_BaseCreateCompilationResultLongRunning__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DataformClient( + 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_compilation_result_long_running(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_compilation_result_long_running_rest_flattened(): + client = DataformClient( + 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/repositories/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_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_compilation_result_long_running(**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/*/repositories/*}/compilationResults:createLongRunning" + % client.transport._host, + args[1], + ) + + +def test_create_compilation_result_long_running_rest_flattened_error( + transport: str = "rest", +): + client = DataformClient( + 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_compilation_result_long_running( + dataform.CreateCompilationResultRequest(), + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_value" + ), + ) + + def test_query_compilation_result_actions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -40780,6 +41331,28 @@ def test_create_compilation_result_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_create_compilation_result_long_running_empty_call_grpc(): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_compilation_result_long_running(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.CreateCompilationResultRequest() + 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_query_compilation_result_actions_empty_call_grpc(): @@ -42711,6 +43284,32 @@ async def test_create_compilation_result_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_create_compilation_result_long_running_empty_call_grpc_asyncio(): + client = DataformAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__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_compilation_result_long_running(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.CreateCompilationResultRequest() + 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 @@ -51487,6 +52086,250 @@ def test_create_compilation_result_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_create_compilation_result_long_running_rest_bad_request( + request_type=dataform.CreateCompilationResultRequest, +): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/repositories/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.create_compilation_result_long_running(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dataform.CreateCompilationResultRequest, + dict, + ], +) +def test_create_compilation_result_long_running_rest_call_success(request_type): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/repositories/sample3"} + request_init["compilation_result"] = { + "git_commitish": "git_commitish_value", + "workspace": "workspace_value", + "release_config": "release_config_value", + "name": "name_value", + "code_compilation_config": { + "default_database": "default_database_value", + "default_schema": "default_schema_value", + "default_location": "default_location_value", + "assertion_schema": "assertion_schema_value", + "vars": {}, + "database_suffix": "database_suffix_value", + "schema_suffix": "schema_suffix_value", + "table_prefix": "table_prefix_value", + "builtin_assertion_name_prefix": "builtin_assertion_name_prefix_value", + "default_notebook_runtime_options": { + "gcs_output_bucket": "gcs_output_bucket_value", + "gcs_repository_snapshot_destination": { + "repository_snapshot_uri": "repository_snapshot_uri_value" + }, + "ai_platform_notebook_runtime_template": "ai_platform_notebook_runtime_template_value", + }, + "pipeline_config": {"pipeline_type": 1, "path": "path_value"}, + "lineage_enabled": True, + }, + "resolved_git_commit_sha": "resolved_git_commit_sha_value", + "dataform_core_version": "dataform_core_version_value", + "compilation_errors": [ + { + "message": "message_value", + "stack": "stack_value", + "path": "path_value", + "action_target": { + "database": "database_value", + "schema": "schema_value", + "name": "name_value", + }, + } + ], + "data_encryption_state": {"kms_key_version_name": "kms_key_version_name_value"}, + "create_time": {"seconds": 751, "nanos": 543}, + "internal_metadata": "internal_metadata_value", + "private_resource_metadata": {"user_scoped": True}, + "gcs_repository_snapshot_metadata": { + "repository_snapshot_uri": "repository_snapshot_uri_value", + "crc32c_checksum": "crc32c_checksum_value", + "generation": 1068, + }, + } + # 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 = dataform.CreateCompilationResultRequest.meta.fields[ + "compilation_result" + ] + + 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["compilation_result"].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["compilation_result"][field])): + del request_init["compilation_result"][field][i][subfield] + else: + del request_init["compilation_result"][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_compilation_result_long_running(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_compilation_result_long_running_rest_interceptors(null_interceptor): + transport = transports.DataformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataformRestInterceptor(), + ) + client = DataformClient(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.DataformRestInterceptor, + "post_create_compilation_result_long_running", + ) as post, + mock.patch.object( + transports.DataformRestInterceptor, + "post_create_compilation_result_long_running_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataformRestInterceptor, + "pre_create_compilation_result_long_running", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dataform.CreateCompilationResultRequest.pb( + dataform.CreateCompilationResultRequest() + ) + 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 = dataform.CreateCompilationResultRequest() + 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_compilation_result_long_running( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_query_compilation_result_actions_rest_bad_request( request_type=dataform.QueryCompilationResultActionsRequest, ): @@ -51969,6 +52812,8 @@ def test_create_workflow_config_rest_call_success(request_type): }, }, "query_priority": 1, + "concurrent_actions_limit": 2577, + "execution_mode": 1, }, "cron_schedule": "cron_schedule_value", "time_zone": "time_zone_value", @@ -52233,6 +53078,8 @@ def test_update_workflow_config_rest_call_success(request_type): }, }, "query_priority": 1, + "concurrent_actions_limit": 2577, + "execution_mode": 1, }, "cron_schedule": "cron_schedule_value", "time_zone": "time_zone_value", @@ -52880,6 +53727,8 @@ def test_create_workflow_invocation_rest_call_success(request_type): }, }, "query_priority": 1, + "concurrent_actions_limit": 2577, + "execution_mode": 1, }, "state": 1, "invocation_timing": { @@ -55672,6 +56521,27 @@ def test_create_compilation_result_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_create_compilation_result_long_running_empty_call_rest(): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + client.create_compilation_result_long_running(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.CreateCompilationResultRequest() + 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_query_compilation_result_actions_empty_call_rest(): @@ -56127,6 +56997,7 @@ def test_dataform_base_transport(): "list_compilation_results", "get_compilation_result", "create_compilation_result", + "create_compilation_result_long_running", "query_compilation_result_actions", "list_workflow_configs", "get_workflow_config", @@ -56597,6 +57468,9 @@ def test_dataform_client_transport_session_collision(transport_name): session1 = client1.transport.create_compilation_result._session session2 = client2.transport.create_compilation_result._session assert session1 != session2 + session1 = client1.transport.create_compilation_result_long_running._session + session2 = client2.transport.create_compilation_result_long_running._session + assert session1 != session2 session1 = client1.transport.query_compilation_result_actions._session session2 = client2.transport.query_compilation_result_actions._session assert session1 != session2 diff --git a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1beta1/test_dataform.py b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1beta1/test_dataform.py index ec2b7210f635..396a150b5b5c 100644 --- a/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1beta1/test_dataform.py +++ b/packages/google-cloud-dataform/tests/unit/gapic/dataform_v1beta1/test_dataform.py @@ -15966,6 +15966,474 @@ async def test_fetch_git_ahead_behind_field_headers_async(): ) in kw["metadata"] +@pytest.mark.parametrize( + "request_type", + [ + dataform.FetchWorkspaceHistoryRequest(), + {}, + ], +) +def test_fetch_workspace_history(request_type, transport: str = "grpc"): + client = DataformClient( + 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.fetch_workspace_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = dataform.FetchWorkspaceHistoryResponse( + next_page_token="next_page_token_value", + reaches_shallow_boundary=True, + ) + response = client.fetch_workspace_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dataform.FetchWorkspaceHistoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchWorkspaceHistoryPager) + assert response.next_page_token == "next_page_token_value" + assert response.reaches_shallow_boundary is True + + +def test_fetch_workspace_history_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 = DataformClient( + 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 = dataform.FetchWorkspaceHistoryRequest( + name="name_value", + page_token="page_token_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_workspace_history), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_workspace_history(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.FetchWorkspaceHistoryRequest( + name="name_value", + page_token="page_token_value", + ) + assert args[0] == request_msg + + +def test_fetch_workspace_history_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 = DataformClient( + 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.fetch_workspace_history + 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.fetch_workspace_history + ] = mock_rpc + request = {} + client.fetch_workspace_history(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_workspace_history(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_fetch_workspace_history_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 = DataformAsyncClient( + 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.fetch_workspace_history + 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.fetch_workspace_history + ] = mock_rpc + + request = {} + await client.fetch_workspace_history(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_workspace_history(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", + [ + dataform.FetchWorkspaceHistoryRequest(), + {}, + ], +) +async def test_fetch_workspace_history_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataformAsyncClient( + 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.fetch_workspace_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dataform.FetchWorkspaceHistoryResponse( + next_page_token="next_page_token_value", + reaches_shallow_boundary=True, + ) + ) + response = await client.fetch_workspace_history(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dataform.FetchWorkspaceHistoryRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchWorkspaceHistoryAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.reaches_shallow_boundary is True + + +def test_fetch_workspace_history_field_headers(): + client = DataformClient( + 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 = dataform.FetchWorkspaceHistoryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_workspace_history), "__call__" + ) as call: + call.return_value = dataform.FetchWorkspaceHistoryResponse() + client.fetch_workspace_history(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_fetch_workspace_history_field_headers_async(): + client = DataformAsyncClient( + 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 = dataform.FetchWorkspaceHistoryRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_workspace_history), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dataform.FetchWorkspaceHistoryResponse() + ) + await client.fetch_workspace_history(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_fetch_workspace_history_pager(transport_name: str = "grpc"): + client = DataformClient( + 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.fetch_workspace_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + next_page_token="abc", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[], + next_page_token="def", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + ], + next_page_token="ghi", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.fetch_workspace_history(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, dataform.CommitLogEntry) for i in results) + + +def test_fetch_workspace_history_pages(transport_name: str = "grpc"): + client = DataformClient( + 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.fetch_workspace_history), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + next_page_token="abc", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[], + next_page_token="def", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + ], + next_page_token="ghi", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + ), + RuntimeError, + ) + pages = list(client.fetch_workspace_history(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_fetch_workspace_history_async_pager(): + client = DataformAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_workspace_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + next_page_token="abc", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[], + next_page_token="def", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + ], + next_page_token="ghi", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_workspace_history( + 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, dataform.CommitLogEntry) for i in responses) + + +@pytest.mark.asyncio +async def test_fetch_workspace_history_async_pages(): + client = DataformAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_workspace_history), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + next_page_token="abc", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[], + next_page_token="def", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + ], + next_page_token="ghi", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.fetch_workspace_history(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", [ @@ -22613,6 +23081,373 @@ async def test_create_compilation_result_flattened_error_async(): ) +@pytest.mark.parametrize( + "request_type", + [ + dataform.CreateCompilationResultRequest(), + {}, + ], +) +def test_create_compilation_result_long_running(request_type, transport: str = "grpc"): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_compilation_result_long_running(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = dataform.CreateCompilationResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_compilation_result_long_running_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 = DataformClient( + 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 = dataform.CreateCompilationResultRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_compilation_result_long_running(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.CreateCompilationResultRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_create_compilation_result_long_running_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 = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_compilation_result_long_running + 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_compilation_result_long_running + ] = mock_rpc + request = {} + client.create_compilation_result_long_running(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.create_compilation_result_long_running(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_compilation_result_long_running_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 = DataformAsyncClient( + 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.create_compilation_result_long_running + 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.create_compilation_result_long_running + ] = mock_rpc + + request = {} + await client.create_compilation_result_long_running(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.create_compilation_result_long_running(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", + [ + dataform.CreateCompilationResultRequest(), + {}, + ], +) +async def test_create_compilation_result_long_running_async( + request_type, transport: str = "grpc_asyncio" +): + client = DataformAsyncClient( + 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.create_compilation_result_long_running), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_compilation_result_long_running(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = dataform.CreateCompilationResultRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_compilation_result_long_running_field_headers(): + client = DataformClient( + 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 = dataform.CreateCompilationResultRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_compilation_result_long_running(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_compilation_result_long_running_field_headers_async(): + client = DataformAsyncClient( + 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 = dataform.CreateCompilationResultRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_compilation_result_long_running(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_compilation_result_long_running_flattened(): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_compilation_result_long_running( + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_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].compilation_result + mock_val = dataform.CompilationResult(git_commitish="git_commitish_value") + assert arg == mock_val + + +def test_create_compilation_result_long_running_flattened_error(): + client = DataformClient( + 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_compilation_result_long_running( + dataform.CreateCompilationResultRequest(), + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_value" + ), + ) + + +@pytest.mark.asyncio +async def test_create_compilation_result_long_running_flattened_async(): + client = DataformAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_compilation_result_long_running( + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_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].compilation_result + mock_val = dataform.CompilationResult(git_commitish="git_commitish_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_compilation_result_long_running_flattened_error_async(): + client = DataformAsyncClient( + 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_compilation_result_long_running( + dataform.CreateCompilationResultRequest(), + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_value" + ), + ) + + @pytest.mark.parametrize( "request_type", [ @@ -36035,6 +36870,198 @@ def test_fetch_git_ahead_behind_rest_required_fields( assert sorted(expected_params) == sorted(actual_params) +def test_fetch_workspace_history_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 = DataformClient( + 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.fetch_workspace_history + 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.fetch_workspace_history + ] = mock_rpc + + request = {} + client.fetch_workspace_history(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_workspace_history(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_fetch_workspace_history_rest_required_fields( + request_type=dataform.FetchWorkspaceHistoryRequest, +): + transport_class = transports.DataformRestTransport + + 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 + + default_values = getattr( + transport_class._BaseFetchWorkspaceHistory, + "_BaseFetchWorkspaceHistory__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dataform.FetchWorkspaceHistoryResponse() + # 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 = dataform.FetchWorkspaceHistoryResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_workspace_history(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_workspace_history_rest_pager(transport: str = "rest"): + client = DataformClient( + 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 = ( + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + next_page_token="abc", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[], + next_page_token="def", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + ], + next_page_token="ghi", + ), + dataform.FetchWorkspaceHistoryResponse( + commits=[ + dataform.CommitLogEntry(), + dataform.CommitLogEntry(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + dataform.FetchWorkspaceHistoryResponse.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 = { + "name": "projects/sample1/locations/sample2/repositories/sample3/workspaces/sample4" + } + + pager = client.fetch_workspace_history(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, dataform.CommitLogEntry) for i in results) + + pages = list(client.fetch_workspace_history(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + def test_commit_workspace_changes_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -39194,6 +40221,190 @@ def test_create_compilation_result_rest_flattened_error(transport: str = "rest") ) +def test_create_compilation_result_long_running_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 = DataformClient( + 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_compilation_result_long_running + 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_compilation_result_long_running + ] = mock_rpc + + request = {} + client.create_compilation_result_long_running(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_compilation_result_long_running(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_compilation_result_long_running_rest_required_fields( + request_type=dataform.CreateCompilationResultRequest, +): + transport_class = transports.DataformRestTransport + + 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 + + default_values = getattr( + transport_class._BaseCreateCompilationResultLongRunning, + "_BaseCreateCompilationResultLongRunning__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DataformClient( + 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_compilation_result_long_running(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_compilation_result_long_running_rest_flattened(): + client = DataformClient( + 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/repositories/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_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_compilation_result_long_running(**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/v1beta1/{parent=projects/*/locations/*/repositories/*}/compilationResults:createLongRunning" + % client.transport._host, + args[1], + ) + + +def test_create_compilation_result_long_running_rest_flattened_error( + transport: str = "rest", +): + client = DataformClient( + 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_compilation_result_long_running( + dataform.CreateCompilationResultRequest(), + parent="parent_value", + compilation_result=dataform.CompilationResult( + git_commitish="git_commitish_value" + ), + ) + + def test_query_compilation_result_actions_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -43196,6 +44407,28 @@ def test_fetch_git_ahead_behind_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_fetch_workspace_history_empty_call_grpc(): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_workspace_history), "__call__" + ) as call: + call.return_value = dataform.FetchWorkspaceHistoryResponse() + client.fetch_workspace_history(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.FetchWorkspaceHistoryRequest() + 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_commit_workspace_changes_empty_call_grpc(): @@ -43618,6 +44851,28 @@ def test_create_compilation_result_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_create_compilation_result_long_running_empty_call_grpc(): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_compilation_result_long_running(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.CreateCompilationResultRequest() + 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_query_compilation_result_actions_empty_call_grpc(): @@ -45165,6 +46420,35 @@ async def test_fetch_git_ahead_behind_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_fetch_workspace_history_empty_call_grpc_asyncio(): + client = DataformAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_workspace_history), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + dataform.FetchWorkspaceHistoryResponse( + next_page_token="next_page_token_value", + reaches_shallow_boundary=True, + ) + ) + await client.fetch_workspace_history(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.FetchWorkspaceHistoryRequest() + 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 @@ -45713,6 +46997,32 @@ async def test_create_compilation_result_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_create_compilation_result_long_running_empty_call_grpc_asyncio(): + client = DataformAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__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_compilation_result_long_running(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.CreateCompilationResultRequest() + 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 @@ -48763,6 +50073,7 @@ def test_create_repository_rest_call_success(request_type): "user_private_key_secret_version": "user_private_key_secret_version_value", "host_public_key": "host_public_key_value", }, + "account_connector": "account_connector_value", "git_repository_link": "git_repository_link_value", "token_status": 1, }, @@ -49024,6 +50335,7 @@ def test_update_repository_rest_call_success(request_type): "user_private_key_secret_version": "user_private_key_secret_version_value", "host_public_key": "host_public_key_value", }, + "account_connector": "account_connector_value", "git_repository_link": "git_repository_link_value", "token_status": 1, }, @@ -52297,8 +53609,8 @@ def test_fetch_git_ahead_behind_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_commit_workspace_changes_rest_bad_request( - request_type=dataform.CommitWorkspaceChangesRequest, +def test_fetch_workspace_history_rest_bad_request( + request_type=dataform.FetchWorkspaceHistoryRequest, ): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -52322,17 +53634,17 @@ def test_commit_workspace_changes_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.commit_workspace_changes(request) + client.fetch_workspace_history(request) @pytest.mark.parametrize( "request_type", [ - dataform.CommitWorkspaceChangesRequest, + dataform.FetchWorkspaceHistoryRequest, dict, ], ) -def test_commit_workspace_changes_rest_call_success(request_type): +def test_fetch_workspace_history_rest_call_success(request_type): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -52346,26 +53658,31 @@ def test_commit_workspace_changes_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 = dataform.CommitWorkspaceChangesResponse() + return_value = dataform.FetchWorkspaceHistoryResponse( + next_page_token="next_page_token_value", + reaches_shallow_boundary=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 = dataform.CommitWorkspaceChangesResponse.pb(return_value) + return_value = dataform.FetchWorkspaceHistoryResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.commit_workspace_changes(request) + response = client.fetch_workspace_history(request) # Establish that the response is the type that we expect. - assert isinstance(response, dataform.CommitWorkspaceChangesResponse) + assert isinstance(response, pagers.FetchWorkspaceHistoryPager) + assert response.next_page_token == "next_page_token_value" + assert response.reaches_shallow_boundary is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_commit_workspace_changes_rest_interceptors(null_interceptor): +def test_fetch_workspace_history_rest_interceptors(null_interceptor): transport = transports.DataformRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.DataformRestInterceptor(), @@ -52376,21 +53693,21 @@ def test_commit_workspace_changes_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.DataformRestInterceptor, "post_commit_workspace_changes" + transports.DataformRestInterceptor, "post_fetch_workspace_history" ) as post, mock.patch.object( transports.DataformRestInterceptor, - "post_commit_workspace_changes_with_metadata", + "post_fetch_workspace_history_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataformRestInterceptor, "pre_commit_workspace_changes" + transports.DataformRestInterceptor, "pre_fetch_workspace_history" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = dataform.CommitWorkspaceChangesRequest.pb( - dataform.CommitWorkspaceChangesRequest() + pb_message = dataform.FetchWorkspaceHistoryRequest.pb( + dataform.FetchWorkspaceHistoryRequest() ) transcode.return_value = { "method": "post", @@ -52402,24 +53719,24 @@ def test_commit_workspace_changes_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 = dataform.CommitWorkspaceChangesResponse.to_json( - dataform.CommitWorkspaceChangesResponse() + return_value = dataform.FetchWorkspaceHistoryResponse.to_json( + dataform.FetchWorkspaceHistoryResponse() ) req.return_value.content = return_value - request = dataform.CommitWorkspaceChangesRequest() + request = dataform.FetchWorkspaceHistoryRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = dataform.CommitWorkspaceChangesResponse() + post.return_value = dataform.FetchWorkspaceHistoryResponse() post_with_metadata.return_value = ( - dataform.CommitWorkspaceChangesResponse(), + dataform.FetchWorkspaceHistoryResponse(), metadata, ) - client.commit_workspace_changes( + client.fetch_workspace_history( request, metadata=[ ("key", "val"), @@ -52432,8 +53749,8 @@ def test_commit_workspace_changes_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_reset_workspace_changes_rest_bad_request( - request_type=dataform.ResetWorkspaceChangesRequest, +def test_commit_workspace_changes_rest_bad_request( + request_type=dataform.CommitWorkspaceChangesRequest, ): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -52457,17 +53774,17 @@ def test_reset_workspace_changes_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.reset_workspace_changes(request) + client.commit_workspace_changes(request) @pytest.mark.parametrize( "request_type", [ - dataform.ResetWorkspaceChangesRequest, + dataform.CommitWorkspaceChangesRequest, dict, ], ) -def test_reset_workspace_changes_rest_call_success(request_type): +def test_commit_workspace_changes_rest_call_success(request_type): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -52481,26 +53798,26 @@ def test_reset_workspace_changes_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 = dataform.ResetWorkspaceChangesResponse() + return_value = dataform.CommitWorkspaceChangesResponse() # 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 = dataform.ResetWorkspaceChangesResponse.pb(return_value) + return_value = dataform.CommitWorkspaceChangesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.reset_workspace_changes(request) + response = client.commit_workspace_changes(request) # Establish that the response is the type that we expect. - assert isinstance(response, dataform.ResetWorkspaceChangesResponse) + assert isinstance(response, dataform.CommitWorkspaceChangesResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_reset_workspace_changes_rest_interceptors(null_interceptor): +def test_commit_workspace_changes_rest_interceptors(null_interceptor): transport = transports.DataformRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.DataformRestInterceptor(), @@ -52511,21 +53828,21 @@ def test_reset_workspace_changes_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.DataformRestInterceptor, "post_reset_workspace_changes" + transports.DataformRestInterceptor, "post_commit_workspace_changes" ) as post, mock.patch.object( transports.DataformRestInterceptor, - "post_reset_workspace_changes_with_metadata", + "post_commit_workspace_changes_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataformRestInterceptor, "pre_reset_workspace_changes" + transports.DataformRestInterceptor, "pre_commit_workspace_changes" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = dataform.ResetWorkspaceChangesRequest.pb( - dataform.ResetWorkspaceChangesRequest() + pb_message = dataform.CommitWorkspaceChangesRequest.pb( + dataform.CommitWorkspaceChangesRequest() ) transcode.return_value = { "method": "post", @@ -52537,24 +53854,24 @@ def test_reset_workspace_changes_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 = dataform.ResetWorkspaceChangesResponse.to_json( - dataform.ResetWorkspaceChangesResponse() + return_value = dataform.CommitWorkspaceChangesResponse.to_json( + dataform.CommitWorkspaceChangesResponse() ) req.return_value.content = return_value - request = dataform.ResetWorkspaceChangesRequest() + request = dataform.CommitWorkspaceChangesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = dataform.ResetWorkspaceChangesResponse() + post.return_value = dataform.CommitWorkspaceChangesResponse() post_with_metadata.return_value = ( - dataform.ResetWorkspaceChangesResponse(), + dataform.CommitWorkspaceChangesResponse(), metadata, ) - client.reset_workspace_changes( + client.commit_workspace_changes( request, metadata=[ ("key", "val"), @@ -52567,13 +53884,15 @@ def test_reset_workspace_changes_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_file_diff_rest_bad_request(request_type=dataform.FetchFileDiffRequest): +def test_reset_workspace_changes_rest_bad_request( + request_type=dataform.ResetWorkspaceChangesRequest, +): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "workspace": "projects/sample1/locations/sample2/repositories/sample3/workspaces/sample4" + "name": "projects/sample1/locations/sample2/repositories/sample3/workspaces/sample4" } request = request_type(**request_init) @@ -52590,53 +53909,50 @@ def test_fetch_file_diff_rest_bad_request(request_type=dataform.FetchFileDiffReq response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.fetch_file_diff(request) + client.reset_workspace_changes(request) @pytest.mark.parametrize( "request_type", [ - dataform.FetchFileDiffRequest, + dataform.ResetWorkspaceChangesRequest, dict, ], ) -def test_fetch_file_diff_rest_call_success(request_type): +def test_reset_workspace_changes_rest_call_success(request_type): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "workspace": "projects/sample1/locations/sample2/repositories/sample3/workspaces/sample4" + "name": "projects/sample1/locations/sample2/repositories/sample3/workspaces/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 = dataform.FetchFileDiffResponse( - formatted_diff="formatted_diff_value", - ) + return_value = dataform.ResetWorkspaceChangesResponse() # 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 = dataform.FetchFileDiffResponse.pb(return_value) + return_value = dataform.ResetWorkspaceChangesResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.fetch_file_diff(request) + response = client.reset_workspace_changes(request) # Establish that the response is the type that we expect. - assert isinstance(response, dataform.FetchFileDiffResponse) - assert response.formatted_diff == "formatted_diff_value" + assert isinstance(response, dataform.ResetWorkspaceChangesResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_file_diff_rest_interceptors(null_interceptor): +def test_reset_workspace_changes_rest_interceptors(null_interceptor): transport = transports.DataformRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.DataformRestInterceptor(), @@ -52647,19 +53963,22 @@ def test_fetch_file_diff_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.DataformRestInterceptor, "post_fetch_file_diff" + transports.DataformRestInterceptor, "post_reset_workspace_changes" ) as post, mock.patch.object( - transports.DataformRestInterceptor, "post_fetch_file_diff_with_metadata" + transports.DataformRestInterceptor, + "post_reset_workspace_changes_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataformRestInterceptor, "pre_fetch_file_diff" + transports.DataformRestInterceptor, "pre_reset_workspace_changes" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = dataform.FetchFileDiffRequest.pb(dataform.FetchFileDiffRequest()) + pb_message = dataform.ResetWorkspaceChangesRequest.pb( + dataform.ResetWorkspaceChangesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -52670,21 +53989,24 @@ def test_fetch_file_diff_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 = dataform.FetchFileDiffResponse.to_json( - dataform.FetchFileDiffResponse() + return_value = dataform.ResetWorkspaceChangesResponse.to_json( + dataform.ResetWorkspaceChangesResponse() ) req.return_value.content = return_value - request = dataform.FetchFileDiffRequest() + request = dataform.ResetWorkspaceChangesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = dataform.FetchFileDiffResponse() - post_with_metadata.return_value = dataform.FetchFileDiffResponse(), metadata + post.return_value = dataform.ResetWorkspaceChangesResponse() + post_with_metadata.return_value = ( + dataform.ResetWorkspaceChangesResponse(), + metadata, + ) - client.fetch_file_diff( + client.reset_workspace_changes( request, metadata=[ ("key", "val"), @@ -52697,9 +54019,7 @@ def test_fetch_file_diff_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_query_directory_contents_rest_bad_request( - request_type=dataform.QueryDirectoryContentsRequest, -): +def test_fetch_file_diff_rest_bad_request(request_type=dataform.FetchFileDiffRequest): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -52722,17 +54042,17 @@ def test_query_directory_contents_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.query_directory_contents(request) + client.fetch_file_diff(request) @pytest.mark.parametrize( "request_type", [ - dataform.QueryDirectoryContentsRequest, + dataform.FetchFileDiffRequest, dict, ], ) -def test_query_directory_contents_rest_call_success(request_type): +def test_fetch_file_diff_rest_call_success(request_type): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -52746,8 +54066,8 @@ def test_query_directory_contents_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 = dataform.QueryDirectoryContentsResponse( - next_page_token="next_page_token_value", + return_value = dataform.FetchFileDiffResponse( + formatted_diff="formatted_diff_value", ) # Wrap the value into a proper Response obj @@ -52755,20 +54075,20 @@ def test_query_directory_contents_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = dataform.QueryDirectoryContentsResponse.pb(return_value) + return_value = dataform.FetchFileDiffResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.query_directory_contents(request) + response = client.fetch_file_diff(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.QueryDirectoryContentsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, dataform.FetchFileDiffResponse) + assert response.formatted_diff == "formatted_diff_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_query_directory_contents_rest_interceptors(null_interceptor): +def test_fetch_file_diff_rest_interceptors(null_interceptor): transport = transports.DataformRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.DataformRestInterceptor(), @@ -52779,22 +54099,19 @@ def test_query_directory_contents_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.DataformRestInterceptor, "post_query_directory_contents" + transports.DataformRestInterceptor, "post_fetch_file_diff" ) as post, mock.patch.object( - transports.DataformRestInterceptor, - "post_query_directory_contents_with_metadata", + transports.DataformRestInterceptor, "post_fetch_file_diff_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.DataformRestInterceptor, "pre_query_directory_contents" + transports.DataformRestInterceptor, "pre_fetch_file_diff" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = dataform.QueryDirectoryContentsRequest.pb( - dataform.QueryDirectoryContentsRequest() - ) + pb_message = dataform.FetchFileDiffRequest.pb(dataform.FetchFileDiffRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -52805,24 +54122,21 @@ def test_query_directory_contents_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 = dataform.QueryDirectoryContentsResponse.to_json( - dataform.QueryDirectoryContentsResponse() + return_value = dataform.FetchFileDiffResponse.to_json( + dataform.FetchFileDiffResponse() ) req.return_value.content = return_value - request = dataform.QueryDirectoryContentsRequest() + request = dataform.FetchFileDiffRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = dataform.QueryDirectoryContentsResponse() - post_with_metadata.return_value = ( - dataform.QueryDirectoryContentsResponse(), - metadata, - ) + post.return_value = dataform.FetchFileDiffResponse() + post_with_metadata.return_value = dataform.FetchFileDiffResponse(), metadata - client.query_directory_contents( + client.fetch_file_diff( request, metadata=[ ("key", "val"), @@ -52835,7 +54149,9 @@ def test_query_directory_contents_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_search_files_rest_bad_request(request_type=dataform.SearchFilesRequest): +def test_query_directory_contents_rest_bad_request( + request_type=dataform.QueryDirectoryContentsRequest, +): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -52858,17 +54174,17 @@ def test_search_files_rest_bad_request(request_type=dataform.SearchFilesRequest) response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.search_files(request) + client.query_directory_contents(request) @pytest.mark.parametrize( "request_type", [ - dataform.SearchFilesRequest, + dataform.QueryDirectoryContentsRequest, dict, ], ) -def test_search_files_rest_call_success(request_type): +def test_query_directory_contents_rest_call_success(request_type): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -52882,7 +54198,7 @@ def test_search_files_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 = dataform.SearchFilesResponse( + return_value = dataform.QueryDirectoryContentsResponse( next_page_token="next_page_token_value", ) @@ -52891,20 +54207,20 @@ def test_search_files_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = dataform.SearchFilesResponse.pb(return_value) + return_value = dataform.QueryDirectoryContentsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.search_files(request) + response = client.query_directory_contents(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchFilesPager) + assert isinstance(response, pagers.QueryDirectoryContentsPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_files_rest_interceptors(null_interceptor): +def test_query_directory_contents_rest_interceptors(null_interceptor): transport = transports.DataformRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.DataformRestInterceptor(), @@ -52915,19 +54231,22 @@ def test_search_files_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.DataformRestInterceptor, "post_search_files" + transports.DataformRestInterceptor, "post_query_directory_contents" ) as post, mock.patch.object( - transports.DataformRestInterceptor, "post_search_files_with_metadata" + transports.DataformRestInterceptor, + "post_query_directory_contents_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DataformRestInterceptor, "pre_search_files" + transports.DataformRestInterceptor, "pre_query_directory_contents" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = dataform.SearchFilesRequest.pb(dataform.SearchFilesRequest()) + pb_message = dataform.QueryDirectoryContentsRequest.pb( + dataform.QueryDirectoryContentsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -52938,21 +54257,24 @@ def test_search_files_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 = dataform.SearchFilesResponse.to_json( - dataform.SearchFilesResponse() + return_value = dataform.QueryDirectoryContentsResponse.to_json( + dataform.QueryDirectoryContentsResponse() ) req.return_value.content = return_value - request = dataform.SearchFilesRequest() + request = dataform.QueryDirectoryContentsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = dataform.SearchFilesResponse() - post_with_metadata.return_value = dataform.SearchFilesResponse(), metadata + post.return_value = dataform.QueryDirectoryContentsResponse() + post_with_metadata.return_value = ( + dataform.QueryDirectoryContentsResponse(), + metadata, + ) - client.search_files( + client.query_directory_contents( request, metadata=[ ("key", "val"), @@ -52965,7 +54287,137 @@ def test_search_files_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_make_directory_rest_bad_request(request_type=dataform.MakeDirectoryRequest): +def test_search_files_rest_bad_request(request_type=dataform.SearchFilesRequest): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "workspace": "projects/sample1/locations/sample2/repositories/sample3/workspaces/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.search_files(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dataform.SearchFilesRequest, + dict, + ], +) +def test_search_files_rest_call_success(request_type): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "workspace": "projects/sample1/locations/sample2/repositories/sample3/workspaces/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 = dataform.SearchFilesResponse( + next_page_token="next_page_token_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 = dataform.SearchFilesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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.search_files(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchFilesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_files_rest_interceptors(null_interceptor): + transport = transports.DataformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataformRestInterceptor(), + ) + client = DataformClient(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.DataformRestInterceptor, "post_search_files" + ) as post, + mock.patch.object( + transports.DataformRestInterceptor, "post_search_files_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.DataformRestInterceptor, "pre_search_files" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dataform.SearchFilesRequest.pb(dataform.SearchFilesRequest()) + 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 = dataform.SearchFilesResponse.to_json( + dataform.SearchFilesResponse() + ) + req.return_value.content = return_value + + request = dataform.SearchFilesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dataform.SearchFilesResponse() + post_with_metadata.return_value = dataform.SearchFilesResponse(), metadata + + client.search_files( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_make_directory_rest_bad_request(request_type=dataform.MakeDirectoryRequest): client = DataformClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -55279,6 +56731,250 @@ def test_create_compilation_result_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() +def test_create_compilation_result_long_running_rest_bad_request( + request_type=dataform.CreateCompilationResultRequest, +): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/repositories/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.create_compilation_result_long_running(request) + + +@pytest.mark.parametrize( + "request_type", + [ + dataform.CreateCompilationResultRequest, + dict, + ], +) +def test_create_compilation_result_long_running_rest_call_success(request_type): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/repositories/sample3"} + request_init["compilation_result"] = { + "git_commitish": "git_commitish_value", + "workspace": "workspace_value", + "release_config": "release_config_value", + "name": "name_value", + "code_compilation_config": { + "default_database": "default_database_value", + "default_schema": "default_schema_value", + "default_location": "default_location_value", + "assertion_schema": "assertion_schema_value", + "vars": {}, + "database_suffix": "database_suffix_value", + "schema_suffix": "schema_suffix_value", + "table_prefix": "table_prefix_value", + "builtin_assertion_name_prefix": "builtin_assertion_name_prefix_value", + "default_notebook_runtime_options": { + "gcs_output_bucket": "gcs_output_bucket_value", + "gcs_repository_snapshot_destination": { + "repository_snapshot_uri": "repository_snapshot_uri_value" + }, + "ai_platform_notebook_runtime_template": "ai_platform_notebook_runtime_template_value", + }, + "pipeline_config": {"pipeline_type": 1, "path": "path_value"}, + "lineage_enabled": True, + }, + "resolved_git_commit_sha": "resolved_git_commit_sha_value", + "dataform_core_version": "dataform_core_version_value", + "compilation_errors": [ + { + "message": "message_value", + "stack": "stack_value", + "path": "path_value", + "action_target": { + "database": "database_value", + "schema": "schema_value", + "name": "name_value", + }, + } + ], + "data_encryption_state": {"kms_key_version_name": "kms_key_version_name_value"}, + "create_time": {"seconds": 751, "nanos": 543}, + "internal_metadata": "internal_metadata_value", + "private_resource_metadata": {"user_scoped": True}, + "gcs_repository_snapshot_metadata": { + "repository_snapshot_uri": "repository_snapshot_uri_value", + "crc32c_checksum": "crc32c_checksum_value", + "generation": 1068, + }, + } + # 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 = dataform.CreateCompilationResultRequest.meta.fields[ + "compilation_result" + ] + + 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["compilation_result"].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["compilation_result"][field])): + del request_init["compilation_result"][field][i][subfield] + else: + del request_init["compilation_result"][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_compilation_result_long_running(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_compilation_result_long_running_rest_interceptors(null_interceptor): + transport = transports.DataformRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.DataformRestInterceptor(), + ) + client = DataformClient(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.DataformRestInterceptor, + "post_create_compilation_result_long_running", + ) as post, + mock.patch.object( + transports.DataformRestInterceptor, + "post_create_compilation_result_long_running_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DataformRestInterceptor, + "pre_create_compilation_result_long_running", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = dataform.CreateCompilationResultRequest.pb( + dataform.CreateCompilationResultRequest() + ) + 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 = dataform.CreateCompilationResultRequest() + 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_compilation_result_long_running( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + def test_query_compilation_result_actions_rest_bad_request( request_type=dataform.QueryCompilationResultActionsRequest, ): @@ -55761,6 +57457,8 @@ def test_create_workflow_config_rest_call_success(request_type): }, }, "query_priority": 1, + "concurrent_actions_limit": 2577, + "execution_mode": 1, }, "cron_schedule": "cron_schedule_value", "time_zone": "time_zone_value", @@ -56037,6 +57735,8 @@ def test_update_workflow_config_rest_call_success(request_type): }, }, "query_priority": 1, + "concurrent_actions_limit": 2577, + "execution_mode": 1, }, "cron_schedule": "cron_schedule_value", "time_zone": "time_zone_value", @@ -56696,6 +58396,8 @@ def test_create_workflow_invocation_rest_call_success(request_type): }, }, "query_priority": 1, + "concurrent_actions_limit": 2577, + "execution_mode": 1, }, "state": 1, "invocation_timing": { @@ -59210,6 +60912,27 @@ def test_fetch_git_ahead_behind_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_fetch_workspace_history_empty_call_rest(): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_workspace_history), "__call__" + ) as call: + client.fetch_workspace_history(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.FetchWorkspaceHistoryRequest() + 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_commit_workspace_changes_empty_call_rest(): @@ -59612,6 +61335,27 @@ def test_create_compilation_result_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_create_compilation_result_long_running_empty_call_rest(): + client = DataformClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_compilation_result_long_running), "__call__" + ) as call: + client.create_compilation_result_long_running(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = dataform.CreateCompilationResultRequest() + 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_query_compilation_result_actions_empty_call_rest(): @@ -60053,6 +61797,7 @@ def test_dataform_base_transport(): "push_git_commits", "fetch_file_git_statuses", "fetch_git_ahead_behind", + "fetch_workspace_history", "commit_workspace_changes", "reset_workspace_changes", "fetch_file_diff", @@ -60073,6 +61818,7 @@ def test_dataform_base_transport(): "list_compilation_results", "get_compilation_result", "create_compilation_result", + "create_compilation_result_long_running", "query_compilation_result_actions", "list_workflow_configs", "get_workflow_config", @@ -60501,6 +62247,9 @@ def test_dataform_client_transport_session_collision(transport_name): session1 = client1.transport.fetch_git_ahead_behind._session session2 = client2.transport.fetch_git_ahead_behind._session assert session1 != session2 + session1 = client1.transport.fetch_workspace_history._session + session2 = client2.transport.fetch_workspace_history._session + assert session1 != session2 session1 = client1.transport.commit_workspace_changes._session session2 = client2.transport.commit_workspace_changes._session assert session1 != session2 @@ -60561,6 +62310,9 @@ def test_dataform_client_transport_session_collision(transport_name): session1 = client1.transport.create_compilation_result._session session2 = client2.transport.create_compilation_result._session assert session1 != session2 + session1 = client1.transport.create_compilation_result_long_running._session + session2 = client2.transport.create_compilation_result_long_running._session + assert session1 != session2 session1 = client1.transport.query_compilation_result_actions._session session2 = client2.transport.query_compilation_result_actions._session assert session1 != session2 @@ -60767,11 +62519,37 @@ def test_dataform_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client -def test_compilation_result_path(): +def test_account_connector_path(): project = "squid" location = "clam" - repository = "whelk" - compilation_result = "octopus" + account_connector = "whelk" + expected = "projects/{project}/locations/{location}/accountConnectors/{account_connector}".format( + project=project, + location=location, + account_connector=account_connector, + ) + actual = DataformClient.account_connector_path(project, location, account_connector) + assert expected == actual + + +def test_parse_account_connector_path(): + expected = { + "project": "octopus", + "location": "oyster", + "account_connector": "nudibranch", + } + path = DataformClient.account_connector_path(**expected) + + # Check that the path construction is reversible. + actual = DataformClient.parse_account_connector_path(path) + assert expected == actual + + +def test_compilation_result_path(): + project = "cuttlefish" + location = "mussel" + repository = "winkle" + compilation_result = "nautilus" expected = "projects/{project}/locations/{location}/repositories/{repository}/compilationResults/{compilation_result}".format( project=project, location=location, @@ -60786,10 +62564,10 @@ def test_compilation_result_path(): def test_parse_compilation_result_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "repository": "cuttlefish", - "compilation_result": "mussel", + "project": "scallop", + "location": "abalone", + "repository": "squid", + "compilation_result": "clam", } path = DataformClient.compilation_result_path(**expected) @@ -60799,8 +62577,8 @@ def test_parse_compilation_result_path(): def test_config_path(): - project = "winkle" - location = "nautilus" + project = "whelk" + location = "octopus" expected = "projects/{project}/locations/{location}/config".format( project=project, location=location, @@ -60811,8 +62589,8 @@ def test_config_path(): def test_parse_config_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "oyster", + "location": "nudibranch", } path = DataformClient.config_path(**expected) @@ -60822,10 +62600,10 @@ def test_parse_config_path(): def test_crypto_key_path(): - project = "squid" - location = "clam" - key_ring = "whelk" - crypto_key = "octopus" + project = "cuttlefish" + location = "mussel" + key_ring = "winkle" + crypto_key = "nautilus" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( project=project, location=location, @@ -60838,10 +62616,10 @@ def test_crypto_key_path(): def test_parse_crypto_key_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "key_ring": "cuttlefish", - "crypto_key": "mussel", + "project": "scallop", + "location": "abalone", + "key_ring": "squid", + "crypto_key": "clam", } path = DataformClient.crypto_key_path(**expected) @@ -60851,11 +62629,11 @@ def test_parse_crypto_key_path(): def test_crypto_key_version_path(): - project = "winkle" - location = "nautilus" - key_ring = "scallop" - crypto_key = "abalone" - crypto_key_version = "squid" + project = "whelk" + location = "octopus" + key_ring = "oyster" + crypto_key = "nudibranch" + crypto_key_version = "cuttlefish" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( project=project, location=location, @@ -60871,11 +62649,11 @@ def test_crypto_key_version_path(): def test_parse_crypto_key_version_path(): expected = { - "project": "clam", - "location": "whelk", - "key_ring": "octopus", - "crypto_key": "oyster", - "crypto_key_version": "nudibranch", + "project": "mussel", + "location": "winkle", + "key_ring": "nautilus", + "crypto_key": "scallop", + "crypto_key_version": "abalone", } path = DataformClient.crypto_key_version_path(**expected) @@ -60885,9 +62663,9 @@ def test_parse_crypto_key_version_path(): def test_folder_path(): - project = "cuttlefish" - location = "mussel" - folder = "winkle" + project = "squid" + location = "clam" + folder = "whelk" expected = "projects/{project}/locations/{location}/folders/{folder}".format( project=project, location=location, @@ -60899,9 +62677,9 @@ def test_folder_path(): def test_parse_folder_path(): expected = { - "project": "nautilus", - "location": "scallop", - "folder": "abalone", + "project": "octopus", + "location": "oyster", + "folder": "nudibranch", } path = DataformClient.folder_path(**expected) @@ -60911,10 +62689,10 @@ def test_parse_folder_path(): def test_git_repository_link_path(): - project = "squid" - location = "clam" - connection = "whelk" - git_repository_link = "octopus" + project = "cuttlefish" + location = "mussel" + connection = "winkle" + git_repository_link = "nautilus" expected = "projects/{project}/locations/{location}/connections/{connection}/gitRepositoryLinks/{git_repository_link}".format( project=project, location=location, @@ -60929,10 +62707,10 @@ def test_git_repository_link_path(): def test_parse_git_repository_link_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "connection": "cuttlefish", - "git_repository_link": "mussel", + "project": "scallop", + "location": "abalone", + "connection": "squid", + "git_repository_link": "clam", } path = DataformClient.git_repository_link_path(**expected) @@ -60942,9 +62720,9 @@ def test_parse_git_repository_link_path(): def test_notebook_runtime_template_path(): - project = "winkle" - location = "nautilus" - notebook_runtime_template = "scallop" + project = "whelk" + location = "octopus" + notebook_runtime_template = "oyster" expected = "projects/{project}/locations/{location}/notebookRuntimeTemplates/{notebook_runtime_template}".format( project=project, location=location, @@ -60958,9 +62736,9 @@ def test_notebook_runtime_template_path(): def test_parse_notebook_runtime_template_path(): expected = { - "project": "abalone", - "location": "squid", - "notebook_runtime_template": "clam", + "project": "nudibranch", + "location": "cuttlefish", + "notebook_runtime_template": "mussel", } path = DataformClient.notebook_runtime_template_path(**expected) @@ -60970,10 +62748,10 @@ def test_parse_notebook_runtime_template_path(): def test_release_config_path(): - project = "whelk" - location = "octopus" - repository = "oyster" - release_config = "nudibranch" + project = "winkle" + location = "nautilus" + repository = "scallop" + release_config = "abalone" expected = "projects/{project}/locations/{location}/repositories/{repository}/releaseConfigs/{release_config}".format( project=project, location=location, @@ -60988,10 +62766,10 @@ def test_release_config_path(): def test_parse_release_config_path(): expected = { - "project": "cuttlefish", - "location": "mussel", - "repository": "winkle", - "release_config": "nautilus", + "project": "squid", + "location": "clam", + "repository": "whelk", + "release_config": "octopus", } path = DataformClient.release_config_path(**expected) @@ -61001,9 +62779,9 @@ def test_parse_release_config_path(): def test_repository_path(): - project = "scallop" - location = "abalone" - repository = "squid" + project = "oyster" + location = "nudibranch" + repository = "cuttlefish" expected = ( "projects/{project}/locations/{location}/repositories/{repository}".format( project=project, @@ -61017,9 +62795,9 @@ def test_repository_path(): def test_parse_repository_path(): expected = { - "project": "clam", - "location": "whelk", - "repository": "octopus", + "project": "mussel", + "location": "winkle", + "repository": "nautilus", } path = DataformClient.repository_path(**expected) @@ -61029,9 +62807,9 @@ def test_parse_repository_path(): def test_secret_version_path(): - project = "oyster" - secret = "nudibranch" - version = "cuttlefish" + project = "scallop" + secret = "abalone" + version = "squid" expected = "projects/{project}/secrets/{secret}/versions/{version}".format( project=project, secret=secret, @@ -61043,9 +62821,9 @@ def test_secret_version_path(): def test_parse_secret_version_path(): expected = { - "project": "mussel", - "secret": "winkle", - "version": "nautilus", + "project": "clam", + "secret": "whelk", + "version": "octopus", } path = DataformClient.secret_version_path(**expected) @@ -61055,9 +62833,9 @@ def test_parse_secret_version_path(): def test_team_folder_path(): - project = "scallop" - location = "abalone" - team_folder = "squid" + project = "oyster" + location = "nudibranch" + team_folder = "cuttlefish" expected = ( "projects/{project}/locations/{location}/teamFolders/{team_folder}".format( project=project, @@ -61071,9 +62849,9 @@ def test_team_folder_path(): def test_parse_team_folder_path(): expected = { - "project": "clam", - "location": "whelk", - "team_folder": "octopus", + "project": "mussel", + "location": "winkle", + "team_folder": "nautilus", } path = DataformClient.team_folder_path(**expected) @@ -61083,10 +62861,10 @@ def test_parse_team_folder_path(): def test_workflow_config_path(): - project = "oyster" - location = "nudibranch" - repository = "cuttlefish" - workflow_config = "mussel" + project = "scallop" + location = "abalone" + repository = "squid" + workflow_config = "clam" expected = "projects/{project}/locations/{location}/repositories/{repository}/workflowConfigs/{workflow_config}".format( project=project, location=location, @@ -61101,10 +62879,10 @@ def test_workflow_config_path(): def test_parse_workflow_config_path(): expected = { - "project": "winkle", - "location": "nautilus", - "repository": "scallop", - "workflow_config": "abalone", + "project": "whelk", + "location": "octopus", + "repository": "oyster", + "workflow_config": "nudibranch", } path = DataformClient.workflow_config_path(**expected) @@ -61114,10 +62892,10 @@ def test_parse_workflow_config_path(): def test_workflow_invocation_path(): - project = "squid" - location = "clam" - repository = "whelk" - workflow_invocation = "octopus" + project = "cuttlefish" + location = "mussel" + repository = "winkle" + workflow_invocation = "nautilus" expected = "projects/{project}/locations/{location}/repositories/{repository}/workflowInvocations/{workflow_invocation}".format( project=project, location=location, @@ -61132,10 +62910,10 @@ def test_workflow_invocation_path(): def test_parse_workflow_invocation_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "repository": "cuttlefish", - "workflow_invocation": "mussel", + "project": "scallop", + "location": "abalone", + "repository": "squid", + "workflow_invocation": "clam", } path = DataformClient.workflow_invocation_path(**expected) @@ -61145,10 +62923,10 @@ def test_parse_workflow_invocation_path(): def test_workspace_path(): - project = "winkle" - location = "nautilus" - repository = "scallop" - workspace = "abalone" + project = "whelk" + location = "octopus" + repository = "oyster" + workspace = "nudibranch" expected = "projects/{project}/locations/{location}/repositories/{repository}/workspaces/{workspace}".format( project=project, location=location, @@ -61161,10 +62939,10 @@ def test_workspace_path(): def test_parse_workspace_path(): expected = { - "project": "squid", - "location": "clam", - "repository": "whelk", - "workspace": "octopus", + "project": "cuttlefish", + "location": "mussel", + "repository": "winkle", + "workspace": "nautilus", } path = DataformClient.workspace_path(**expected) @@ -61174,7 +62952,7 @@ def test_parse_workspace_path(): def test_common_billing_account_path(): - billing_account = "oyster" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -61184,7 +62962,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nudibranch", + "billing_account": "abalone", } path = DataformClient.common_billing_account_path(**expected) @@ -61194,7 +62972,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "cuttlefish" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -61204,7 +62982,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "mussel", + "folder": "clam", } path = DataformClient.common_folder_path(**expected) @@ -61214,7 +62992,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "winkle" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -61224,7 +63002,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nautilus", + "organization": "octopus", } path = DataformClient.common_organization_path(**expected) @@ -61234,7 +63012,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "scallop" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -61244,7 +63022,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "abalone", + "project": "nudibranch", } path = DataformClient.common_project_path(**expected) @@ -61254,8 +63032,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "squid" - location = "clam" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -61266,8 +63044,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "whelk", - "location": "octopus", + "project": "winkle", + "location": "nautilus", } path = DataformClient.common_location_path(**expected) diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect/__init__.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect/__init__.py index 258a1cd39407..e4a6207e2e27 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect/__init__.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect/__init__.py @@ -32,8 +32,12 @@ ) from google.cloud.developerconnect_v1.types.developer_connect import ( AccountConnector, + AddGitRepositoryLinkPullRequestCommentRequest, + AddGitRepositoryLinkPullRequestReviewCommentRequest, BitbucketCloudConfig, BitbucketDataCenterConfig, + BlameRange, + CommitView, Connection, CreateAccountConnectorRequest, CreateConnectionRequest, @@ -44,6 +48,8 @@ DeleteGitRepositoryLinkRequest, DeleteSelfRequest, DeleteUserRequest, + DiffGitRepositoryLinkCommitRequest, + DiffGitRepositoryLinkCommitResponse, ExchangeError, FetchAccessTokenRequest, FetchAccessTokenResponse, @@ -51,6 +57,15 @@ FetchGitHubInstallationsResponse, FetchGitRefsRequest, FetchGitRefsResponse, + FetchGitRepositoryLinkCommitListRequest, + FetchGitRepositoryLinkCommitListResponse, + FetchGitRepositoryLinkCommitRequest, + FetchGitRepositoryLinkCommitResponse, + FetchGitRepositoryLinkFileBlameRequest, + FetchGitRepositoryLinkFileBlameResponse, + FetchGitRepositoryLinkPullRequestListRequest, + FetchGitRepositoryLinkPullRequestListResponse, + FetchGitRepositoryLinkPullRequestRequest, FetchLinkableGitRepositoriesRequest, FetchLinkableGitRepositoriesResponse, FetchReadTokenRequest, @@ -58,6 +73,7 @@ FetchReadWriteTokenRequest, FetchReadWriteTokenResponse, FetchSelfRequest, + FileDiff, FinishOAuthRequest, FinishOAuthResponse, GenericHTTPEndpointConfig, @@ -80,9 +96,15 @@ ListGitRepositoryLinksResponse, ListUsersRequest, ListUsersResponse, + ModifyGitRepositoryLinkPullRequestRequest, OAuthCredential, + OpenGitRepositoryLinkPullRequestRequest, OperationMetadata, ProviderOAuthConfig, + PullRequest, + PullRequestComment, + PullRequestReviewComment, + SCMCommit, SecureSourceManagerInstanceConfig, ServiceDirectoryConfig, StartOAuthRequest, @@ -123,8 +145,11 @@ "InsightsConfigServiceClient", "InsightsConfigServiceAsyncClient", "AccountConnector", + "AddGitRepositoryLinkPullRequestCommentRequest", + "AddGitRepositoryLinkPullRequestReviewCommentRequest", "BitbucketCloudConfig", "BitbucketDataCenterConfig", + "BlameRange", "Connection", "CreateAccountConnectorRequest", "CreateConnectionRequest", @@ -135,6 +160,8 @@ "DeleteGitRepositoryLinkRequest", "DeleteSelfRequest", "DeleteUserRequest", + "DiffGitRepositoryLinkCommitRequest", + "DiffGitRepositoryLinkCommitResponse", "ExchangeError", "FetchAccessTokenRequest", "FetchAccessTokenResponse", @@ -142,6 +169,15 @@ "FetchGitHubInstallationsResponse", "FetchGitRefsRequest", "FetchGitRefsResponse", + "FetchGitRepositoryLinkCommitListRequest", + "FetchGitRepositoryLinkCommitListResponse", + "FetchGitRepositoryLinkCommitRequest", + "FetchGitRepositoryLinkCommitResponse", + "FetchGitRepositoryLinkFileBlameRequest", + "FetchGitRepositoryLinkFileBlameResponse", + "FetchGitRepositoryLinkPullRequestListRequest", + "FetchGitRepositoryLinkPullRequestListResponse", + "FetchGitRepositoryLinkPullRequestRequest", "FetchLinkableGitRepositoriesRequest", "FetchLinkableGitRepositoriesResponse", "FetchReadTokenRequest", @@ -149,6 +185,7 @@ "FetchReadWriteTokenRequest", "FetchReadWriteTokenResponse", "FetchSelfRequest", + "FileDiff", "FinishOAuthRequest", "FinishOAuthResponse", "GenericHTTPEndpointConfig", @@ -171,9 +208,15 @@ "ListGitRepositoryLinksResponse", "ListUsersRequest", "ListUsersResponse", + "ModifyGitRepositoryLinkPullRequestRequest", "OAuthCredential", + "OpenGitRepositoryLinkPullRequestRequest", "OperationMetadata", "ProviderOAuthConfig", + "PullRequest", + "PullRequestComment", + "PullRequestReviewComment", + "SCMCommit", "SecureSourceManagerInstanceConfig", "ServiceDirectoryConfig", "StartOAuthRequest", @@ -182,6 +225,7 @@ "UpdateConnectionRequest", "User", "UserCredential", + "CommitView", "SystemProvider", "AppHubService", "AppHubWorkload", diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/__init__.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/__init__.py index cfd8d91c18f4..6cd6eba890f5 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/__init__.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/__init__.py @@ -43,8 +43,12 @@ ) from .types.developer_connect import ( AccountConnector, + AddGitRepositoryLinkPullRequestCommentRequest, + AddGitRepositoryLinkPullRequestReviewCommentRequest, BitbucketCloudConfig, BitbucketDataCenterConfig, + BlameRange, + CommitView, Connection, CreateAccountConnectorRequest, CreateConnectionRequest, @@ -55,6 +59,8 @@ DeleteGitRepositoryLinkRequest, DeleteSelfRequest, DeleteUserRequest, + DiffGitRepositoryLinkCommitRequest, + DiffGitRepositoryLinkCommitResponse, ExchangeError, FetchAccessTokenRequest, FetchAccessTokenResponse, @@ -62,6 +68,15 @@ FetchGitHubInstallationsResponse, FetchGitRefsRequest, FetchGitRefsResponse, + FetchGitRepositoryLinkCommitListRequest, + FetchGitRepositoryLinkCommitListResponse, + FetchGitRepositoryLinkCommitRequest, + FetchGitRepositoryLinkCommitResponse, + FetchGitRepositoryLinkFileBlameRequest, + FetchGitRepositoryLinkFileBlameResponse, + FetchGitRepositoryLinkPullRequestListRequest, + FetchGitRepositoryLinkPullRequestListResponse, + FetchGitRepositoryLinkPullRequestRequest, FetchLinkableGitRepositoriesRequest, FetchLinkableGitRepositoriesResponse, FetchReadTokenRequest, @@ -69,6 +84,7 @@ FetchReadWriteTokenRequest, FetchReadWriteTokenResponse, FetchSelfRequest, + FileDiff, FinishOAuthRequest, FinishOAuthResponse, GenericHTTPEndpointConfig, @@ -91,9 +107,15 @@ ListGitRepositoryLinksResponse, ListUsersRequest, ListUsersResponse, + ModifyGitRepositoryLinkPullRequestRequest, OAuthCredential, + OpenGitRepositoryLinkPullRequestRequest, OperationMetadata, ProviderOAuthConfig, + PullRequest, + PullRequestComment, + PullRequestReviewComment, + SCMCommit, SecureSourceManagerInstanceConfig, ServiceDirectoryConfig, StartOAuthRequest, @@ -132,12 +154,16 @@ "DeveloperConnectAsyncClient", "InsightsConfigServiceAsyncClient", "AccountConnector", + "AddGitRepositoryLinkPullRequestCommentRequest", + "AddGitRepositoryLinkPullRequestReviewCommentRequest", "AppHubService", "AppHubWorkload", "ArtifactConfig", "ArtifactDeployment", "BitbucketCloudConfig", "BitbucketDataCenterConfig", + "BlameRange", + "CommitView", "Connection", "CreateAccountConnectorRequest", "CreateConnectionRequest", @@ -152,6 +178,8 @@ "DeleteUserRequest", "DeploymentEvent", "DeveloperConnectClient", + "DiffGitRepositoryLinkCommitRequest", + "DiffGitRepositoryLinkCommitResponse", "ExchangeError", "FetchAccessTokenRequest", "FetchAccessTokenResponse", @@ -159,6 +187,15 @@ "FetchGitHubInstallationsResponse", "FetchGitRefsRequest", "FetchGitRefsResponse", + "FetchGitRepositoryLinkCommitListRequest", + "FetchGitRepositoryLinkCommitListResponse", + "FetchGitRepositoryLinkCommitRequest", + "FetchGitRepositoryLinkCommitResponse", + "FetchGitRepositoryLinkFileBlameRequest", + "FetchGitRepositoryLinkFileBlameResponse", + "FetchGitRepositoryLinkPullRequestListRequest", + "FetchGitRepositoryLinkPullRequestListResponse", + "FetchGitRepositoryLinkPullRequestRequest", "FetchLinkableGitRepositoriesRequest", "FetchLinkableGitRepositoriesResponse", "FetchReadTokenRequest", @@ -166,6 +203,7 @@ "FetchReadWriteTokenRequest", "FetchReadWriteTokenResponse", "FetchSelfRequest", + "FileDiff", "FinishOAuthRequest", "FinishOAuthResponse", "GKEWorkload", @@ -200,11 +238,17 @@ "ListInsightsConfigsResponse", "ListUsersRequest", "ListUsersResponse", + "ModifyGitRepositoryLinkPullRequestRequest", "OAuthCredential", + "OpenGitRepositoryLinkPullRequestRequest", "OperationMetadata", "Projects", "ProviderOAuthConfig", + "PullRequest", + "PullRequestComment", + "PullRequestReviewComment", "RuntimeConfig", + "SCMCommit", "SecureSourceManagerInstanceConfig", "ServiceDirectoryConfig", "StartOAuthRequest", diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/gapic_metadata.json b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/gapic_metadata.json index d23287bdfd1c..874de072d9b2 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/gapic_metadata.json +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/gapic_metadata.json @@ -10,6 +10,16 @@ "grpc": { "libraryClient": "DeveloperConnectClient", "rpcs": { + "AddGitRepositoryLinkPullRequestComment": { + "methods": [ + "add_git_repository_link_pull_request_comment" + ] + }, + "AddGitRepositoryLinkPullRequestReviewComment": { + "methods": [ + "add_git_repository_link_pull_request_review_comment" + ] + }, "CreateAccountConnector": { "methods": [ "create_account_connector" @@ -50,6 +60,11 @@ "delete_user" ] }, + "DiffGitRepositoryLinkCommit": { + "methods": [ + "diff_git_repository_link_commit" + ] + }, "FetchAccessToken": { "methods": [ "fetch_access_token" @@ -65,6 +80,31 @@ "fetch_git_refs" ] }, + "FetchGitRepositoryLinkCommit": { + "methods": [ + "fetch_git_repository_link_commit" + ] + }, + "FetchGitRepositoryLinkCommitList": { + "methods": [ + "fetch_git_repository_link_commit_list" + ] + }, + "FetchGitRepositoryLinkFileBlame": { + "methods": [ + "fetch_git_repository_link_file_blame" + ] + }, + "FetchGitRepositoryLinkPullRequest": { + "methods": [ + "fetch_git_repository_link_pull_request" + ] + }, + "FetchGitRepositoryLinkPullRequestList": { + "methods": [ + "fetch_git_repository_link_pull_request_list" + ] + }, "FetchLinkableGitRepositories": { "methods": [ "fetch_linkable_git_repositories" @@ -125,6 +165,16 @@ "list_users" ] }, + "ModifyGitRepositoryLinkPullRequest": { + "methods": [ + "modify_git_repository_link_pull_request" + ] + }, + "OpenGitRepositoryLinkPullRequest": { + "methods": [ + "open_git_repository_link_pull_request" + ] + }, "StartOAuth": { "methods": [ "start_o_auth" @@ -145,6 +195,16 @@ "grpc-async": { "libraryClient": "DeveloperConnectAsyncClient", "rpcs": { + "AddGitRepositoryLinkPullRequestComment": { + "methods": [ + "add_git_repository_link_pull_request_comment" + ] + }, + "AddGitRepositoryLinkPullRequestReviewComment": { + "methods": [ + "add_git_repository_link_pull_request_review_comment" + ] + }, "CreateAccountConnector": { "methods": [ "create_account_connector" @@ -185,6 +245,11 @@ "delete_user" ] }, + "DiffGitRepositoryLinkCommit": { + "methods": [ + "diff_git_repository_link_commit" + ] + }, "FetchAccessToken": { "methods": [ "fetch_access_token" @@ -200,6 +265,31 @@ "fetch_git_refs" ] }, + "FetchGitRepositoryLinkCommit": { + "methods": [ + "fetch_git_repository_link_commit" + ] + }, + "FetchGitRepositoryLinkCommitList": { + "methods": [ + "fetch_git_repository_link_commit_list" + ] + }, + "FetchGitRepositoryLinkFileBlame": { + "methods": [ + "fetch_git_repository_link_file_blame" + ] + }, + "FetchGitRepositoryLinkPullRequest": { + "methods": [ + "fetch_git_repository_link_pull_request" + ] + }, + "FetchGitRepositoryLinkPullRequestList": { + "methods": [ + "fetch_git_repository_link_pull_request_list" + ] + }, "FetchLinkableGitRepositories": { "methods": [ "fetch_linkable_git_repositories" @@ -260,6 +350,16 @@ "list_users" ] }, + "ModifyGitRepositoryLinkPullRequest": { + "methods": [ + "modify_git_repository_link_pull_request" + ] + }, + "OpenGitRepositoryLinkPullRequest": { + "methods": [ + "open_git_repository_link_pull_request" + ] + }, "StartOAuth": { "methods": [ "start_o_auth" @@ -280,6 +380,16 @@ "rest": { "libraryClient": "DeveloperConnectClient", "rpcs": { + "AddGitRepositoryLinkPullRequestComment": { + "methods": [ + "add_git_repository_link_pull_request_comment" + ] + }, + "AddGitRepositoryLinkPullRequestReviewComment": { + "methods": [ + "add_git_repository_link_pull_request_review_comment" + ] + }, "CreateAccountConnector": { "methods": [ "create_account_connector" @@ -320,6 +430,11 @@ "delete_user" ] }, + "DiffGitRepositoryLinkCommit": { + "methods": [ + "diff_git_repository_link_commit" + ] + }, "FetchAccessToken": { "methods": [ "fetch_access_token" @@ -335,6 +450,31 @@ "fetch_git_refs" ] }, + "FetchGitRepositoryLinkCommit": { + "methods": [ + "fetch_git_repository_link_commit" + ] + }, + "FetchGitRepositoryLinkCommitList": { + "methods": [ + "fetch_git_repository_link_commit_list" + ] + }, + "FetchGitRepositoryLinkFileBlame": { + "methods": [ + "fetch_git_repository_link_file_blame" + ] + }, + "FetchGitRepositoryLinkPullRequest": { + "methods": [ + "fetch_git_repository_link_pull_request" + ] + }, + "FetchGitRepositoryLinkPullRequestList": { + "methods": [ + "fetch_git_repository_link_pull_request_list" + ] + }, "FetchLinkableGitRepositories": { "methods": [ "fetch_linkable_git_repositories" @@ -395,6 +535,16 @@ "list_users" ] }, + "ModifyGitRepositoryLinkPullRequest": { + "methods": [ + "modify_git_repository_link_pull_request" + ] + }, + "OpenGitRepositoryLinkPullRequest": { + "methods": [ + "open_git_repository_link_pull_request" + ] + }, "StartOAuth": { "methods": [ "start_o_auth" diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/async_client.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/async_client.py index 2a567ad9328e..3e5354166515 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/async_client.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/async_client.py @@ -1744,6 +1744,139 @@ async def sample_fetch_read_token(): # Done; return the response. return response + async def open_git_repository_link_pull_request( + self, + request: Optional[ + Union[developer_connect.OpenGitRepositoryLinkPullRequestRequest, dict] + ] = None, + *, + name: Optional[str] = None, + pull_request: Optional[developer_connect.PullRequest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.PullRequest: + r"""Opens a Pull Request in the remote SCM repository + associated with a GitRepositoryLink. + + .. 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 developerconnect_v1 + + async def sample_open_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + pull_request = developerconnect_v1.PullRequest() + pull_request.id = "id_value" + pull_request.title = "title_value" + pull_request.head_ref = "head_ref_value" + pull_request.base_ref = "base_ref_value" + + request = developerconnect_v1.OpenGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request=pull_request, + ) + + # Make the request + response = await client.open_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.OpenGitRepositoryLinkPullRequestRequest, dict]]): + The request object. Message for opening SCM Pull Request. + name (:class:`str`): + Required. The GitRepositoryLink resource name in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request (:class:`google.cloud.developerconnect_v1.types.PullRequest`): + Required. The Pull Request details to open. Input fields + used: title, body, head_ref, base_ref. + + This corresponds to the ``pull_request`` 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.developerconnect_v1.types.PullRequest: + Message representing a SCM Pull + Request. + + """ + # 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, pull_request] + 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, developer_connect.OpenGitRepositoryLinkPullRequestRequest + ): + request = developer_connect.OpenGitRepositoryLinkPullRequestRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request is not None: + request.pull_request = pull_request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.open_git_repository_link_pull_request + ] + + # 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 fetch_linkable_git_repositories( self, request: Optional[ @@ -2135,6 +2268,1229 @@ async def sample_fetch_git_refs(): # Done; return the response. return response + async def diff_git_repository_link_commit( + self, + request: Optional[ + Union[developer_connect.DiffGitRepositoryLinkCommitRequest, dict] + ] = None, + *, + name: Optional[str] = None, + base_sha: Optional[str] = None, + head_sha: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.DiffGitRepositoryLinkCommitResponse: + r"""Diff commits for a GitRepositoryLink. + + .. 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 developerconnect_v1 + + async def sample_diff_git_repository_link_commit(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.DiffGitRepositoryLinkCommitRequest( + name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", + ) + + # Make the request + response = await client.diff_git_repository_link_commit(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.DiffGitRepositoryLinkCommitRequest, dict]]): + The request object. Request message for + DiffGitRepositoryLinkCommit. + name (:class:`str`): + Required. The resource name of the + GitRepositoryLink. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + base_sha (:class:`str`): + Required. The base commit SHA or ref. + This corresponds to the ``base_sha`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + head_sha (:class:`str`): + Required. The head commit SHA or ref. + This corresponds to the ``head_sha`` 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.developerconnect_v1.types.DiffGitRepositoryLinkCommitResponse: + Response message for + DiffGitRepositoryLinkCommit. + + """ + # 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, base_sha, head_sha] + 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, developer_connect.DiffGitRepositoryLinkCommitRequest + ): + request = developer_connect.DiffGitRepositoryLinkCommitRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if base_sha is not None: + request.base_sha = base_sha + if head_sha is not None: + request.head_sha = head_sha + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.diff_git_repository_link_commit + ] + + # 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 fetch_git_repository_link_commit( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkCommitRequest, dict] + ] = None, + *, + name: Optional[str] = None, + commit_sha: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.FetchGitRepositoryLinkCommitResponse: + r"""Fetch Commit details from a Git repository link. + + .. 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 developerconnect_v1 + + async def sample_fetch_git_repository_link_commit(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkCommitRequest( + name="name_value", + commit_sha="commit_sha_value", + ) + + # Make the request + response = await client.fetch_git_repository_link_commit(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitRequest, dict]]): + The request object. Request message for + FetchGitRepositoryLinkCommit. + name (:class:`str`): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + commit_sha (:class:`str`): + Required. The commit SHA, or symbolic + revision (e.g., branch name, tag, or Git + reference). + + This corresponds to the ``commit_sha`` 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.developerconnect_v1.types.FetchGitRepositoryLinkCommitResponse: + Response message for + FetchGitRepositoryLinkCommit. + + """ + # 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, commit_sha] + 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, developer_connect.FetchGitRepositoryLinkCommitRequest + ): + request = developer_connect.FetchGitRepositoryLinkCommitRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if commit_sha is not None: + request.commit_sha = commit_sha + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_git_repository_link_commit + ] + + # 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 fetch_git_repository_link_commit_list( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkCommitListRequest, dict] + ] = None, + *, + name: Optional[str] = None, + ref: 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.FetchGitRepositoryLinkCommitListAsyncPager: + r"""Fetch a list of Commits from a Git repository link. + + .. 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 developerconnect_v1 + + async def sample_fetch_git_repository_link_commit_list(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkCommitListRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_git_repository_link_commit_list(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListRequest, dict]]): + The request object. Request message for + FetchGitRepositoryLinkCommitList. + name (:class:`str`): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ref (:class:`str`): + Optional. The commit SHA, or symbolic + revision (e.g., branch name, tag, or Git + reference) from which to start listing + commits. + + This corresponds to the ``ref`` 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.developerconnect_v1.services.developer_connect.pagers.FetchGitRepositoryLinkCommitListAsyncPager: + Response message for + FetchGitRepositoryLinkCommitList. + 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 = [name, ref] + 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, developer_connect.FetchGitRepositoryLinkCommitListRequest + ): + request = developer_connect.FetchGitRepositoryLinkCommitListRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ref is not None: + request.ref = ref + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_git_repository_link_commit_list + ] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchGitRepositoryLinkCommitListAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def fetch_git_repository_link_file_blame( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkFileBlameRequest, dict] + ] = None, + *, + name: Optional[str] = None, + ref: Optional[str] = None, + path: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.FetchGitRepositoryLinkFileBlameResponse: + r"""Fetches blame information for a file or line range in + a file. + + .. 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 developerconnect_v1 + + async def sample_fetch_git_repository_link_file_blame(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkFileBlameRequest( + name="name_value", + ref="ref_value", + path="path_value", + ) + + # Make the request + response = await client.fetch_git_repository_link_file_blame(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkFileBlameRequest, dict]]): + The request object. Request message for + FetchGitRepositoryLinkFileBlame. + name (:class:`str`): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ref (:class:`str`): + Required. The SCM commit SHA, or + symbolic revision (e.g., branch name, + tag) from which to fetch the blame. + + This corresponds to the ``ref`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + path (:class:`str`): + Required. The file path within the + repository. + + This corresponds to the ``path`` 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.developerconnect_v1.types.FetchGitRepositoryLinkFileBlameResponse: + Response message for + FetchGitRepositoryLinkFileBlame. + + """ + # 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, ref, path] + 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, developer_connect.FetchGitRepositoryLinkFileBlameRequest + ): + request = developer_connect.FetchGitRepositoryLinkFileBlameRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ref is not None: + request.ref = ref + if path is not None: + request.path = path + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_git_repository_link_file_blame + ] + + # 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 fetch_git_repository_link_pull_request( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkPullRequestRequest, dict] + ] = None, + *, + name: Optional[str] = None, + pull_request_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]]] = (), + ) -> developer_connect.PullRequest: + r"""Fetch Pull Request details from a Git repository + link. + + .. 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 developerconnect_v1 + + async def sample_fetch_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", + ) + + # Make the request + response = await client.fetch_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestRequest, dict]]): + The request object. Request message for + FetchGitRepositoryLinkPullRequest. + name (:class:`str`): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request_id (:class:`str`): + Required. The ID of the Pull Request. + This corresponds to the ``pull_request_id`` 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.developerconnect_v1.types.PullRequest: + Message representing a SCM Pull + Request. + + """ + # 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, pull_request_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, developer_connect.FetchGitRepositoryLinkPullRequestRequest + ): + request = developer_connect.FetchGitRepositoryLinkPullRequestRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request_id is not None: + request.pull_request_id = pull_request_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.fetch_git_repository_link_pull_request + ] + + # 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_git_repository_link_pull_request_comment( + self, + request: Optional[ + Union[developer_connect.AddGitRepositoryLinkPullRequestCommentRequest, dict] + ] = None, + *, + name: Optional[str] = None, + pull_request_id: Optional[str] = None, + comment: Optional[developer_connect.PullRequestComment] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.PullRequestComment: + r"""Add a comment to a Pull 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 developerconnect_v1 + + async def sample_add_git_repository_link_pull_request_comment(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + comment = developerconnect_v1.PullRequestComment() + comment.body = "body_value" + + request = developerconnect_v1.AddGitRepositoryLinkPullRequestCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", + comment=comment, + ) + + # Make the request + response = await client.add_git_repository_link_pull_request_comment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.AddGitRepositoryLinkPullRequestCommentRequest, dict]]): + The request object. Request message for + AddGitRepositoryLinkPullRequestComment. + name (:class:`str`): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request_id (:class:`str`): + Required. The ID of the Pull Request. + This corresponds to the ``pull_request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + comment (:class:`google.cloud.developerconnect_v1.types.PullRequestComment`): + Required. The comment to add. + This corresponds to the ``comment`` 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.developerconnect_v1.types.PullRequestComment: + Message representing a SCM Pull + Request Comment. + + """ + # 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, pull_request_id, comment] + 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, developer_connect.AddGitRepositoryLinkPullRequestCommentRequest + ): + request = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request_id is not None: + request.pull_request_id = pull_request_id + if comment is not None: + request.comment = comment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.add_git_repository_link_pull_request_comment + ] + + # 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_git_repository_link_pull_request_review_comment( + self, + request: Optional[ + Union[ + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + pull_request_id: Optional[str] = None, + comment: Optional[developer_connect.PullRequestReviewComment] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.PullRequestReviewComment: + r"""Add a review comment (inline on diff) to a Pull + 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 developerconnect_v1 + + async def sample_add_git_repository_link_pull_request_review_comment(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + comment = developerconnect_v1.PullRequestReviewComment() + comment.body = "body_value" + comment.path = "path_value" + comment.last_line = 955 + + request = developerconnect_v1.AddGitRepositoryLinkPullRequestReviewCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", + comment=comment, + ) + + # Make the request + response = await client.add_git_repository_link_pull_request_review_comment(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.AddGitRepositoryLinkPullRequestReviewCommentRequest, dict]]): + The request object. Request message for + AddGitRepositoryLinkPullRequestReviewComment. + name (:class:`str`): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request_id (:class:`str`): + Required. The ID of the Pull Request. + This corresponds to the ``pull_request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + comment (:class:`google.cloud.developerconnect_v1.types.PullRequestReviewComment`): + Required. The review comment to add. + This corresponds to the ``comment`` 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.developerconnect_v1.types.PullRequestReviewComment: + Message representing a SCM Pull + Request Review Comment (inline on diff). + + """ + # 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, pull_request_id, comment] + 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, + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, + ): + request = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest( + request + ) + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request_id is not None: + request.pull_request_id = pull_request_id + if comment is not None: + request.comment = comment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.add_git_repository_link_pull_request_review_comment + ] + + # 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 modify_git_repository_link_pull_request( + self, + request: Optional[ + Union[developer_connect.ModifyGitRepositoryLinkPullRequestRequest, dict] + ] = None, + *, + name: Optional[str] = None, + pull_request_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]]] = (), + ) -> developer_connect.PullRequest: + r"""Modifies a Pull Request in the remote SCM repository + associated with a GitRepositoryLink. + + .. 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 developerconnect_v1 + + async def sample_modify_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.ModifyGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", + ) + + # Make the request + response = await client.modify_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.ModifyGitRepositoryLinkPullRequestRequest, dict]]): + The request object. Message for modifying SCM Pull + Request. + name (:class:`str`): + Required. The GitRepositoryLink resource name in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request_id (:class:`str`): + Required. The SCM-specific Pull + Request identifier (e.g., "45"). + + This corresponds to the ``pull_request_id`` 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.developerconnect_v1.types.PullRequest: + Message representing a SCM Pull + Request. + + """ + # 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, pull_request_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, developer_connect.ModifyGitRepositoryLinkPullRequestRequest + ): + request = developer_connect.ModifyGitRepositoryLinkPullRequestRequest( + request + ) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request_id is not None: + request.pull_request_id = pull_request_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.modify_git_repository_link_pull_request + ] + + # 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 fetch_git_repository_link_pull_request_list( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkPullRequestListRequest, 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]]] = (), + ) -> pagers.FetchGitRepositoryLinkPullRequestListAsyncPager: + r"""Fetches a list of Pull Requests from the remote + repository. + + .. 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 developerconnect_v1 + + async def sample_fetch_git_repository_link_pull_request_list(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkPullRequestListRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_git_repository_link_pull_request_list(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListRequest, dict]]): + The request object. Request message for + FetchGitRepositoryLinkPullRequestList. + name (:class:`str`): + Required. The GitRepositoryLink resource name in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + 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.developerconnect_v1.services.developer_connect.pagers.FetchGitRepositoryLinkPullRequestListAsyncPager: + Response message for + FetchGitRepositoryLinkPullRequestList. + 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 = [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, developer_connect.FetchGitRepositoryLinkPullRequestListRequest + ): + request = developer_connect.FetchGitRepositoryLinkPullRequestListRequest( + 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.fetch_git_repository_link_pull_request_list + ] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.FetchGitRepositoryLinkPullRequestListAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_account_connectors( self, request: Optional[ diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/client.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/client.py index ff0774bababd..239ae72cd09e 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/client.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/client.py @@ -2157,6 +2157,138 @@ def sample_fetch_read_token(): # Done; return the response. return response + def open_git_repository_link_pull_request( + self, + request: Optional[ + Union[developer_connect.OpenGitRepositoryLinkPullRequestRequest, dict] + ] = None, + *, + name: Optional[str] = None, + pull_request: Optional[developer_connect.PullRequest] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.PullRequest: + r"""Opens a Pull Request in the remote SCM repository + associated with a GitRepositoryLink. + + .. 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 developerconnect_v1 + + def sample_open_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + pull_request = developerconnect_v1.PullRequest() + pull_request.id = "id_value" + pull_request.title = "title_value" + pull_request.head_ref = "head_ref_value" + pull_request.base_ref = "base_ref_value" + + request = developerconnect_v1.OpenGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request=pull_request, + ) + + # Make the request + response = client.open_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.OpenGitRepositoryLinkPullRequestRequest, dict]): + The request object. Message for opening SCM Pull Request. + name (str): + Required. The GitRepositoryLink resource name in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request (google.cloud.developerconnect_v1.types.PullRequest): + Required. The Pull Request details to open. Input fields + used: title, body, head_ref, base_ref. + + This corresponds to the ``pull_request`` 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.developerconnect_v1.types.PullRequest: + Message representing a SCM Pull + Request. + + """ + # 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, pull_request] + 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, developer_connect.OpenGitRepositoryLinkPullRequestRequest + ): + request = developer_connect.OpenGitRepositoryLinkPullRequestRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request is not None: + request.pull_request = pull_request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.open_git_repository_link_pull_request + ] + + # 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 fetch_linkable_git_repositories( self, request: Optional[ @@ -2543,6 +2675,1220 @@ def sample_fetch_git_refs(): # Done; return the response. return response + def diff_git_repository_link_commit( + self, + request: Optional[ + Union[developer_connect.DiffGitRepositoryLinkCommitRequest, dict] + ] = None, + *, + name: Optional[str] = None, + base_sha: Optional[str] = None, + head_sha: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.DiffGitRepositoryLinkCommitResponse: + r"""Diff commits for a GitRepositoryLink. + + .. 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 developerconnect_v1 + + def sample_diff_git_repository_link_commit(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.DiffGitRepositoryLinkCommitRequest( + name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", + ) + + # Make the request + response = client.diff_git_repository_link_commit(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.DiffGitRepositoryLinkCommitRequest, dict]): + The request object. Request message for + DiffGitRepositoryLinkCommit. + name (str): + Required. The resource name of the + GitRepositoryLink. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + base_sha (str): + Required. The base commit SHA or ref. + This corresponds to the ``base_sha`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + head_sha (str): + Required. The head commit SHA or ref. + This corresponds to the ``head_sha`` 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.developerconnect_v1.types.DiffGitRepositoryLinkCommitResponse: + Response message for + DiffGitRepositoryLinkCommit. + + """ + # 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, base_sha, head_sha] + 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, developer_connect.DiffGitRepositoryLinkCommitRequest + ): + request = developer_connect.DiffGitRepositoryLinkCommitRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if base_sha is not None: + request.base_sha = base_sha + if head_sha is not None: + request.head_sha = head_sha + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.diff_git_repository_link_commit + ] + + # 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 fetch_git_repository_link_commit( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkCommitRequest, dict] + ] = None, + *, + name: Optional[str] = None, + commit_sha: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.FetchGitRepositoryLinkCommitResponse: + r"""Fetch Commit details from a Git repository link. + + .. 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 developerconnect_v1 + + def sample_fetch_git_repository_link_commit(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkCommitRequest( + name="name_value", + commit_sha="commit_sha_value", + ) + + # Make the request + response = client.fetch_git_repository_link_commit(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitRequest, dict]): + The request object. Request message for + FetchGitRepositoryLinkCommit. + name (str): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + commit_sha (str): + Required. The commit SHA, or symbolic + revision (e.g., branch name, tag, or Git + reference). + + This corresponds to the ``commit_sha`` 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.developerconnect_v1.types.FetchGitRepositoryLinkCommitResponse: + Response message for + FetchGitRepositoryLinkCommit. + + """ + # 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, commit_sha] + 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, developer_connect.FetchGitRepositoryLinkCommitRequest + ): + request = developer_connect.FetchGitRepositoryLinkCommitRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if commit_sha is not None: + request.commit_sha = commit_sha + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_git_repository_link_commit + ] + + # 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 fetch_git_repository_link_commit_list( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkCommitListRequest, dict] + ] = None, + *, + name: Optional[str] = None, + ref: 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.FetchGitRepositoryLinkCommitListPager: + r"""Fetch a list of Commits from a Git repository link. + + .. 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 developerconnect_v1 + + def sample_fetch_git_repository_link_commit_list(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkCommitListRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_git_repository_link_commit_list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListRequest, dict]): + The request object. Request message for + FetchGitRepositoryLinkCommitList. + name (str): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ref (str): + Optional. The commit SHA, or symbolic + revision (e.g., branch name, tag, or Git + reference) from which to start listing + commits. + + This corresponds to the ``ref`` 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.developerconnect_v1.services.developer_connect.pagers.FetchGitRepositoryLinkCommitListPager: + Response message for + FetchGitRepositoryLinkCommitList. + 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 = [name, ref] + 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, developer_connect.FetchGitRepositoryLinkCommitListRequest + ): + request = developer_connect.FetchGitRepositoryLinkCommitListRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ref is not None: + request.ref = ref + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_git_repository_link_commit_list + ] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchGitRepositoryLinkCommitListPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def fetch_git_repository_link_file_blame( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkFileBlameRequest, dict] + ] = None, + *, + name: Optional[str] = None, + ref: Optional[str] = None, + path: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.FetchGitRepositoryLinkFileBlameResponse: + r"""Fetches blame information for a file or line range in + a file. + + .. 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 developerconnect_v1 + + def sample_fetch_git_repository_link_file_blame(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkFileBlameRequest( + name="name_value", + ref="ref_value", + path="path_value", + ) + + # Make the request + response = client.fetch_git_repository_link_file_blame(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkFileBlameRequest, dict]): + The request object. Request message for + FetchGitRepositoryLinkFileBlame. + name (str): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + ref (str): + Required. The SCM commit SHA, or + symbolic revision (e.g., branch name, + tag) from which to fetch the blame. + + This corresponds to the ``ref`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + path (str): + Required. The file path within the + repository. + + This corresponds to the ``path`` 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.developerconnect_v1.types.FetchGitRepositoryLinkFileBlameResponse: + Response message for + FetchGitRepositoryLinkFileBlame. + + """ + # 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, ref, path] + 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, developer_connect.FetchGitRepositoryLinkFileBlameRequest + ): + request = developer_connect.FetchGitRepositoryLinkFileBlameRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if ref is not None: + request.ref = ref + if path is not None: + request.path = path + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_git_repository_link_file_blame + ] + + # 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 fetch_git_repository_link_pull_request( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkPullRequestRequest, dict] + ] = None, + *, + name: Optional[str] = None, + pull_request_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]]] = (), + ) -> developer_connect.PullRequest: + r"""Fetch Pull Request details from a Git repository + link. + + .. 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 developerconnect_v1 + + def sample_fetch_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", + ) + + # Make the request + response = client.fetch_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestRequest, dict]): + The request object. Request message for + FetchGitRepositoryLinkPullRequest. + name (str): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request_id (str): + Required. The ID of the Pull Request. + This corresponds to the ``pull_request_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.developerconnect_v1.types.PullRequest: + Message representing a SCM Pull + Request. + + """ + # 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, pull_request_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, developer_connect.FetchGitRepositoryLinkPullRequestRequest + ): + request = developer_connect.FetchGitRepositoryLinkPullRequestRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request_id is not None: + request.pull_request_id = pull_request_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.fetch_git_repository_link_pull_request + ] + + # 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_git_repository_link_pull_request_comment( + self, + request: Optional[ + Union[developer_connect.AddGitRepositoryLinkPullRequestCommentRequest, dict] + ] = None, + *, + name: Optional[str] = None, + pull_request_id: Optional[str] = None, + comment: Optional[developer_connect.PullRequestComment] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.PullRequestComment: + r"""Add a comment to a Pull 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 developerconnect_v1 + + def sample_add_git_repository_link_pull_request_comment(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + comment = developerconnect_v1.PullRequestComment() + comment.body = "body_value" + + request = developerconnect_v1.AddGitRepositoryLinkPullRequestCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", + comment=comment, + ) + + # Make the request + response = client.add_git_repository_link_pull_request_comment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.AddGitRepositoryLinkPullRequestCommentRequest, dict]): + The request object. Request message for + AddGitRepositoryLinkPullRequestComment. + name (str): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request_id (str): + Required. The ID of the Pull Request. + This corresponds to the ``pull_request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + comment (google.cloud.developerconnect_v1.types.PullRequestComment): + Required. The comment to add. + This corresponds to the ``comment`` 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.developerconnect_v1.types.PullRequestComment: + Message representing a SCM Pull + Request Comment. + + """ + # 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, pull_request_id, comment] + 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, developer_connect.AddGitRepositoryLinkPullRequestCommentRequest + ): + request = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request_id is not None: + request.pull_request_id = pull_request_id + if comment is not None: + request.comment = comment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.add_git_repository_link_pull_request_comment + ] + + # 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_git_repository_link_pull_request_review_comment( + self, + request: Optional[ + Union[ + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, + dict, + ] + ] = None, + *, + name: Optional[str] = None, + pull_request_id: Optional[str] = None, + comment: Optional[developer_connect.PullRequestReviewComment] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.PullRequestReviewComment: + r"""Add a review comment (inline on diff) to a Pull + 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 developerconnect_v1 + + def sample_add_git_repository_link_pull_request_review_comment(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + comment = developerconnect_v1.PullRequestReviewComment() + comment.body = "body_value" + comment.path = "path_value" + comment.last_line = 955 + + request = developerconnect_v1.AddGitRepositoryLinkPullRequestReviewCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", + comment=comment, + ) + + # Make the request + response = client.add_git_repository_link_pull_request_review_comment(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.AddGitRepositoryLinkPullRequestReviewCommentRequest, dict]): + The request object. Request message for + AddGitRepositoryLinkPullRequestReviewComment. + name (str): + Required. The resource name of the GitRepositoryLink in + the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request_id (str): + Required. The ID of the Pull Request. + This corresponds to the ``pull_request_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + comment (google.cloud.developerconnect_v1.types.PullRequestReviewComment): + Required. The review comment to add. + This corresponds to the ``comment`` 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.developerconnect_v1.types.PullRequestReviewComment: + Message representing a SCM Pull + Request Review Comment (inline on diff). + + """ + # 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, pull_request_id, comment] + 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, + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, + ): + request = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest( + request + ) + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request_id is not None: + request.pull_request_id = pull_request_id + if comment is not None: + request.comment = comment + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.add_git_repository_link_pull_request_review_comment + ] + + # 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 modify_git_repository_link_pull_request( + self, + request: Optional[ + Union[developer_connect.ModifyGitRepositoryLinkPullRequestRequest, dict] + ] = None, + *, + name: Optional[str] = None, + pull_request_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]]] = (), + ) -> developer_connect.PullRequest: + r"""Modifies a Pull Request in the remote SCM repository + associated with a GitRepositoryLink. + + .. 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 developerconnect_v1 + + def sample_modify_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.ModifyGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", + ) + + # Make the request + response = client.modify_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.ModifyGitRepositoryLinkPullRequestRequest, dict]): + The request object. Message for modifying SCM Pull + Request. + name (str): + Required. The GitRepositoryLink resource name in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + pull_request_id (str): + Required. The SCM-specific Pull + Request identifier (e.g., "45"). + + This corresponds to the ``pull_request_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.developerconnect_v1.types.PullRequest: + Message representing a SCM Pull + Request. + + """ + # 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, pull_request_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, developer_connect.ModifyGitRepositoryLinkPullRequestRequest + ): + request = developer_connect.ModifyGitRepositoryLinkPullRequestRequest( + request + ) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if pull_request_id is not None: + request.pull_request_id = pull_request_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.modify_git_repository_link_pull_request + ] + + # 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 fetch_git_repository_link_pull_request_list( + self, + request: Optional[ + Union[developer_connect.FetchGitRepositoryLinkPullRequestListRequest, 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]]] = (), + ) -> pagers.FetchGitRepositoryLinkPullRequestListPager: + r"""Fetches a list of Pull Requests from the remote + repository. + + .. 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 developerconnect_v1 + + def sample_fetch_git_repository_link_pull_request_list(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkPullRequestListRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_git_repository_link_pull_request_list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListRequest, dict]): + The request object. Request message for + FetchGitRepositoryLinkPullRequestList. + name (str): + Required. The GitRepositoryLink resource name in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + + 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.developerconnect_v1.services.developer_connect.pagers.FetchGitRepositoryLinkPullRequestListPager: + Response message for + FetchGitRepositoryLinkPullRequestList. + 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 = [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, developer_connect.FetchGitRepositoryLinkPullRequestListRequest + ): + request = developer_connect.FetchGitRepositoryLinkPullRequestListRequest( + 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.fetch_git_repository_link_pull_request_list + ] + + # 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, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.FetchGitRepositoryLinkPullRequestListPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def list_account_connectors( self, request: Optional[ diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/pagers.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/pagers.py index cad8c174d9ed..9877cdb4eb99 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/pagers.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/pagers.py @@ -673,6 +673,343 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class FetchGitRepositoryLinkCommitListPager: + """A pager for iterating through ``fetch_git_repository_link_commit_list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListResponse` object, and + provides an ``__iter__`` method to iterate through its + ``commits`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchGitRepositoryLinkCommitList`` requests and continue to iterate + through the ``commits`` field on the + corresponding responses. + + All the usual :class:`google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListResponse` + 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[ + ..., developer_connect.FetchGitRepositoryLinkCommitListResponse + ], + request: developer_connect.FetchGitRepositoryLinkCommitListRequest, + response: developer_connect.FetchGitRepositoryLinkCommitListResponse, + *, + 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.developerconnect_v1.types.FetchGitRepositoryLinkCommitListRequest): + The initial request object. + response (google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListResponse): + 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 = developer_connect.FetchGitRepositoryLinkCommitListRequest( + 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[developer_connect.FetchGitRepositoryLinkCommitListResponse]: + 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[developer_connect.SCMCommit]: + for page in self.pages: + yield from page.commits + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchGitRepositoryLinkCommitListAsyncPager: + """A pager for iterating through ``fetch_git_repository_link_commit_list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``commits`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchGitRepositoryLinkCommitList`` requests and continue to iterate + through the ``commits`` field on the + corresponding responses. + + All the usual :class:`google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListResponse` + 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[developer_connect.FetchGitRepositoryLinkCommitListResponse] + ], + request: developer_connect.FetchGitRepositoryLinkCommitListRequest, + response: developer_connect.FetchGitRepositoryLinkCommitListResponse, + *, + 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.developerconnect_v1.types.FetchGitRepositoryLinkCommitListRequest): + The initial request object. + response (google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListResponse): + 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 = developer_connect.FetchGitRepositoryLinkCommitListRequest( + 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[developer_connect.FetchGitRepositoryLinkCommitListResponse]: + 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[developer_connect.SCMCommit]: + async def async_generator(): + async for page in self.pages: + for response in page.commits: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchGitRepositoryLinkPullRequestListPager: + """A pager for iterating through ``fetch_git_repository_link_pull_request_list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListResponse` object, and + provides an ``__iter__`` method to iterate through its + ``pull_requests`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``FetchGitRepositoryLinkPullRequestList`` requests and continue to iterate + through the ``pull_requests`` field on the + corresponding responses. + + All the usual :class:`google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListResponse` + 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[ + ..., developer_connect.FetchGitRepositoryLinkPullRequestListResponse + ], + request: developer_connect.FetchGitRepositoryLinkPullRequestListRequest, + response: developer_connect.FetchGitRepositoryLinkPullRequestListResponse, + *, + 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.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListRequest): + The initial request object. + response (google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListResponse): + 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 = developer_connect.FetchGitRepositoryLinkPullRequestListRequest( + 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[developer_connect.FetchGitRepositoryLinkPullRequestListResponse]: + 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[developer_connect.PullRequest]: + for page in self.pages: + yield from page.pull_requests + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class FetchGitRepositoryLinkPullRequestListAsyncPager: + """A pager for iterating through ``fetch_git_repository_link_pull_request_list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``pull_requests`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``FetchGitRepositoryLinkPullRequestList`` requests and continue to iterate + through the ``pull_requests`` field on the + corresponding responses. + + All the usual :class:`google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListResponse` + 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[developer_connect.FetchGitRepositoryLinkPullRequestListResponse], + ], + request: developer_connect.FetchGitRepositoryLinkPullRequestListRequest, + response: developer_connect.FetchGitRepositoryLinkPullRequestListResponse, + *, + 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.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListRequest): + The initial request object. + response (google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListResponse): + 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 = developer_connect.FetchGitRepositoryLinkPullRequestListRequest( + 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[developer_connect.FetchGitRepositoryLinkPullRequestListResponse]: + 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[developer_connect.PullRequest]: + async def async_generator(): + async for page in self.pages: + for response in page.pull_requests: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListAccountConnectorsPager: """A pager for iterating through ``list_account_connectors`` requests. diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/base.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/base.py index 3b2b82f7cfa9..bd95f2c6764d 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/base.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/base.py @@ -287,6 +287,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.open_git_repository_link_pull_request: gapic_v1.method.wrap_method( + self.open_git_repository_link_pull_request, + default_timeout=None, + client_info=client_info, + ), self.fetch_linkable_git_repositories: gapic_v1.method.wrap_method( self.fetch_linkable_git_repositories, default_retry=retries.Retry( @@ -320,6 +325,51 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.diff_git_repository_link_commit: gapic_v1.method.wrap_method( + self.diff_git_repository_link_commit, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_commit: gapic_v1.method.wrap_method( + self.fetch_git_repository_link_commit, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_commit_list: gapic_v1.method.wrap_method( + self.fetch_git_repository_link_commit_list, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_file_blame: gapic_v1.method.wrap_method( + self.fetch_git_repository_link_file_blame, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_pull_request: gapic_v1.method.wrap_method( + self.fetch_git_repository_link_pull_request, + default_timeout=None, + client_info=client_info, + ), + self.add_git_repository_link_pull_request_comment: gapic_v1.method.wrap_method( + self.add_git_repository_link_pull_request_comment, + default_timeout=None, + client_info=client_info, + ), + self.add_git_repository_link_pull_request_review_comment: gapic_v1.method.wrap_method( + self.add_git_repository_link_pull_request_review_comment, + default_timeout=None, + client_info=client_info, + ), + self.modify_git_repository_link_pull_request: gapic_v1.method.wrap_method( + self.modify_git_repository_link_pull_request, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_pull_request_list: gapic_v1.method.wrap_method( + self.fetch_git_repository_link_pull_request_list, + default_timeout=None, + client_info=client_info, + ), self.list_account_connectors: gapic_v1.method.wrap_method( self.list_account_connectors, default_timeout=None, @@ -540,6 +590,15 @@ def fetch_read_token( ]: raise NotImplementedError() + @property + def open_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.OpenGitRepositoryLinkPullRequestRequest], + Union[developer_connect.PullRequest, Awaitable[developer_connect.PullRequest]], + ]: + raise NotImplementedError() + @property def fetch_linkable_git_repositories( self, @@ -576,6 +635,108 @@ def fetch_git_refs( ]: raise NotImplementedError() + @property + def diff_git_repository_link_commit( + self, + ) -> Callable[ + [developer_connect.DiffGitRepositoryLinkCommitRequest], + Union[ + developer_connect.DiffGitRepositoryLinkCommitResponse, + Awaitable[developer_connect.DiffGitRepositoryLinkCommitResponse], + ], + ]: + raise NotImplementedError() + + @property + def fetch_git_repository_link_commit( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkCommitRequest], + Union[ + developer_connect.FetchGitRepositoryLinkCommitResponse, + Awaitable[developer_connect.FetchGitRepositoryLinkCommitResponse], + ], + ]: + raise NotImplementedError() + + @property + def fetch_git_repository_link_commit_list( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkCommitListRequest], + Union[ + developer_connect.FetchGitRepositoryLinkCommitListResponse, + Awaitable[developer_connect.FetchGitRepositoryLinkCommitListResponse], + ], + ]: + raise NotImplementedError() + + @property + def fetch_git_repository_link_file_blame( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkFileBlameRequest], + Union[ + developer_connect.FetchGitRepositoryLinkFileBlameResponse, + Awaitable[developer_connect.FetchGitRepositoryLinkFileBlameResponse], + ], + ]: + raise NotImplementedError() + + @property + def fetch_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkPullRequestRequest], + Union[developer_connect.PullRequest, Awaitable[developer_connect.PullRequest]], + ]: + raise NotImplementedError() + + @property + def add_git_repository_link_pull_request_comment( + self, + ) -> Callable[ + [developer_connect.AddGitRepositoryLinkPullRequestCommentRequest], + Union[ + developer_connect.PullRequestComment, + Awaitable[developer_connect.PullRequestComment], + ], + ]: + raise NotImplementedError() + + @property + def add_git_repository_link_pull_request_review_comment( + self, + ) -> Callable[ + [developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest], + Union[ + developer_connect.PullRequestReviewComment, + Awaitable[developer_connect.PullRequestReviewComment], + ], + ]: + raise NotImplementedError() + + @property + def modify_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.ModifyGitRepositoryLinkPullRequestRequest], + Union[developer_connect.PullRequest, Awaitable[developer_connect.PullRequest]], + ]: + raise NotImplementedError() + + @property + def fetch_git_repository_link_pull_request_list( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkPullRequestListRequest], + Union[ + developer_connect.FetchGitRepositoryLinkPullRequestListResponse, + Awaitable[developer_connect.FetchGitRepositoryLinkPullRequestListResponse], + ], + ]: + raise NotImplementedError() + @property def list_account_connectors( self, diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/grpc.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/grpc.py index b459a128bbd4..1db26174137e 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/grpc.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/grpc.py @@ -671,6 +671,39 @@ def fetch_read_token( ) return self._stubs["fetch_read_token"] + @property + def open_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.OpenGitRepositoryLinkPullRequestRequest], + developer_connect.PullRequest, + ]: + r"""Return a callable for the open git repository link pull + request method over gRPC. + + Opens a Pull Request in the remote SCM repository + associated with a GitRepositoryLink. + + Returns: + Callable[[~.OpenGitRepositoryLinkPullRequestRequest], + ~.PullRequest]: + 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 "open_git_repository_link_pull_request" not in self._stubs: + self._stubs["open_git_repository_link_pull_request"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/OpenGitRepositoryLinkPullRequest", + request_serializer=developer_connect.OpenGitRepositoryLinkPullRequestRequest.serialize, + response_deserializer=developer_connect.PullRequest.deserialize, + ) + ) + return self._stubs["open_git_repository_link_pull_request"] + @property def fetch_linkable_git_repositories( self, @@ -769,6 +802,299 @@ def fetch_git_refs( ) return self._stubs["fetch_git_refs"] + @property + def diff_git_repository_link_commit( + self, + ) -> Callable[ + [developer_connect.DiffGitRepositoryLinkCommitRequest], + developer_connect.DiffGitRepositoryLinkCommitResponse, + ]: + r"""Return a callable for the diff git repository link + commit method over gRPC. + + Diff commits for a GitRepositoryLink. + + Returns: + Callable[[~.DiffGitRepositoryLinkCommitRequest], + ~.DiffGitRepositoryLinkCommitResponse]: + 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 "diff_git_repository_link_commit" not in self._stubs: + self._stubs["diff_git_repository_link_commit"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/DiffGitRepositoryLinkCommit", + request_serializer=developer_connect.DiffGitRepositoryLinkCommitRequest.serialize, + response_deserializer=developer_connect.DiffGitRepositoryLinkCommitResponse.deserialize, + ) + ) + return self._stubs["diff_git_repository_link_commit"] + + @property + def fetch_git_repository_link_commit( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkCommitRequest], + developer_connect.FetchGitRepositoryLinkCommitResponse, + ]: + r"""Return a callable for the fetch git repository link + commit method over gRPC. + + Fetch Commit details from a Git repository link. + + Returns: + Callable[[~.FetchGitRepositoryLinkCommitRequest], + ~.FetchGitRepositoryLinkCommitResponse]: + 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 "fetch_git_repository_link_commit" not in self._stubs: + self._stubs["fetch_git_repository_link_commit"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkCommit", + request_serializer=developer_connect.FetchGitRepositoryLinkCommitRequest.serialize, + response_deserializer=developer_connect.FetchGitRepositoryLinkCommitResponse.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_commit"] + + @property + def fetch_git_repository_link_commit_list( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkCommitListRequest], + developer_connect.FetchGitRepositoryLinkCommitListResponse, + ]: + r"""Return a callable for the fetch git repository link + commit list method over gRPC. + + Fetch a list of Commits from a Git repository link. + + Returns: + Callable[[~.FetchGitRepositoryLinkCommitListRequest], + ~.FetchGitRepositoryLinkCommitListResponse]: + 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 "fetch_git_repository_link_commit_list" not in self._stubs: + self._stubs["fetch_git_repository_link_commit_list"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkCommitList", + request_serializer=developer_connect.FetchGitRepositoryLinkCommitListRequest.serialize, + response_deserializer=developer_connect.FetchGitRepositoryLinkCommitListResponse.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_commit_list"] + + @property + def fetch_git_repository_link_file_blame( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkFileBlameRequest], + developer_connect.FetchGitRepositoryLinkFileBlameResponse, + ]: + r"""Return a callable for the fetch git repository link file + blame method over gRPC. + + Fetches blame information for a file or line range in + a file. + + Returns: + Callable[[~.FetchGitRepositoryLinkFileBlameRequest], + ~.FetchGitRepositoryLinkFileBlameResponse]: + 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 "fetch_git_repository_link_file_blame" not in self._stubs: + self._stubs["fetch_git_repository_link_file_blame"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkFileBlame", + request_serializer=developer_connect.FetchGitRepositoryLinkFileBlameRequest.serialize, + response_deserializer=developer_connect.FetchGitRepositoryLinkFileBlameResponse.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_file_blame"] + + @property + def fetch_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkPullRequestRequest], + developer_connect.PullRequest, + ]: + r"""Return a callable for the fetch git repository link pull + request method over gRPC. + + Fetch Pull Request details from a Git repository + link. + + Returns: + Callable[[~.FetchGitRepositoryLinkPullRequestRequest], + ~.PullRequest]: + 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 "fetch_git_repository_link_pull_request" not in self._stubs: + self._stubs["fetch_git_repository_link_pull_request"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkPullRequest", + request_serializer=developer_connect.FetchGitRepositoryLinkPullRequestRequest.serialize, + response_deserializer=developer_connect.PullRequest.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_pull_request"] + + @property + def add_git_repository_link_pull_request_comment( + self, + ) -> Callable[ + [developer_connect.AddGitRepositoryLinkPullRequestCommentRequest], + developer_connect.PullRequestComment, + ]: + r"""Return a callable for the add git repository link pull + request comment method over gRPC. + + Add a comment to a Pull Request. + + Returns: + Callable[[~.AddGitRepositoryLinkPullRequestCommentRequest], + ~.PullRequestComment]: + 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_git_repository_link_pull_request_comment" not in self._stubs: + self._stubs["add_git_repository_link_pull_request_comment"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/AddGitRepositoryLinkPullRequestComment", + request_serializer=developer_connect.AddGitRepositoryLinkPullRequestCommentRequest.serialize, + response_deserializer=developer_connect.PullRequestComment.deserialize, + ) + ) + return self._stubs["add_git_repository_link_pull_request_comment"] + + @property + def add_git_repository_link_pull_request_review_comment( + self, + ) -> Callable[ + [developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest], + developer_connect.PullRequestReviewComment, + ]: + r"""Return a callable for the add git repository link pull + request review comment method over gRPC. + + Add a review comment (inline on diff) to a Pull + Request. + + Returns: + Callable[[~.AddGitRepositoryLinkPullRequestReviewCommentRequest], + ~.PullRequestReviewComment]: + 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_git_repository_link_pull_request_review_comment" not in self._stubs: + self._stubs["add_git_repository_link_pull_request_review_comment"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/AddGitRepositoryLinkPullRequestReviewComment", + request_serializer=developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest.serialize, + response_deserializer=developer_connect.PullRequestReviewComment.deserialize, + ) + ) + return self._stubs["add_git_repository_link_pull_request_review_comment"] + + @property + def modify_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.ModifyGitRepositoryLinkPullRequestRequest], + developer_connect.PullRequest, + ]: + r"""Return a callable for the modify git repository link + pull request method over gRPC. + + Modifies a Pull Request in the remote SCM repository + associated with a GitRepositoryLink. + + Returns: + Callable[[~.ModifyGitRepositoryLinkPullRequestRequest], + ~.PullRequest]: + 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 "modify_git_repository_link_pull_request" not in self._stubs: + self._stubs["modify_git_repository_link_pull_request"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/ModifyGitRepositoryLinkPullRequest", + request_serializer=developer_connect.ModifyGitRepositoryLinkPullRequestRequest.serialize, + response_deserializer=developer_connect.PullRequest.deserialize, + ) + ) + return self._stubs["modify_git_repository_link_pull_request"] + + @property + def fetch_git_repository_link_pull_request_list( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkPullRequestListRequest], + developer_connect.FetchGitRepositoryLinkPullRequestListResponse, + ]: + r"""Return a callable for the fetch git repository link pull + request list method over gRPC. + + Fetches a list of Pull Requests from the remote + repository. + + Returns: + Callable[[~.FetchGitRepositoryLinkPullRequestListRequest], + ~.FetchGitRepositoryLinkPullRequestListResponse]: + 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 "fetch_git_repository_link_pull_request_list" not in self._stubs: + self._stubs["fetch_git_repository_link_pull_request_list"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkPullRequestList", + request_serializer=developer_connect.FetchGitRepositoryLinkPullRequestListRequest.serialize, + response_deserializer=developer_connect.FetchGitRepositoryLinkPullRequestListResponse.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_pull_request_list"] + @property def list_account_connectors( self, diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/grpc_asyncio.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/grpc_asyncio.py index c20ed3c28205..67687afff777 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/grpc_asyncio.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/grpc_asyncio.py @@ -682,6 +682,39 @@ def fetch_read_token( ) return self._stubs["fetch_read_token"] + @property + def open_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.OpenGitRepositoryLinkPullRequestRequest], + Awaitable[developer_connect.PullRequest], + ]: + r"""Return a callable for the open git repository link pull + request method over gRPC. + + Opens a Pull Request in the remote SCM repository + associated with a GitRepositoryLink. + + Returns: + Callable[[~.OpenGitRepositoryLinkPullRequestRequest], + Awaitable[~.PullRequest]]: + 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 "open_git_repository_link_pull_request" not in self._stubs: + self._stubs["open_git_repository_link_pull_request"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/OpenGitRepositoryLinkPullRequest", + request_serializer=developer_connect.OpenGitRepositoryLinkPullRequestRequest.serialize, + response_deserializer=developer_connect.PullRequest.deserialize, + ) + ) + return self._stubs["open_git_repository_link_pull_request"] + @property def fetch_linkable_git_repositories( self, @@ -781,6 +814,299 @@ def fetch_git_refs( ) return self._stubs["fetch_git_refs"] + @property + def diff_git_repository_link_commit( + self, + ) -> Callable[ + [developer_connect.DiffGitRepositoryLinkCommitRequest], + Awaitable[developer_connect.DiffGitRepositoryLinkCommitResponse], + ]: + r"""Return a callable for the diff git repository link + commit method over gRPC. + + Diff commits for a GitRepositoryLink. + + Returns: + Callable[[~.DiffGitRepositoryLinkCommitRequest], + Awaitable[~.DiffGitRepositoryLinkCommitResponse]]: + 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 "diff_git_repository_link_commit" not in self._stubs: + self._stubs["diff_git_repository_link_commit"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/DiffGitRepositoryLinkCommit", + request_serializer=developer_connect.DiffGitRepositoryLinkCommitRequest.serialize, + response_deserializer=developer_connect.DiffGitRepositoryLinkCommitResponse.deserialize, + ) + ) + return self._stubs["diff_git_repository_link_commit"] + + @property + def fetch_git_repository_link_commit( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkCommitRequest], + Awaitable[developer_connect.FetchGitRepositoryLinkCommitResponse], + ]: + r"""Return a callable for the fetch git repository link + commit method over gRPC. + + Fetch Commit details from a Git repository link. + + Returns: + Callable[[~.FetchGitRepositoryLinkCommitRequest], + Awaitable[~.FetchGitRepositoryLinkCommitResponse]]: + 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 "fetch_git_repository_link_commit" not in self._stubs: + self._stubs["fetch_git_repository_link_commit"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkCommit", + request_serializer=developer_connect.FetchGitRepositoryLinkCommitRequest.serialize, + response_deserializer=developer_connect.FetchGitRepositoryLinkCommitResponse.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_commit"] + + @property + def fetch_git_repository_link_commit_list( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkCommitListRequest], + Awaitable[developer_connect.FetchGitRepositoryLinkCommitListResponse], + ]: + r"""Return a callable for the fetch git repository link + commit list method over gRPC. + + Fetch a list of Commits from a Git repository link. + + Returns: + Callable[[~.FetchGitRepositoryLinkCommitListRequest], + Awaitable[~.FetchGitRepositoryLinkCommitListResponse]]: + 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 "fetch_git_repository_link_commit_list" not in self._stubs: + self._stubs["fetch_git_repository_link_commit_list"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkCommitList", + request_serializer=developer_connect.FetchGitRepositoryLinkCommitListRequest.serialize, + response_deserializer=developer_connect.FetchGitRepositoryLinkCommitListResponse.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_commit_list"] + + @property + def fetch_git_repository_link_file_blame( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkFileBlameRequest], + Awaitable[developer_connect.FetchGitRepositoryLinkFileBlameResponse], + ]: + r"""Return a callable for the fetch git repository link file + blame method over gRPC. + + Fetches blame information for a file or line range in + a file. + + Returns: + Callable[[~.FetchGitRepositoryLinkFileBlameRequest], + Awaitable[~.FetchGitRepositoryLinkFileBlameResponse]]: + 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 "fetch_git_repository_link_file_blame" not in self._stubs: + self._stubs["fetch_git_repository_link_file_blame"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkFileBlame", + request_serializer=developer_connect.FetchGitRepositoryLinkFileBlameRequest.serialize, + response_deserializer=developer_connect.FetchGitRepositoryLinkFileBlameResponse.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_file_blame"] + + @property + def fetch_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkPullRequestRequest], + Awaitable[developer_connect.PullRequest], + ]: + r"""Return a callable for the fetch git repository link pull + request method over gRPC. + + Fetch Pull Request details from a Git repository + link. + + Returns: + Callable[[~.FetchGitRepositoryLinkPullRequestRequest], + Awaitable[~.PullRequest]]: + 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 "fetch_git_repository_link_pull_request" not in self._stubs: + self._stubs["fetch_git_repository_link_pull_request"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkPullRequest", + request_serializer=developer_connect.FetchGitRepositoryLinkPullRequestRequest.serialize, + response_deserializer=developer_connect.PullRequest.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_pull_request"] + + @property + def add_git_repository_link_pull_request_comment( + self, + ) -> Callable[ + [developer_connect.AddGitRepositoryLinkPullRequestCommentRequest], + Awaitable[developer_connect.PullRequestComment], + ]: + r"""Return a callable for the add git repository link pull + request comment method over gRPC. + + Add a comment to a Pull Request. + + Returns: + Callable[[~.AddGitRepositoryLinkPullRequestCommentRequest], + Awaitable[~.PullRequestComment]]: + 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_git_repository_link_pull_request_comment" not in self._stubs: + self._stubs["add_git_repository_link_pull_request_comment"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/AddGitRepositoryLinkPullRequestComment", + request_serializer=developer_connect.AddGitRepositoryLinkPullRequestCommentRequest.serialize, + response_deserializer=developer_connect.PullRequestComment.deserialize, + ) + ) + return self._stubs["add_git_repository_link_pull_request_comment"] + + @property + def add_git_repository_link_pull_request_review_comment( + self, + ) -> Callable[ + [developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest], + Awaitable[developer_connect.PullRequestReviewComment], + ]: + r"""Return a callable for the add git repository link pull + request review comment method over gRPC. + + Add a review comment (inline on diff) to a Pull + Request. + + Returns: + Callable[[~.AddGitRepositoryLinkPullRequestReviewCommentRequest], + Awaitable[~.PullRequestReviewComment]]: + 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_git_repository_link_pull_request_review_comment" not in self._stubs: + self._stubs["add_git_repository_link_pull_request_review_comment"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/AddGitRepositoryLinkPullRequestReviewComment", + request_serializer=developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest.serialize, + response_deserializer=developer_connect.PullRequestReviewComment.deserialize, + ) + ) + return self._stubs["add_git_repository_link_pull_request_review_comment"] + + @property + def modify_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.ModifyGitRepositoryLinkPullRequestRequest], + Awaitable[developer_connect.PullRequest], + ]: + r"""Return a callable for the modify git repository link + pull request method over gRPC. + + Modifies a Pull Request in the remote SCM repository + associated with a GitRepositoryLink. + + Returns: + Callable[[~.ModifyGitRepositoryLinkPullRequestRequest], + Awaitable[~.PullRequest]]: + 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 "modify_git_repository_link_pull_request" not in self._stubs: + self._stubs["modify_git_repository_link_pull_request"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/ModifyGitRepositoryLinkPullRequest", + request_serializer=developer_connect.ModifyGitRepositoryLinkPullRequestRequest.serialize, + response_deserializer=developer_connect.PullRequest.deserialize, + ) + ) + return self._stubs["modify_git_repository_link_pull_request"] + + @property + def fetch_git_repository_link_pull_request_list( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkPullRequestListRequest], + Awaitable[developer_connect.FetchGitRepositoryLinkPullRequestListResponse], + ]: + r"""Return a callable for the fetch git repository link pull + request list method over gRPC. + + Fetches a list of Pull Requests from the remote + repository. + + Returns: + Callable[[~.FetchGitRepositoryLinkPullRequestListRequest], + Awaitable[~.FetchGitRepositoryLinkPullRequestListResponse]]: + 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 "fetch_git_repository_link_pull_request_list" not in self._stubs: + self._stubs["fetch_git_repository_link_pull_request_list"] = ( + self._logged_channel.unary_unary( + "/google.cloud.developerconnect.v1.DeveloperConnect/FetchGitRepositoryLinkPullRequestList", + request_serializer=developer_connect.FetchGitRepositoryLinkPullRequestListRequest.serialize, + response_deserializer=developer_connect.FetchGitRepositoryLinkPullRequestListResponse.deserialize, + ) + ) + return self._stubs["fetch_git_repository_link_pull_request_list"] + @property def list_account_connectors( self, @@ -1277,6 +1603,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.open_git_repository_link_pull_request: self._wrap_method( + self.open_git_repository_link_pull_request, + default_timeout=None, + client_info=client_info, + ), self.fetch_linkable_git_repositories: self._wrap_method( self.fetch_linkable_git_repositories, default_retry=retries.AsyncRetry( @@ -1310,6 +1641,51 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.diff_git_repository_link_commit: self._wrap_method( + self.diff_git_repository_link_commit, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_commit: self._wrap_method( + self.fetch_git_repository_link_commit, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_commit_list: self._wrap_method( + self.fetch_git_repository_link_commit_list, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_file_blame: self._wrap_method( + self.fetch_git_repository_link_file_blame, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_pull_request: self._wrap_method( + self.fetch_git_repository_link_pull_request, + default_timeout=None, + client_info=client_info, + ), + self.add_git_repository_link_pull_request_comment: self._wrap_method( + self.add_git_repository_link_pull_request_comment, + default_timeout=None, + client_info=client_info, + ), + self.add_git_repository_link_pull_request_review_comment: self._wrap_method( + self.add_git_repository_link_pull_request_review_comment, + default_timeout=None, + client_info=client_info, + ), + self.modify_git_repository_link_pull_request: self._wrap_method( + self.modify_git_repository_link_pull_request, + default_timeout=None, + client_info=client_info, + ), + self.fetch_git_repository_link_pull_request_list: self._wrap_method( + self.fetch_git_repository_link_pull_request_list, + default_timeout=None, + client_info=client_info, + ), self.list_account_connectors: self._wrap_method( self.list_account_connectors, default_timeout=None, diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/rest.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/rest.py index 79e0316d2d06..0dbd1d80e3e6 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/rest.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/rest.py @@ -74,6 +74,22 @@ class DeveloperConnectRestInterceptor: .. code-block:: python class MyCustomDeveloperConnectInterceptor(DeveloperConnectRestInterceptor): + def pre_add_git_repository_link_pull_request_comment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_git_repository_link_pull_request_comment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_add_git_repository_link_pull_request_review_comment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_git_repository_link_pull_request_review_comment(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_account_connector(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -138,6 +154,14 @@ def post_delete_user(self, response): logging.log(f"Received response: {response}") return response + def pre_diff_git_repository_link_commit(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_diff_git_repository_link_commit(self, response): + logging.log(f"Received response: {response}") + return response + def pre_fetch_access_token(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -162,6 +186,46 @@ def post_fetch_git_refs(self, response): logging.log(f"Received response: {response}") return response + def pre_fetch_git_repository_link_commit(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_git_repository_link_commit(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_git_repository_link_commit_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_git_repository_link_commit_list(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_git_repository_link_file_blame(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_git_repository_link_file_blame(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_git_repository_link_pull_request(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_git_repository_link_pull_request(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_fetch_git_repository_link_pull_request_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_fetch_git_repository_link_pull_request_list(self, response): + logging.log(f"Received response: {response}") + return response + def pre_fetch_linkable_git_repositories(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -258,6 +322,22 @@ def post_list_users(self, response): logging.log(f"Received response: {response}") return response + def pre_modify_git_repository_link_pull_request(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_modify_git_repository_link_pull_request(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_open_git_repository_link_pull_request(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_open_git_repository_link_pull_request(self, response): + logging.log(f"Received response: {response}") + return response + def pre_start_o_auth(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -288,6 +368,109 @@ def post_update_connection(self, response): """ + def pre_add_git_repository_link_pull_request_comment( + self, + request: developer_connect.AddGitRepositoryLinkPullRequestCommentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.AddGitRepositoryLinkPullRequestCommentRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for add_git_repository_link_pull_request_comment + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_add_git_repository_link_pull_request_comment( + self, response: developer_connect.PullRequestComment + ) -> developer_connect.PullRequestComment: + """Post-rpc interceptor for add_git_repository_link_pull_request_comment + + DEPRECATED. Please use the `post_add_git_repository_link_pull_request_comment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_add_git_repository_link_pull_request_comment` interceptor runs + before the `post_add_git_repository_link_pull_request_comment_with_metadata` interceptor. + """ + return response + + def post_add_git_repository_link_pull_request_comment_with_metadata( + self, + response: developer_connect.PullRequestComment, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.PullRequestComment, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for add_git_repository_link_pull_request_comment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_add_git_repository_link_pull_request_comment_with_metadata` + interceptor in new development instead of the `post_add_git_repository_link_pull_request_comment` interceptor. + When both interceptors are used, this `post_add_git_repository_link_pull_request_comment_with_metadata` interceptor runs after the + `post_add_git_repository_link_pull_request_comment` interceptor. The (possibly modified) response returned by + `post_add_git_repository_link_pull_request_comment` will be passed to + `post_add_git_repository_link_pull_request_comment_with_metadata`. + """ + return response, metadata + + def pre_add_git_repository_link_pull_request_review_comment( + self, + request: developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for add_git_repository_link_pull_request_review_comment + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_add_git_repository_link_pull_request_review_comment( + self, response: developer_connect.PullRequestReviewComment + ) -> developer_connect.PullRequestReviewComment: + """Post-rpc interceptor for add_git_repository_link_pull_request_review_comment + + DEPRECATED. Please use the `post_add_git_repository_link_pull_request_review_comment_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_add_git_repository_link_pull_request_review_comment` interceptor runs + before the `post_add_git_repository_link_pull_request_review_comment_with_metadata` interceptor. + """ + return response + + def post_add_git_repository_link_pull_request_review_comment_with_metadata( + self, + response: developer_connect.PullRequestReviewComment, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.PullRequestReviewComment, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for add_git_repository_link_pull_request_review_comment + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_add_git_repository_link_pull_request_review_comment_with_metadata` + interceptor in new development instead of the `post_add_git_repository_link_pull_request_review_comment` interceptor. + When both interceptors are used, this `post_add_git_repository_link_pull_request_review_comment_with_metadata` interceptor runs after the + `post_add_git_repository_link_pull_request_review_comment` interceptor. The (possibly modified) response returned by + `post_add_git_repository_link_pull_request_review_comment` will be passed to + `post_add_git_repository_link_pull_request_review_comment_with_metadata`. + """ + return response, metadata + def pre_create_account_connector( self, request: developer_connect.CreateAccountConnectorRequest, @@ -678,6 +861,58 @@ def post_delete_user_with_metadata( """ return response, metadata + def pre_diff_git_repository_link_commit( + self, + request: developer_connect.DiffGitRepositoryLinkCommitRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.DiffGitRepositoryLinkCommitRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for diff_git_repository_link_commit + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_diff_git_repository_link_commit( + self, response: developer_connect.DiffGitRepositoryLinkCommitResponse + ) -> developer_connect.DiffGitRepositoryLinkCommitResponse: + """Post-rpc interceptor for diff_git_repository_link_commit + + DEPRECATED. Please use the `post_diff_git_repository_link_commit_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_diff_git_repository_link_commit` interceptor runs + before the `post_diff_git_repository_link_commit_with_metadata` interceptor. + """ + return response + + def post_diff_git_repository_link_commit_with_metadata( + self, + response: developer_connect.DiffGitRepositoryLinkCommitResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.DiffGitRepositoryLinkCommitResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for diff_git_repository_link_commit + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_diff_git_repository_link_commit_with_metadata` + interceptor in new development instead of the `post_diff_git_repository_link_commit` interceptor. + When both interceptors are used, this `post_diff_git_repository_link_commit_with_metadata` interceptor runs after the + `post_diff_git_repository_link_commit` interceptor. The (possibly modified) response returned by + `post_diff_git_repository_link_commit` will be passed to + `post_diff_git_repository_link_commit_with_metadata`. + """ + return response, metadata + def pre_fetch_access_token( self, request: developer_connect.FetchAccessTokenRequest, @@ -832,251 +1067,508 @@ def post_fetch_git_refs_with_metadata( """ return response, metadata - def pre_fetch_linkable_git_repositories( + def pre_fetch_git_repository_link_commit( self, - request: developer_connect.FetchLinkableGitRepositoriesRequest, + request: developer_connect.FetchGitRepositoryLinkCommitRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.FetchLinkableGitRepositoriesRequest, + developer_connect.FetchGitRepositoryLinkCommitRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for fetch_linkable_git_repositories + """Pre-rpc interceptor for fetch_git_repository_link_commit Override in a subclass to manipulate the request or metadata before they are sent to the DeveloperConnect server. """ return request, metadata - def post_fetch_linkable_git_repositories( - self, response: developer_connect.FetchLinkableGitRepositoriesResponse - ) -> developer_connect.FetchLinkableGitRepositoriesResponse: - """Post-rpc interceptor for fetch_linkable_git_repositories + def post_fetch_git_repository_link_commit( + self, response: developer_connect.FetchGitRepositoryLinkCommitResponse + ) -> developer_connect.FetchGitRepositoryLinkCommitResponse: + """Post-rpc interceptor for fetch_git_repository_link_commit - DEPRECATED. Please use the `post_fetch_linkable_git_repositories_with_metadata` + DEPRECATED. Please use the `post_fetch_git_repository_link_commit_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the DeveloperConnect server but before - it is returned to user code. This `post_fetch_linkable_git_repositories` interceptor runs - before the `post_fetch_linkable_git_repositories_with_metadata` interceptor. + it is returned to user code. This `post_fetch_git_repository_link_commit` interceptor runs + before the `post_fetch_git_repository_link_commit_with_metadata` interceptor. """ return response - def post_fetch_linkable_git_repositories_with_metadata( + def post_fetch_git_repository_link_commit_with_metadata( self, - response: developer_connect.FetchLinkableGitRepositoriesResponse, + response: developer_connect.FetchGitRepositoryLinkCommitResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.FetchLinkableGitRepositoriesResponse, + developer_connect.FetchGitRepositoryLinkCommitResponse, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for fetch_linkable_git_repositories + """Post-rpc interceptor for fetch_git_repository_link_commit Override in a subclass to read or manipulate the response or metadata after it is returned by the DeveloperConnect server but before it is returned to user code. - We recommend only using this `post_fetch_linkable_git_repositories_with_metadata` - interceptor in new development instead of the `post_fetch_linkable_git_repositories` interceptor. - When both interceptors are used, this `post_fetch_linkable_git_repositories_with_metadata` interceptor runs after the - `post_fetch_linkable_git_repositories` interceptor. The (possibly modified) response returned by - `post_fetch_linkable_git_repositories` will be passed to - `post_fetch_linkable_git_repositories_with_metadata`. + We recommend only using this `post_fetch_git_repository_link_commit_with_metadata` + interceptor in new development instead of the `post_fetch_git_repository_link_commit` interceptor. + When both interceptors are used, this `post_fetch_git_repository_link_commit_with_metadata` interceptor runs after the + `post_fetch_git_repository_link_commit` interceptor. The (possibly modified) response returned by + `post_fetch_git_repository_link_commit` will be passed to + `post_fetch_git_repository_link_commit_with_metadata`. """ return response, metadata - def pre_fetch_read_token( + def pre_fetch_git_repository_link_commit_list( self, - request: developer_connect.FetchReadTokenRequest, + request: developer_connect.FetchGitRepositoryLinkCommitListRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.FetchReadTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] + developer_connect.FetchGitRepositoryLinkCommitListRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for fetch_read_token + """Pre-rpc interceptor for fetch_git_repository_link_commit_list Override in a subclass to manipulate the request or metadata before they are sent to the DeveloperConnect server. """ return request, metadata - def post_fetch_read_token( - self, response: developer_connect.FetchReadTokenResponse - ) -> developer_connect.FetchReadTokenResponse: - """Post-rpc interceptor for fetch_read_token + def post_fetch_git_repository_link_commit_list( + self, response: developer_connect.FetchGitRepositoryLinkCommitListResponse + ) -> developer_connect.FetchGitRepositoryLinkCommitListResponse: + """Post-rpc interceptor for fetch_git_repository_link_commit_list - DEPRECATED. Please use the `post_fetch_read_token_with_metadata` + DEPRECATED. Please use the `post_fetch_git_repository_link_commit_list_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the DeveloperConnect server but before - it is returned to user code. This `post_fetch_read_token` interceptor runs - before the `post_fetch_read_token_with_metadata` interceptor. + it is returned to user code. This `post_fetch_git_repository_link_commit_list` interceptor runs + before the `post_fetch_git_repository_link_commit_list_with_metadata` interceptor. """ return response - def post_fetch_read_token_with_metadata( + def post_fetch_git_repository_link_commit_list_with_metadata( self, - response: developer_connect.FetchReadTokenResponse, + response: developer_connect.FetchGitRepositoryLinkCommitListResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.FetchReadTokenResponse, + developer_connect.FetchGitRepositoryLinkCommitListResponse, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for fetch_read_token + """Post-rpc interceptor for fetch_git_repository_link_commit_list Override in a subclass to read or manipulate the response or metadata after it is returned by the DeveloperConnect server but before it is returned to user code. - We recommend only using this `post_fetch_read_token_with_metadata` - interceptor in new development instead of the `post_fetch_read_token` interceptor. - When both interceptors are used, this `post_fetch_read_token_with_metadata` interceptor runs after the - `post_fetch_read_token` interceptor. The (possibly modified) response returned by - `post_fetch_read_token` will be passed to - `post_fetch_read_token_with_metadata`. + We recommend only using this `post_fetch_git_repository_link_commit_list_with_metadata` + interceptor in new development instead of the `post_fetch_git_repository_link_commit_list` interceptor. + When both interceptors are used, this `post_fetch_git_repository_link_commit_list_with_metadata` interceptor runs after the + `post_fetch_git_repository_link_commit_list` interceptor. The (possibly modified) response returned by + `post_fetch_git_repository_link_commit_list` will be passed to + `post_fetch_git_repository_link_commit_list_with_metadata`. """ return response, metadata - def pre_fetch_read_write_token( + def pre_fetch_git_repository_link_file_blame( self, - request: developer_connect.FetchReadWriteTokenRequest, + request: developer_connect.FetchGitRepositoryLinkFileBlameRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.FetchReadWriteTokenRequest, + developer_connect.FetchGitRepositoryLinkFileBlameRequest, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for fetch_read_write_token + """Pre-rpc interceptor for fetch_git_repository_link_file_blame Override in a subclass to manipulate the request or metadata before they are sent to the DeveloperConnect server. """ return request, metadata - def post_fetch_read_write_token( - self, response: developer_connect.FetchReadWriteTokenResponse - ) -> developer_connect.FetchReadWriteTokenResponse: - """Post-rpc interceptor for fetch_read_write_token + def post_fetch_git_repository_link_file_blame( + self, response: developer_connect.FetchGitRepositoryLinkFileBlameResponse + ) -> developer_connect.FetchGitRepositoryLinkFileBlameResponse: + """Post-rpc interceptor for fetch_git_repository_link_file_blame - DEPRECATED. Please use the `post_fetch_read_write_token_with_metadata` + DEPRECATED. Please use the `post_fetch_git_repository_link_file_blame_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the DeveloperConnect server but before - it is returned to user code. This `post_fetch_read_write_token` interceptor runs - before the `post_fetch_read_write_token_with_metadata` interceptor. + it is returned to user code. This `post_fetch_git_repository_link_file_blame` interceptor runs + before the `post_fetch_git_repository_link_file_blame_with_metadata` interceptor. """ return response - def post_fetch_read_write_token_with_metadata( + def post_fetch_git_repository_link_file_blame_with_metadata( self, - response: developer_connect.FetchReadWriteTokenResponse, + response: developer_connect.FetchGitRepositoryLinkFileBlameResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.FetchReadWriteTokenResponse, + developer_connect.FetchGitRepositoryLinkFileBlameResponse, Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for fetch_read_write_token + """Post-rpc interceptor for fetch_git_repository_link_file_blame Override in a subclass to read or manipulate the response or metadata after it is returned by the DeveloperConnect server but before it is returned to user code. - We recommend only using this `post_fetch_read_write_token_with_metadata` - interceptor in new development instead of the `post_fetch_read_write_token` interceptor. - When both interceptors are used, this `post_fetch_read_write_token_with_metadata` interceptor runs after the - `post_fetch_read_write_token` interceptor. The (possibly modified) response returned by - `post_fetch_read_write_token` will be passed to - `post_fetch_read_write_token_with_metadata`. + We recommend only using this `post_fetch_git_repository_link_file_blame_with_metadata` + interceptor in new development instead of the `post_fetch_git_repository_link_file_blame` interceptor. + When both interceptors are used, this `post_fetch_git_repository_link_file_blame_with_metadata` interceptor runs after the + `post_fetch_git_repository_link_file_blame` interceptor. The (possibly modified) response returned by + `post_fetch_git_repository_link_file_blame` will be passed to + `post_fetch_git_repository_link_file_blame_with_metadata`. """ return response, metadata - def pre_fetch_self( + def pre_fetch_git_repository_link_pull_request( self, - request: developer_connect.FetchSelfRequest, + request: developer_connect.FetchGitRepositoryLinkPullRequestRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.FetchSelfRequest, Sequence[Tuple[str, Union[str, bytes]]] + developer_connect.FetchGitRepositoryLinkPullRequestRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for fetch_self + """Pre-rpc interceptor for fetch_git_repository_link_pull_request Override in a subclass to manipulate the request or metadata before they are sent to the DeveloperConnect server. """ return request, metadata - def post_fetch_self( - self, response: developer_connect.User - ) -> developer_connect.User: - """Post-rpc interceptor for fetch_self + def post_fetch_git_repository_link_pull_request( + self, response: developer_connect.PullRequest + ) -> developer_connect.PullRequest: + """Post-rpc interceptor for fetch_git_repository_link_pull_request - DEPRECATED. Please use the `post_fetch_self_with_metadata` + DEPRECATED. Please use the `post_fetch_git_repository_link_pull_request_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the DeveloperConnect server but before - it is returned to user code. This `post_fetch_self` interceptor runs - before the `post_fetch_self_with_metadata` interceptor. + it is returned to user code. This `post_fetch_git_repository_link_pull_request` interceptor runs + before the `post_fetch_git_repository_link_pull_request_with_metadata` interceptor. """ return response - def post_fetch_self_with_metadata( + def post_fetch_git_repository_link_pull_request_with_metadata( self, - response: developer_connect.User, + response: developer_connect.PullRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[developer_connect.User, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for fetch_self + ) -> Tuple[developer_connect.PullRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for fetch_git_repository_link_pull_request Override in a subclass to read or manipulate the response or metadata after it is returned by the DeveloperConnect server but before it is returned to user code. - We recommend only using this `post_fetch_self_with_metadata` - interceptor in new development instead of the `post_fetch_self` interceptor. - When both interceptors are used, this `post_fetch_self_with_metadata` interceptor runs after the - `post_fetch_self` interceptor. The (possibly modified) response returned by - `post_fetch_self` will be passed to - `post_fetch_self_with_metadata`. + We recommend only using this `post_fetch_git_repository_link_pull_request_with_metadata` + interceptor in new development instead of the `post_fetch_git_repository_link_pull_request` interceptor. + When both interceptors are used, this `post_fetch_git_repository_link_pull_request_with_metadata` interceptor runs after the + `post_fetch_git_repository_link_pull_request` interceptor. The (possibly modified) response returned by + `post_fetch_git_repository_link_pull_request` will be passed to + `post_fetch_git_repository_link_pull_request_with_metadata`. """ return response, metadata - def pre_finish_o_auth( + def pre_fetch_git_repository_link_pull_request_list( self, - request: developer_connect.FinishOAuthRequest, + request: developer_connect.FetchGitRepositoryLinkPullRequestListRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.FinishOAuthRequest, Sequence[Tuple[str, Union[str, bytes]]] + developer_connect.FetchGitRepositoryLinkPullRequestListRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for finish_o_auth + """Pre-rpc interceptor for fetch_git_repository_link_pull_request_list Override in a subclass to manipulate the request or metadata before they are sent to the DeveloperConnect server. """ return request, metadata - def post_finish_o_auth( - self, response: developer_connect.FinishOAuthResponse - ) -> developer_connect.FinishOAuthResponse: - """Post-rpc interceptor for finish_o_auth + def post_fetch_git_repository_link_pull_request_list( + self, response: developer_connect.FetchGitRepositoryLinkPullRequestListResponse + ) -> developer_connect.FetchGitRepositoryLinkPullRequestListResponse: + """Post-rpc interceptor for fetch_git_repository_link_pull_request_list - DEPRECATED. Please use the `post_finish_o_auth_with_metadata` + DEPRECATED. Please use the `post_fetch_git_repository_link_pull_request_list_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the DeveloperConnect server but before - it is returned to user code. This `post_finish_o_auth` interceptor runs - before the `post_finish_o_auth_with_metadata` interceptor. + it is returned to user code. This `post_fetch_git_repository_link_pull_request_list` interceptor runs + before the `post_fetch_git_repository_link_pull_request_list_with_metadata` interceptor. """ return response - def post_finish_o_auth_with_metadata( + def post_fetch_git_repository_link_pull_request_list_with_metadata( self, - response: developer_connect.FinishOAuthResponse, + response: developer_connect.FetchGitRepositoryLinkPullRequestListResponse, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.FinishOAuthResponse, Sequence[Tuple[str, Union[str, bytes]]] + developer_connect.FetchGitRepositoryLinkPullRequestListResponse, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Post-rpc interceptor for finish_o_auth + """Post-rpc interceptor for fetch_git_repository_link_pull_request_list Override in a subclass to read or manipulate the response or metadata after it is returned by the DeveloperConnect server but before it is returned to user code. - We recommend only using this `post_finish_o_auth_with_metadata` + We recommend only using this `post_fetch_git_repository_link_pull_request_list_with_metadata` + interceptor in new development instead of the `post_fetch_git_repository_link_pull_request_list` interceptor. + When both interceptors are used, this `post_fetch_git_repository_link_pull_request_list_with_metadata` interceptor runs after the + `post_fetch_git_repository_link_pull_request_list` interceptor. The (possibly modified) response returned by + `post_fetch_git_repository_link_pull_request_list` will be passed to + `post_fetch_git_repository_link_pull_request_list_with_metadata`. + """ + return response, metadata + + def pre_fetch_linkable_git_repositories( + self, + request: developer_connect.FetchLinkableGitRepositoriesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.FetchLinkableGitRepositoriesRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_linkable_git_repositories + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_fetch_linkable_git_repositories( + self, response: developer_connect.FetchLinkableGitRepositoriesResponse + ) -> developer_connect.FetchLinkableGitRepositoriesResponse: + """Post-rpc interceptor for fetch_linkable_git_repositories + + DEPRECATED. Please use the `post_fetch_linkable_git_repositories_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_fetch_linkable_git_repositories` interceptor runs + before the `post_fetch_linkable_git_repositories_with_metadata` interceptor. + """ + return response + + def post_fetch_linkable_git_repositories_with_metadata( + self, + response: developer_connect.FetchLinkableGitRepositoriesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.FetchLinkableGitRepositoriesResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_linkable_git_repositories + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_fetch_linkable_git_repositories_with_metadata` + interceptor in new development instead of the `post_fetch_linkable_git_repositories` interceptor. + When both interceptors are used, this `post_fetch_linkable_git_repositories_with_metadata` interceptor runs after the + `post_fetch_linkable_git_repositories` interceptor. The (possibly modified) response returned by + `post_fetch_linkable_git_repositories` will be passed to + `post_fetch_linkable_git_repositories_with_metadata`. + """ + return response, metadata + + def pre_fetch_read_token( + self, + request: developer_connect.FetchReadTokenRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.FetchReadTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for fetch_read_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_fetch_read_token( + self, response: developer_connect.FetchReadTokenResponse + ) -> developer_connect.FetchReadTokenResponse: + """Post-rpc interceptor for fetch_read_token + + DEPRECATED. Please use the `post_fetch_read_token_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_fetch_read_token` interceptor runs + before the `post_fetch_read_token_with_metadata` interceptor. + """ + return response + + def post_fetch_read_token_with_metadata( + self, + response: developer_connect.FetchReadTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.FetchReadTokenResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_read_token + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_fetch_read_token_with_metadata` + interceptor in new development instead of the `post_fetch_read_token` interceptor. + When both interceptors are used, this `post_fetch_read_token_with_metadata` interceptor runs after the + `post_fetch_read_token` interceptor. The (possibly modified) response returned by + `post_fetch_read_token` will be passed to + `post_fetch_read_token_with_metadata`. + """ + return response, metadata + + def pre_fetch_read_write_token( + self, + request: developer_connect.FetchReadWriteTokenRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.FetchReadWriteTokenRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for fetch_read_write_token + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_fetch_read_write_token( + self, response: developer_connect.FetchReadWriteTokenResponse + ) -> developer_connect.FetchReadWriteTokenResponse: + """Post-rpc interceptor for fetch_read_write_token + + DEPRECATED. Please use the `post_fetch_read_write_token_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_fetch_read_write_token` interceptor runs + before the `post_fetch_read_write_token_with_metadata` interceptor. + """ + return response + + def post_fetch_read_write_token_with_metadata( + self, + response: developer_connect.FetchReadWriteTokenResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.FetchReadWriteTokenResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for fetch_read_write_token + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_fetch_read_write_token_with_metadata` + interceptor in new development instead of the `post_fetch_read_write_token` interceptor. + When both interceptors are used, this `post_fetch_read_write_token_with_metadata` interceptor runs after the + `post_fetch_read_write_token` interceptor. The (possibly modified) response returned by + `post_fetch_read_write_token` will be passed to + `post_fetch_read_write_token_with_metadata`. + """ + return response, metadata + + def pre_fetch_self( + self, + request: developer_connect.FetchSelfRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.FetchSelfRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for fetch_self + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_fetch_self( + self, response: developer_connect.User + ) -> developer_connect.User: + """Post-rpc interceptor for fetch_self + + DEPRECATED. Please use the `post_fetch_self_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_fetch_self` interceptor runs + before the `post_fetch_self_with_metadata` interceptor. + """ + return response + + def post_fetch_self_with_metadata( + self, + response: developer_connect.User, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[developer_connect.User, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for fetch_self + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_fetch_self_with_metadata` + interceptor in new development instead of the `post_fetch_self` interceptor. + When both interceptors are used, this `post_fetch_self_with_metadata` interceptor runs after the + `post_fetch_self` interceptor. The (possibly modified) response returned by + `post_fetch_self` will be passed to + `post_fetch_self_with_metadata`. + """ + return response, metadata + + def pre_finish_o_auth( + self, + request: developer_connect.FinishOAuthRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.FinishOAuthRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for finish_o_auth + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_finish_o_auth( + self, response: developer_connect.FinishOAuthResponse + ) -> developer_connect.FinishOAuthResponse: + """Post-rpc interceptor for finish_o_auth + + DEPRECATED. Please use the `post_finish_o_auth_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_finish_o_auth` interceptor runs + before the `post_finish_o_auth_with_metadata` interceptor. + """ + return response + + def post_finish_o_auth_with_metadata( + self, + response: developer_connect.FinishOAuthResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.FinishOAuthResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for finish_o_auth + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_finish_o_auth_with_metadata` interceptor in new development instead of the `post_finish_o_auth` interceptor. When both interceptors are used, this `post_finish_o_auth_with_metadata` interceptor runs after the `post_finish_o_auth` interceptor. The (possibly modified) response returned by @@ -1441,23 +1933,121 @@ def post_list_users_with_metadata( """ return response, metadata - def pre_start_o_auth( + def pre_modify_git_repository_link_pull_request( self, - request: developer_connect.StartOAuthRequest, + request: developer_connect.ModifyGitRepositoryLinkPullRequestRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - developer_connect.StartOAuthRequest, Sequence[Tuple[str, Union[str, bytes]]] + developer_connect.ModifyGitRepositoryLinkPullRequestRequest, + Sequence[Tuple[str, Union[str, bytes]]], ]: - """Pre-rpc interceptor for start_o_auth + """Pre-rpc interceptor for modify_git_repository_link_pull_request Override in a subclass to manipulate the request or metadata before they are sent to the DeveloperConnect server. """ return request, metadata - def post_start_o_auth( - self, response: developer_connect.StartOAuthResponse - ) -> developer_connect.StartOAuthResponse: + def post_modify_git_repository_link_pull_request( + self, response: developer_connect.PullRequest + ) -> developer_connect.PullRequest: + """Post-rpc interceptor for modify_git_repository_link_pull_request + + DEPRECATED. Please use the `post_modify_git_repository_link_pull_request_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_modify_git_repository_link_pull_request` interceptor runs + before the `post_modify_git_repository_link_pull_request_with_metadata` interceptor. + """ + return response + + def post_modify_git_repository_link_pull_request_with_metadata( + self, + response: developer_connect.PullRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[developer_connect.PullRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for modify_git_repository_link_pull_request + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_modify_git_repository_link_pull_request_with_metadata` + interceptor in new development instead of the `post_modify_git_repository_link_pull_request` interceptor. + When both interceptors are used, this `post_modify_git_repository_link_pull_request_with_metadata` interceptor runs after the + `post_modify_git_repository_link_pull_request` interceptor. The (possibly modified) response returned by + `post_modify_git_repository_link_pull_request` will be passed to + `post_modify_git_repository_link_pull_request_with_metadata`. + """ + return response, metadata + + def pre_open_git_repository_link_pull_request( + self, + request: developer_connect.OpenGitRepositoryLinkPullRequestRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.OpenGitRepositoryLinkPullRequestRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for open_git_repository_link_pull_request + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_open_git_repository_link_pull_request( + self, response: developer_connect.PullRequest + ) -> developer_connect.PullRequest: + """Post-rpc interceptor for open_git_repository_link_pull_request + + DEPRECATED. Please use the `post_open_git_repository_link_pull_request_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the DeveloperConnect server but before + it is returned to user code. This `post_open_git_repository_link_pull_request` interceptor runs + before the `post_open_git_repository_link_pull_request_with_metadata` interceptor. + """ + return response + + def post_open_git_repository_link_pull_request_with_metadata( + self, + response: developer_connect.PullRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[developer_connect.PullRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for open_git_repository_link_pull_request + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the DeveloperConnect server but before it is returned to user code. + + We recommend only using this `post_open_git_repository_link_pull_request_with_metadata` + interceptor in new development instead of the `post_open_git_repository_link_pull_request` interceptor. + When both interceptors are used, this `post_open_git_repository_link_pull_request_with_metadata` interceptor runs after the + `post_open_git_repository_link_pull_request` interceptor. The (possibly modified) response returned by + `post_open_git_repository_link_pull_request` will be passed to + `post_open_git_repository_link_pull_request_with_metadata`. + """ + return response, metadata + + def pre_start_o_auth( + self, + request: developer_connect.StartOAuthRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + developer_connect.StartOAuthRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for start_o_auth + + Override in a subclass to manipulate the request or metadata + before they are sent to the DeveloperConnect server. + """ + return request, metadata + + def post_start_o_auth( + self, response: developer_connect.StartOAuthResponse + ) -> developer_connect.StartOAuthResponse: """Post-rpc interceptor for start_o_auth DEPRECATED. Please use the `post_start_o_auth_with_metadata` @@ -1883,12 +2473,1530 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient: # Return the client from cache. return self._operations_client - class _CreateAccountConnector( - _BaseDeveloperConnectRestTransport._BaseCreateAccountConnector, + class _AddGitRepositoryLinkPullRequestComment( + _BaseDeveloperConnectRestTransport._BaseAddGitRepositoryLinkPullRequestComment, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.CreateAccountConnector") + return hash( + "DeveloperConnectRestTransport.AddGitRepositoryLinkPullRequestComment" + ) + + @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: developer_connect.AddGitRepositoryLinkPullRequestCommentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.PullRequestComment: + r"""Call the add git repository link + pull request comment method over HTTP. + + Args: + request (~.developer_connect.AddGitRepositoryLinkPullRequestCommentRequest): + The request object. Request message for + AddGitRepositoryLinkPullRequestComment. + 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: + ~.developer_connect.PullRequestComment: + Message representing a SCM Pull + Request Comment. + + """ + + http_options = _BaseDeveloperConnectRestTransport._BaseAddGitRepositoryLinkPullRequestComment._get_http_options() + request, metadata = ( + self._interceptor.pre_add_git_repository_link_pull_request_comment( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseAddGitRepositoryLinkPullRequestComment, + "_BaseAddGitRepositoryLinkPullRequestComment__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.AddGitRepositoryLinkPullRequestComment", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "AddGitRepositoryLinkPullRequestComment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DeveloperConnectRestTransport._AddGitRepositoryLinkPullRequestComment._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 = developer_connect.PullRequestComment() + pb_resp = developer_connect.PullRequestComment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_add_git_repository_link_pull_request_comment( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_add_git_repository_link_pull_request_comment_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = developer_connect.PullRequestComment.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.developerconnect_v1.DeveloperConnectClient.add_git_repository_link_pull_request_comment", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "AddGitRepositoryLinkPullRequestComment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _AddGitRepositoryLinkPullRequestReviewComment( + _BaseDeveloperConnectRestTransport._BaseAddGitRepositoryLinkPullRequestReviewComment, + DeveloperConnectRestStub, + ): + def __hash__(self): + return hash( + "DeveloperConnectRestTransport.AddGitRepositoryLinkPullRequestReviewComment" + ) + + @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: developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.PullRequestReviewComment: + r"""Call the add git repository link + pull request review comment method over HTTP. + + Args: + request (~.developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest): + The request object. Request message for + AddGitRepositoryLinkPullRequestReviewComment. + 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: + ~.developer_connect.PullRequestReviewComment: + Message representing a SCM Pull + Request Review Comment (inline on diff). + + """ + + http_options = _BaseDeveloperConnectRestTransport._BaseAddGitRepositoryLinkPullRequestReviewComment._get_http_options() + request, metadata = ( + self._interceptor.pre_add_git_repository_link_pull_request_review_comment( + request, metadata + ) + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseAddGitRepositoryLinkPullRequestReviewComment, + "_BaseAddGitRepositoryLinkPullRequestReviewComment__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.AddGitRepositoryLinkPullRequestReviewComment", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "AddGitRepositoryLinkPullRequestReviewComment", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DeveloperConnectRestTransport._AddGitRepositoryLinkPullRequestReviewComment._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 = developer_connect.PullRequestReviewComment() + pb_resp = developer_connect.PullRequestReviewComment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_add_git_repository_link_pull_request_review_comment( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_add_git_repository_link_pull_request_review_comment_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + developer_connect.PullRequestReviewComment.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.developerconnect_v1.DeveloperConnectClient.add_git_repository_link_pull_request_review_comment", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "AddGitRepositoryLinkPullRequestReviewComment", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateAccountConnector( + _BaseDeveloperConnectRestTransport._BaseCreateAccountConnector, + DeveloperConnectRestStub, + ): + def __hash__(self): + return hash("DeveloperConnectRestTransport.CreateAccountConnector") + + @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: developer_connect.CreateAccountConnectorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create account connector method over HTTP. + + Args: + request (~.developer_connect.CreateAccountConnectorRequest): + The request 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`. + + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseDeveloperConnectRestTransport._BaseCreateAccountConnector._get_http_options() + request, metadata = self._interceptor.pre_create_account_connector( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseCreateAccountConnector, + "_BaseCreateAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.CreateAccountConnector", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "CreateAccountConnector", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DeveloperConnectRestTransport._CreateAccountConnector._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_account_connector(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_account_connector_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.developerconnect_v1.DeveloperConnectClient.create_account_connector", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "CreateAccountConnector", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateConnection( + _BaseDeveloperConnectRestTransport._BaseCreateConnection, + DeveloperConnectRestStub, + ): + def __hash__(self): + return hash("DeveloperConnectRestTransport.CreateConnection") + + @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: developer_connect.CreateConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create connection method over HTTP. + + Args: + request (~.developer_connect.CreateConnectionRequest): + The request object. Message for creating a Connection + 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 = _BaseDeveloperConnectRestTransport._BaseCreateConnection._get_http_options() + request, metadata = self._interceptor.pre_create_connection( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseCreateConnection, + "_BaseCreateConnection__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.CreateConnection", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "CreateConnection", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DeveloperConnectRestTransport._CreateConnection._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_connection(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_connection_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.developerconnect_v1.DeveloperConnectClient.create_connection", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "CreateConnection", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateGitRepositoryLink( + _BaseDeveloperConnectRestTransport._BaseCreateGitRepositoryLink, + DeveloperConnectRestStub, + ): + def __hash__(self): + return hash("DeveloperConnectRestTransport.CreateGitRepositoryLink") + + @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: developer_connect.CreateGitRepositoryLinkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create git repository + link method over HTTP. + + Args: + request (~.developer_connect.CreateGitRepositoryLinkRequest): + The request object. Message for creating a + GitRepositoryLink + 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 = _BaseDeveloperConnectRestTransport._BaseCreateGitRepositoryLink._get_http_options() + request, metadata = self._interceptor.pre_create_git_repository_link( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseCreateGitRepositoryLink, + "_BaseCreateGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.CreateGitRepositoryLink", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "CreateGitRepositoryLink", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DeveloperConnectRestTransport._CreateGitRepositoryLink._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_git_repository_link(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_git_repository_link_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.developerconnect_v1.DeveloperConnectClient.create_git_repository_link", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "CreateGitRepositoryLink", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAccountConnector( + _BaseDeveloperConnectRestTransport._BaseDeleteAccountConnector, + DeveloperConnectRestStub, + ): + def __hash__(self): + return hash("DeveloperConnectRestTransport.DeleteAccountConnector") + + @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: developer_connect.DeleteAccountConnectorRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete account connector method over HTTP. + + Args: + request (~.developer_connect.DeleteAccountConnectorRequest): + The request object. Message for deleting a + AccountConnector + 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 = _BaseDeveloperConnectRestTransport._BaseDeleteAccountConnector._get_http_options() + request, metadata = self._interceptor.pre_delete_account_connector( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseDeleteAccountConnector, + "_BaseDeleteAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.DeleteAccountConnector", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteAccountConnector", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DeveloperConnectRestTransport._DeleteAccountConnector._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_account_connector(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_account_connector_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.developerconnect_v1.DeveloperConnectClient.delete_account_connector", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteAccountConnector", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteConnection( + _BaseDeveloperConnectRestTransport._BaseDeleteConnection, + DeveloperConnectRestStub, + ): + def __hash__(self): + return hash("DeveloperConnectRestTransport.DeleteConnection") + + @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: developer_connect.DeleteConnectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete connection method over HTTP. + + Args: + request (~.developer_connect.DeleteConnectionRequest): + The request object. Message for deleting a Connection + 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 = _BaseDeveloperConnectRestTransport._BaseDeleteConnection._get_http_options() + request, metadata = self._interceptor.pre_delete_connection( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseDeleteConnection, + "_BaseDeleteConnection__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.DeleteConnection", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteConnection", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DeveloperConnectRestTransport._DeleteConnection._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_connection(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_connection_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.developerconnect_v1.DeveloperConnectClient.delete_connection", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteConnection", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteGitRepositoryLink( + _BaseDeveloperConnectRestTransport._BaseDeleteGitRepositoryLink, + DeveloperConnectRestStub, + ): + def __hash__(self): + return hash("DeveloperConnectRestTransport.DeleteGitRepositoryLink") + + @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: developer_connect.DeleteGitRepositoryLinkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete git repository + link method over HTTP. + + Args: + request (~.developer_connect.DeleteGitRepositoryLinkRequest): + The request object. Message for deleting a + GitRepositoryLink + 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 = _BaseDeveloperConnectRestTransport._BaseDeleteGitRepositoryLink._get_http_options() + request, metadata = self._interceptor.pre_delete_git_repository_link( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseDeleteGitRepositoryLink, + "_BaseDeleteGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.DeleteGitRepositoryLink", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteGitRepositoryLink", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + DeveloperConnectRestTransport._DeleteGitRepositoryLink._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_git_repository_link(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_git_repository_link_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.developerconnect_v1.DeveloperConnectClient.delete_git_repository_link", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteGitRepositoryLink", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteSelf( + _BaseDeveloperConnectRestTransport._BaseDeleteSelf, DeveloperConnectRestStub + ): + def __hash__(self): + return hash("DeveloperConnectRestTransport.DeleteSelf") + + @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: developer_connect.DeleteSelfRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete self method over HTTP. + + Args: + request (~.developer_connect.DeleteSelfRequest): + The request object. Message for deleting a User of the + user themselves. + 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 = ( + _BaseDeveloperConnectRestTransport._BaseDeleteSelf._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_self(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseDeleteSelf, + "_BaseDeleteSelf__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.DeleteSelf", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteSelf", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DeveloperConnectRestTransport._DeleteSelf._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_self(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_self_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.developerconnect_v1.DeveloperConnectClient.delete_self", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteSelf", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteUser( + _BaseDeveloperConnectRestTransport._BaseDeleteUser, DeveloperConnectRestStub + ): + def __hash__(self): + return hash("DeveloperConnectRestTransport.DeleteUser") + + @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: developer_connect.DeleteUserRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete user method over HTTP. + + Args: + request (~.developer_connect.DeleteUserRequest): + The request object. Message for deleting a User + 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 = ( + _BaseDeveloperConnectRestTransport._BaseDeleteUser._get_http_options() + ) + request, metadata = self._interceptor.pre_delete_user(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseDeveloperConnectRestTransport._BaseDeleteUser, + "_BaseDeleteUser__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.developerconnect_v1.DeveloperConnectClient.DeleteUser", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = DeveloperConnectRestTransport._DeleteUser._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_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_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.developerconnect_v1.DeveloperConnectClient.delete_user", + extra={ + "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", + "rpcName": "DeleteUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DiffGitRepositoryLinkCommit( + _BaseDeveloperConnectRestTransport._BaseDiffGitRepositoryLinkCommit, + DeveloperConnectRestStub, + ): + def __hash__(self): + return hash("DeveloperConnectRestTransport.DiffGitRepositoryLinkCommit") @staticmethod def _get_response( @@ -1909,49 +4017,49 @@ 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: developer_connect.CreateAccountConnectorRequest, + request: developer_connect.DiffGitRepositoryLinkCommitRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create account connector method over HTTP. + ) -> developer_connect.DiffGitRepositoryLinkCommitResponse: + r"""Call the diff git repository link + commit method over HTTP. - Args: - request (~.developer_connect.CreateAccountConnectorRequest): - The request 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`. + Args: + request (~.developer_connect.DiffGitRepositoryLinkCommitRequest): + The request object. Request message for + DiffGitRepositoryLinkCommit. + 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. + Returns: + ~.developer_connect.DiffGitRepositoryLinkCommitResponse: + Response message for + DiffGitRepositoryLinkCommit. """ - http_options = _BaseDeveloperConnectRestTransport._BaseCreateAccountConnector._get_http_options() - request, metadata = self._interceptor.pre_create_account_connector( + http_options = _BaseDeveloperConnectRestTransport._BaseDiffGitRepositoryLinkCommit._get_http_options() + request, metadata = self._interceptor.pre_diff_git_repository_link_commit( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseCreateAccountConnector, - "_BaseCreateAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseDiffGitRepositoryLinkCommit, + "_BaseDiffGitRepositoryLinkCommit__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -1975,26 +4083,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.CreateAccountConnector", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.DiffGitRepositoryLinkCommit", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "CreateAccountConnector", + "rpcName": "DiffGitRepositoryLinkCommit", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - DeveloperConnectRestTransport._CreateAccountConnector._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - body, - ) + response = DeveloperConnectRestTransport._DiffGitRepositoryLinkCommit._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2003,19 +4108,27 @@ 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 = developer_connect.DiffGitRepositoryLinkCommitResponse() + pb_resp = developer_connect.DiffGitRepositoryLinkCommitResponse.pb(resp) - resp = self._interceptor.post_create_account_connector(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_diff_git_repository_link_commit(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_account_connector_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_diff_git_repository_link_commit_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 = ( + developer_connect.DiffGitRepositoryLinkCommitResponse.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -2024,22 +4137,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.create_account_connector", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.diff_git_repository_link_commit", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "CreateAccountConnector", + "rpcName": "DiffGitRepositoryLinkCommit", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _CreateConnection( - _BaseDeveloperConnectRestTransport._BaseCreateConnection, + class _FetchAccessToken( + _BaseDeveloperConnectRestTransport._BaseFetchAccessToken, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.CreateConnection") + return hash("DeveloperConnectRestTransport.FetchAccessToken") @staticmethod def _get_response( @@ -2066,17 +4179,18 @@ def _get_response( def __call__( self, - request: developer_connect.CreateConnectionRequest, + request: developer_connect.FetchAccessTokenRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create connection method over HTTP. + ) -> developer_connect.FetchAccessTokenResponse: + r"""Call the fetch access token method over HTTP. Args: - request (~.developer_connect.CreateConnectionRequest): - The request object. Message for creating a Connection + request (~.developer_connect.FetchAccessTokenRequest): + The request object. Message for fetching an OAuth access + token. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2086,23 +4200,22 @@ 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. + ~.developer_connect.FetchAccessTokenResponse: + Message for responding to getting an + OAuth access token. """ - http_options = _BaseDeveloperConnectRestTransport._BaseCreateConnection._get_http_options() - request, metadata = self._interceptor.pre_create_connection( + http_options = _BaseDeveloperConnectRestTransport._BaseFetchAccessToken._get_http_options() + request, metadata = self._interceptor.pre_fetch_access_token( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseCreateConnection, - "_BaseCreateConnection__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchAccessToken, + "_BaseFetchAccessToken__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -2126,17 +4239,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.CreateConnection", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchAccessToken", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "CreateConnection", + "rpcName": "FetchAccessToken", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._CreateConnection._get_response( + response = DeveloperConnectRestTransport._FetchAccessToken._get_response( self._host, metadata, query_params, @@ -2152,19 +4265,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 = developer_connect.FetchAccessTokenResponse() + pb_resp = developer_connect.FetchAccessTokenResponse.pb(resp) - resp = self._interceptor.post_create_connection(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_access_token(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_connection_with_metadata( + resp, _ = self._interceptor.post_fetch_access_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) + response_payload = ( + developer_connect.FetchAccessTokenResponse.to_json(response) + ) except: response_payload = None http_response = { @@ -2173,22 +4290,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.create_connection", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_access_token", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "CreateConnection", + "rpcName": "FetchAccessToken", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _CreateGitRepositoryLink( - _BaseDeveloperConnectRestTransport._BaseCreateGitRepositoryLink, + class _FetchGitHubInstallations( + _BaseDeveloperConnectRestTransport._BaseFetchGitHubInstallations, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.CreateGitRepositoryLink") + return hash("DeveloperConnectRestTransport.FetchGitHubInstallations") @staticmethod def _get_response( @@ -2209,25 +4326,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: developer_connect.CreateGitRepositoryLinkRequest, + request: developer_connect.FetchGitHubInstallationsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create git repository - link method over HTTP. + ) -> developer_connect.FetchGitHubInstallationsResponse: + r"""Call the fetch git hub + installations method over HTTP. Args: - request (~.developer_connect.CreateGitRepositoryLinkRequest): - The request object. Message for creating a - GitRepositoryLink + request (~.developer_connect.FetchGitHubInstallationsRequest): + The request object. Request for fetching github + installations. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2237,23 +4353,22 @@ 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. + ~.developer_connect.FetchGitHubInstallationsResponse: + Response of fetching github + installations. """ - http_options = _BaseDeveloperConnectRestTransport._BaseCreateGitRepositoryLink._get_http_options() - request, metadata = self._interceptor.pre_create_git_repository_link( + http_options = _BaseDeveloperConnectRestTransport._BaseFetchGitHubInstallations._get_http_options() + request, metadata = self._interceptor.pre_fetch_git_hub_installations( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseCreateGitRepositoryLink, - "_BaseCreateGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchGitHubInstallations, + "_BaseFetchGitHubInstallations__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -2277,10 +4392,10 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.CreateGitRepositoryLink", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchGitHubInstallations", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "CreateGitRepositoryLink", + "rpcName": "FetchGitHubInstallations", "httpRequest": http_request, "metadata": http_request["headers"], }, @@ -2288,14 +4403,13 @@ def __call__( # Send the request response = ( - DeveloperConnectRestTransport._CreateGitRepositoryLink._get_response( + DeveloperConnectRestTransport._FetchGitHubInstallations._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) ) @@ -2305,19 +4419,25 @@ 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 = developer_connect.FetchGitHubInstallationsResponse() + pb_resp = developer_connect.FetchGitHubInstallationsResponse.pb(resp) - resp = self._interceptor.post_create_git_repository_link(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_git_hub_installations(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_git_repository_link_with_metadata( + resp, _ = self._interceptor.post_fetch_git_hub_installations_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 = ( + developer_connect.FetchGitHubInstallationsResponse.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -2326,22 +4446,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.create_git_repository_link", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_hub_installations", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "CreateGitRepositoryLink", + "rpcName": "FetchGitHubInstallations", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteAccountConnector( - _BaseDeveloperConnectRestTransport._BaseDeleteAccountConnector, - DeveloperConnectRestStub, + class _FetchGitRefs( + _BaseDeveloperConnectRestTransport._BaseFetchGitRefs, DeveloperConnectRestStub ): def __hash__(self): - return hash("DeveloperConnectRestTransport.DeleteAccountConnector") + return hash("DeveloperConnectRestTransport.FetchGitRefs") @staticmethod def _get_response( @@ -2367,18 +4486,17 @@ def _get_response( def __call__( self, - request: developer_connect.DeleteAccountConnectorRequest, + request: developer_connect.FetchGitRefsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete account connector method over HTTP. + ) -> developer_connect.FetchGitRefsResponse: + r"""Call the fetch git refs method over HTTP. Args: - request (~.developer_connect.DeleteAccountConnectorRequest): - The request object. Message for deleting a - AccountConnector + request (~.developer_connect.FetchGitRefsRequest): + The request object. Request for fetching git refs. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2388,23 +4506,20 @@ 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. - + ~.developer_connect.FetchGitRefsResponse: + Response for fetching git refs. """ - http_options = _BaseDeveloperConnectRestTransport._BaseDeleteAccountConnector._get_http_options() - request, metadata = self._interceptor.pre_delete_account_connector( - request, metadata + http_options = ( + _BaseDeveloperConnectRestTransport._BaseFetchGitRefs._get_http_options() ) + request, metadata = self._interceptor.pre_fetch_git_refs(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseDeleteAccountConnector, - "_BaseDeleteAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchGitRefs, + "_BaseFetchGitRefs__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -2428,25 +4543,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.DeleteAccountConnector", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchGitRefs", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteAccountConnector", + "rpcName": "FetchGitRefs", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - DeveloperConnectRestTransport._DeleteAccountConnector._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = DeveloperConnectRestTransport._FetchGitRefs._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2455,19 +4568,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 = developer_connect.FetchGitRefsResponse() + pb_resp = developer_connect.FetchGitRefsResponse.pb(resp) - resp = self._interceptor.post_delete_account_connector(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_git_refs(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_account_connector_with_metadata( + resp, _ = self._interceptor.post_fetch_git_refs_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 = developer_connect.FetchGitRefsResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -2476,22 +4593,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.delete_account_connector", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_refs", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteAccountConnector", + "rpcName": "FetchGitRefs", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteConnection( - _BaseDeveloperConnectRestTransport._BaseDeleteConnection, + class _FetchGitRepositoryLinkCommit( + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkCommit, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.DeleteConnection") + return hash("DeveloperConnectRestTransport.FetchGitRepositoryLinkCommit") @staticmethod def _get_response( @@ -2517,43 +4634,44 @@ def _get_response( def __call__( self, - request: developer_connect.DeleteConnectionRequest, + request: developer_connect.FetchGitRepositoryLinkCommitRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete connection method over HTTP. + ) -> developer_connect.FetchGitRepositoryLinkCommitResponse: + r"""Call the fetch git repository link + commit method over HTTP. - Args: - request (~.developer_connect.DeleteConnectionRequest): - The request object. Message for deleting a Connection - 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 (~.developer_connect.FetchGitRepositoryLinkCommitRequest): + The request object. Request message for + FetchGitRepositoryLinkCommit. + 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. + Returns: + ~.developer_connect.FetchGitRepositoryLinkCommitResponse: + Response message for + FetchGitRepositoryLinkCommit. """ - http_options = _BaseDeveloperConnectRestTransport._BaseDeleteConnection._get_http_options() - request, metadata = self._interceptor.pre_delete_connection( + http_options = _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkCommit._get_http_options() + request, metadata = self._interceptor.pre_fetch_git_repository_link_commit( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseDeleteConnection, - "_BaseDeleteConnection__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkCommit, + "_BaseFetchGitRepositoryLinkCommit__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -2577,17 +4695,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.DeleteConnection", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchGitRepositoryLinkCommit", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteConnection", + "rpcName": "FetchGitRepositoryLinkCommit", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._DeleteConnection._get_response( + response = DeveloperConnectRestTransport._FetchGitRepositoryLinkCommit._get_response( self._host, metadata, query_params, @@ -2602,19 +4720,27 @@ 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 = developer_connect.FetchGitRepositoryLinkCommitResponse() + pb_resp = developer_connect.FetchGitRepositoryLinkCommitResponse.pb(resp) - resp = self._interceptor.post_delete_connection(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_git_repository_link_commit(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_connection_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_fetch_git_repository_link_commit_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 = ( + developer_connect.FetchGitRepositoryLinkCommitResponse.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -2623,22 +4749,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.delete_connection", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_commit", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteConnection", + "rpcName": "FetchGitRepositoryLinkCommit", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteGitRepositoryLink( - _BaseDeveloperConnectRestTransport._BaseDeleteGitRepositoryLink, + class _FetchGitRepositoryLinkCommitList( + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkCommitList, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.DeleteGitRepositoryLink") + return hash( + "DeveloperConnectRestTransport.FetchGitRepositoryLinkCommitList" + ) @staticmethod def _get_response( @@ -2664,19 +4792,19 @@ def _get_response( def __call__( self, - request: developer_connect.DeleteGitRepositoryLinkRequest, + request: developer_connect.FetchGitRepositoryLinkCommitListRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete git repository - link method over HTTP. + ) -> developer_connect.FetchGitRepositoryLinkCommitListResponse: + r"""Call the fetch git repository link + commit list method over HTTP. Args: - request (~.developer_connect.DeleteGitRepositoryLinkRequest): - The request object. Message for deleting a - GitRepositoryLink + request (~.developer_connect.FetchGitRepositoryLinkCommitListRequest): + The request object. Request message for + FetchGitRepositoryLinkCommitList. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -2686,23 +4814,24 @@ 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. + ~.developer_connect.FetchGitRepositoryLinkCommitListResponse: + Response message for + FetchGitRepositoryLinkCommitList. """ - http_options = _BaseDeveloperConnectRestTransport._BaseDeleteGitRepositoryLink._get_http_options() - request, metadata = self._interceptor.pre_delete_git_repository_link( - request, metadata + http_options = _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkCommitList._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_git_repository_link_commit_list( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseDeleteGitRepositoryLink, - "_BaseDeleteGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkCommitList, + "_BaseFetchGitRepositoryLinkCommitList__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -2726,25 +4855,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.DeleteGitRepositoryLink", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchGitRepositoryLinkCommitList", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteGitRepositoryLink", + "rpcName": "FetchGitRepositoryLinkCommitList", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - DeveloperConnectRestTransport._DeleteGitRepositoryLink._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = DeveloperConnectRestTransport._FetchGitRepositoryLinkCommitList._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2753,19 +4880,27 @@ 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 = developer_connect.FetchGitRepositoryLinkCommitListResponse() + pb_resp = developer_connect.FetchGitRepositoryLinkCommitListResponse.pb( + resp + ) - resp = self._interceptor.post_delete_git_repository_link(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_git_repository_link_commit_list(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_git_repository_link_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_fetch_git_repository_link_commit_list_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 = developer_connect.FetchGitRepositoryLinkCommitListResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -2774,21 +4909,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.delete_git_repository_link", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_commit_list", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteGitRepositoryLink", + "rpcName": "FetchGitRepositoryLinkCommitList", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteSelf( - _BaseDeveloperConnectRestTransport._BaseDeleteSelf, DeveloperConnectRestStub + class _FetchGitRepositoryLinkFileBlame( + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkFileBlame, + DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.DeleteSelf") + return hash("DeveloperConnectRestTransport.FetchGitRepositoryLinkFileBlame") @staticmethod def _get_response( @@ -2814,44 +4950,46 @@ def _get_response( def __call__( self, - request: developer_connect.DeleteSelfRequest, + request: developer_connect.FetchGitRepositoryLinkFileBlameRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete self method over HTTP. + ) -> developer_connect.FetchGitRepositoryLinkFileBlameResponse: + r"""Call the fetch git repository link + file blame method over HTTP. - Args: - request (~.developer_connect.DeleteSelfRequest): - The request object. Message for deleting a User of the - user themselves. - 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 (~.developer_connect.FetchGitRepositoryLinkFileBlameRequest): + The request object. Request message for + FetchGitRepositoryLinkFileBlame. + 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. + Returns: + ~.developer_connect.FetchGitRepositoryLinkFileBlameResponse: + Response message for + FetchGitRepositoryLinkFileBlame. """ - http_options = ( - _BaseDeveloperConnectRestTransport._BaseDeleteSelf._get_http_options() + http_options = _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkFileBlame._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_git_repository_link_file_blame( + request, metadata + ) ) - request, metadata = self._interceptor.pre_delete_self(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseDeleteSelf, - "_BaseDeleteSelf__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkFileBlame, + "_BaseFetchGitRepositoryLinkFileBlame__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -2875,17 +5013,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.DeleteSelf", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchGitRepositoryLinkFileBlame", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteSelf", + "rpcName": "FetchGitRepositoryLinkFileBlame", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._DeleteSelf._get_response( + response = DeveloperConnectRestTransport._FetchGitRepositoryLinkFileBlame._get_response( self._host, metadata, query_params, @@ -2900,19 +5038,25 @@ 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 = developer_connect.FetchGitRepositoryLinkFileBlameResponse() + pb_resp = developer_connect.FetchGitRepositoryLinkFileBlameResponse.pb(resp) - resp = self._interceptor.post_delete_self(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_git_repository_link_file_blame(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_self_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_fetch_git_repository_link_file_blame_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 = developer_connect.FetchGitRepositoryLinkFileBlameResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -2921,21 +5065,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.delete_self", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_file_blame", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteSelf", + "rpcName": "FetchGitRepositoryLinkFileBlame", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteUser( - _BaseDeveloperConnectRestTransport._BaseDeleteUser, DeveloperConnectRestStub + class _FetchGitRepositoryLinkPullRequest( + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkPullRequest, + DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.DeleteUser") + return hash( + "DeveloperConnectRestTransport.FetchGitRepositoryLinkPullRequest" + ) @staticmethod def _get_response( @@ -2961,43 +5108,46 @@ def _get_response( def __call__( self, - request: developer_connect.DeleteUserRequest, + request: developer_connect.FetchGitRepositoryLinkPullRequestRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete user method over HTTP. + ) -> developer_connect.PullRequest: + r"""Call the fetch git repository link + pull request method over HTTP. - Args: - request (~.developer_connect.DeleteUserRequest): - The request object. Message for deleting a User - 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 (~.developer_connect.FetchGitRepositoryLinkPullRequestRequest): + The request object. Request message for + FetchGitRepositoryLinkPullRequest. + 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. + Returns: + ~.developer_connect.PullRequest: + Message representing a SCM Pull + Request. """ - http_options = ( - _BaseDeveloperConnectRestTransport._BaseDeleteUser._get_http_options() + http_options = _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkPullRequest._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_git_repository_link_pull_request( + request, metadata + ) ) - request, metadata = self._interceptor.pre_delete_user(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseDeleteUser, - "_BaseDeleteUser__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkPullRequest, + "_BaseFetchGitRepositoryLinkPullRequest__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3021,17 +5171,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.DeleteUser", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchGitRepositoryLinkPullRequest", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteUser", + "rpcName": "FetchGitRepositoryLinkPullRequest", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._DeleteUser._get_response( + response = DeveloperConnectRestTransport._FetchGitRepositoryLinkPullRequest._get_response( self._host, metadata, query_params, @@ -3046,19 +5196,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 = developer_connect.PullRequest() + pb_resp = developer_connect.PullRequest.pb(resp) - resp = self._interceptor.post_delete_user(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_fetch_git_repository_link_pull_request(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_user_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_fetch_git_repository_link_pull_request_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 = developer_connect.PullRequest.to_json(response) except: response_payload = None http_response = { @@ -3067,22 +5221,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.delete_user", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_pull_request", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "DeleteUser", + "rpcName": "FetchGitRepositoryLinkPullRequest", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchAccessToken( - _BaseDeveloperConnectRestTransport._BaseFetchAccessToken, + class _FetchGitRepositoryLinkPullRequestList( + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkPullRequestList, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.FetchAccessToken") + return hash( + "DeveloperConnectRestTransport.FetchGitRepositoryLinkPullRequestList" + ) @staticmethod def _get_response( @@ -3103,49 +5259,51 @@ 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: developer_connect.FetchAccessTokenRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.FetchAccessTokenResponse: - r"""Call the fetch access token method over HTTP. - - Args: - request (~.developer_connect.FetchAccessTokenRequest): - The request object. Message for fetching an OAuth access - token. - 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`. + def __call__( + self, + request: developer_connect.FetchGitRepositoryLinkPullRequestListRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> developer_connect.FetchGitRepositoryLinkPullRequestListResponse: + r"""Call the fetch git repository link + pull request list method over HTTP. - Returns: - ~.developer_connect.FetchAccessTokenResponse: - Message for responding to getting an - OAuth access token. + Args: + request (~.developer_connect.FetchGitRepositoryLinkPullRequestListRequest): + The request object. Request message for + FetchGitRepositoryLinkPullRequestList. + 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: + ~.developer_connect.FetchGitRepositoryLinkPullRequestListResponse: + Response message for + FetchGitRepositoryLinkPullRequestList. """ - http_options = _BaseDeveloperConnectRestTransport._BaseFetchAccessToken._get_http_options() - request, metadata = self._interceptor.pre_fetch_access_token( - request, metadata + http_options = _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkPullRequestList._get_http_options() + request, metadata = ( + self._interceptor.pre_fetch_git_repository_link_pull_request_list( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseFetchAccessToken, - "_BaseFetchAccessToken__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchGitRepositoryLinkPullRequestList, + "_BaseFetchGitRepositoryLinkPullRequestList__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3169,24 +5327,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchAccessToken", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchGitRepositoryLinkPullRequestList", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchAccessToken", + "rpcName": "FetchGitRepositoryLinkPullRequestList", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._FetchAccessToken._get_response( + response = DeveloperConnectRestTransport._FetchGitRepositoryLinkPullRequestList._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3195,22 +5352,28 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.FetchAccessTokenResponse() - pb_resp = developer_connect.FetchAccessTokenResponse.pb(resp) + resp = developer_connect.FetchGitRepositoryLinkPullRequestListResponse() + pb_resp = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse.pb(resp) + ) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_access_token(resp) + resp = self._interceptor.post_fetch_git_repository_link_pull_request_list( + resp + ) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_access_token_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_fetch_git_repository_link_pull_request_list_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - developer_connect.FetchAccessTokenResponse.to_json(response) + response_payload = developer_connect.FetchGitRepositoryLinkPullRequestListResponse.to_json( + response ) except: response_payload = None @@ -3220,22 +5383,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_access_token", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_pull_request_list", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchAccessToken", + "rpcName": "FetchGitRepositoryLinkPullRequestList", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchGitHubInstallations( - _BaseDeveloperConnectRestTransport._BaseFetchGitHubInstallations, + class _FetchLinkableGitRepositories( + _BaseDeveloperConnectRestTransport._BaseFetchLinkableGitRepositories, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.FetchGitHubInstallations") + return hash("DeveloperConnectRestTransport.FetchLinkableGitRepositories") @staticmethod def _get_response( @@ -3261,19 +5424,19 @@ def _get_response( def __call__( self, - request: developer_connect.FetchGitHubInstallationsRequest, + request: developer_connect.FetchLinkableGitRepositoriesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.FetchGitHubInstallationsResponse: - r"""Call the fetch git hub - installations method over HTTP. + ) -> developer_connect.FetchLinkableGitRepositoriesResponse: + r"""Call the fetch linkable git + repositories method over HTTP. Args: - request (~.developer_connect.FetchGitHubInstallationsRequest): - The request object. Request for fetching github - installations. + request (~.developer_connect.FetchLinkableGitRepositoriesRequest): + The request object. Request message for + FetchLinkableGitRepositoriesRequest. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3283,22 +5446,22 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.FetchGitHubInstallationsResponse: - Response of fetching github - installations. + ~.developer_connect.FetchLinkableGitRepositoriesResponse: + Response message for + FetchLinkableGitRepositories. """ - http_options = _BaseDeveloperConnectRestTransport._BaseFetchGitHubInstallations._get_http_options() - request, metadata = self._interceptor.pre_fetch_git_hub_installations( + http_options = _BaseDeveloperConnectRestTransport._BaseFetchLinkableGitRepositories._get_http_options() + request, metadata = self._interceptor.pre_fetch_linkable_git_repositories( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseFetchGitHubInstallations, - "_BaseFetchGitHubInstallations__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchLinkableGitRepositories, + "_BaseFetchLinkableGitRepositories__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3322,25 +5485,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchGitHubInstallations", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchLinkableGitRepositories", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchGitHubInstallations", + "rpcName": "FetchLinkableGitRepositories", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - DeveloperConnectRestTransport._FetchGitHubInstallations._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = DeveloperConnectRestTransport._FetchLinkableGitRepositories._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3349,22 +5510,24 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.FetchGitHubInstallationsResponse() - pb_resp = developer_connect.FetchGitHubInstallationsResponse.pb(resp) + resp = developer_connect.FetchLinkableGitRepositoriesResponse() + pb_resp = developer_connect.FetchLinkableGitRepositoriesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_git_hub_installations(resp) + resp = self._interceptor.post_fetch_linkable_git_repositories(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_git_hub_installations_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_fetch_linkable_git_repositories_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: response_payload = ( - developer_connect.FetchGitHubInstallationsResponse.to_json( + developer_connect.FetchLinkableGitRepositoriesResponse.to_json( response ) ) @@ -3376,21 +5539,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_hub_installations", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_linkable_git_repositories", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchGitHubInstallations", + "rpcName": "FetchLinkableGitRepositories", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchGitRefs( - _BaseDeveloperConnectRestTransport._BaseFetchGitRefs, DeveloperConnectRestStub + class _FetchReadToken( + _BaseDeveloperConnectRestTransport._BaseFetchReadToken, DeveloperConnectRestStub ): def __hash__(self): - return hash("DeveloperConnectRestTransport.FetchGitRefs") + return hash("DeveloperConnectRestTransport.FetchReadToken") @staticmethod def _get_response( @@ -3411,22 +5574,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: developer_connect.FetchGitRefsRequest, + request: developer_connect.FetchReadTokenRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.FetchGitRefsResponse: - r"""Call the fetch git refs method over HTTP. + ) -> developer_connect.FetchReadTokenResponse: + r"""Call the fetch read token method over HTTP. Args: - request (~.developer_connect.FetchGitRefsRequest): - The request object. Request for fetching git refs. + request (~.developer_connect.FetchReadTokenRequest): + The request object. Message for fetching SCM read token. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3436,20 +5600,22 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.FetchGitRefsResponse: - Response for fetching git refs. + ~.developer_connect.FetchReadTokenResponse: + Message for responding to get read + token. + """ - http_options = ( - _BaseDeveloperConnectRestTransport._BaseFetchGitRefs._get_http_options() + http_options = _BaseDeveloperConnectRestTransport._BaseFetchReadToken._get_http_options() + request, metadata = self._interceptor.pre_fetch_read_token( + request, metadata ) - request, metadata = self._interceptor.pre_fetch_git_refs(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseFetchGitRefs, - "_BaseFetchGitRefs__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchReadToken, + "_BaseFetchReadToken__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3473,23 +5639,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchGitRefs", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchReadToken", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchGitRefs", + "rpcName": "FetchReadToken", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._FetchGitRefs._get_response( + response = DeveloperConnectRestTransport._FetchReadToken._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3498,21 +5665,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.FetchGitRefsResponse() - pb_resp = developer_connect.FetchGitRefsResponse.pb(resp) + resp = developer_connect.FetchReadTokenResponse() + pb_resp = developer_connect.FetchReadTokenResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_git_refs(resp) + resp = self._interceptor.post_fetch_read_token(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_git_refs_with_metadata( + resp, _ = self._interceptor.post_fetch_read_token_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = developer_connect.FetchGitRefsResponse.to_json( + response_payload = developer_connect.FetchReadTokenResponse.to_json( response ) except: @@ -3523,22 +5690,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_refs", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_read_token", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchGitRefs", + "rpcName": "FetchReadToken", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchLinkableGitRepositories( - _BaseDeveloperConnectRestTransport._BaseFetchLinkableGitRepositories, + class _FetchReadWriteToken( + _BaseDeveloperConnectRestTransport._BaseFetchReadWriteToken, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.FetchLinkableGitRepositories") + return hash("DeveloperConnectRestTransport.FetchReadWriteToken") @staticmethod def _get_response( @@ -3559,49 +5726,49 @@ 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: developer_connect.FetchLinkableGitRepositoriesRequest, + request: developer_connect.FetchReadWriteTokenRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.FetchLinkableGitRepositoriesResponse: - r"""Call the fetch linkable git - repositories method over HTTP. + ) -> developer_connect.FetchReadWriteTokenResponse: + r"""Call the fetch read write token method over HTTP. - Args: - request (~.developer_connect.FetchLinkableGitRepositoriesRequest): - The request object. Request message for - FetchLinkableGitRepositoriesRequest. - 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 (~.developer_connect.FetchReadWriteTokenRequest): + The request object. Message for fetching SCM read/write + token. + 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: - ~.developer_connect.FetchLinkableGitRepositoriesResponse: - Response message for - FetchLinkableGitRepositories. + Returns: + ~.developer_connect.FetchReadWriteTokenResponse: + Message for responding to get + read/write token. """ - http_options = _BaseDeveloperConnectRestTransport._BaseFetchLinkableGitRepositories._get_http_options() - request, metadata = self._interceptor.pre_fetch_linkable_git_repositories( + http_options = _BaseDeveloperConnectRestTransport._BaseFetchReadWriteToken._get_http_options() + request, metadata = self._interceptor.pre_fetch_read_write_token( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseFetchLinkableGitRepositories, - "_BaseFetchLinkableGitRepositories__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchReadWriteToken, + "_BaseFetchReadWriteToken__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3625,23 +5792,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchLinkableGitRepositories", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchReadWriteToken", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchLinkableGitRepositories", + "rpcName": "FetchReadWriteToken", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._FetchLinkableGitRepositories._get_response( + response = DeveloperConnectRestTransport._FetchReadWriteToken._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3650,26 +5818,22 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.FetchLinkableGitRepositoriesResponse() - pb_resp = developer_connect.FetchLinkableGitRepositoriesResponse.pb(resp) + resp = developer_connect.FetchReadWriteTokenResponse() + pb_resp = developer_connect.FetchReadWriteTokenResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_linkable_git_repositories(resp) + resp = self._interceptor.post_fetch_read_write_token(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_fetch_linkable_git_repositories_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_fetch_read_write_token_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: response_payload = ( - developer_connect.FetchLinkableGitRepositoriesResponse.to_json( - response - ) + developer_connect.FetchReadWriteTokenResponse.to_json(response) ) except: response_payload = None @@ -3679,21 +5843,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_linkable_git_repositories", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_read_write_token", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchLinkableGitRepositories", + "rpcName": "FetchReadWriteToken", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchReadToken( - _BaseDeveloperConnectRestTransport._BaseFetchReadToken, DeveloperConnectRestStub + class _FetchSelf( + _BaseDeveloperConnectRestTransport._BaseFetchSelf, DeveloperConnectRestStub ): def __hash__(self): - return hash("DeveloperConnectRestTransport.FetchReadToken") + return hash("DeveloperConnectRestTransport.FetchSelf") @staticmethod def _get_response( @@ -3714,23 +5878,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: developer_connect.FetchReadTokenRequest, + request: developer_connect.FetchSelfRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.FetchReadTokenResponse: - r"""Call the fetch read token method over HTTP. + ) -> developer_connect.User: + r"""Call the fetch self method over HTTP. Args: - request (~.developer_connect.FetchReadTokenRequest): - The request object. Message for fetching SCM read token. + request (~.developer_connect.FetchSelfRequest): + The request object. Message for fetching a User of the + user themselves. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3740,22 +5904,23 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.FetchReadTokenResponse: - Message for responding to get read - token. + ~.developer_connect.User: + User represents a user connected to + the service providers through a + AccountConnector. """ - http_options = _BaseDeveloperConnectRestTransport._BaseFetchReadToken._get_http_options() - request, metadata = self._interceptor.pre_fetch_read_token( - request, metadata + http_options = ( + _BaseDeveloperConnectRestTransport._BaseFetchSelf._get_http_options() ) + request, metadata = self._interceptor.pre_fetch_self(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseFetchReadToken, - "_BaseFetchReadToken__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFetchSelf, + "_BaseFetchSelf__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3779,24 +5944,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchReadToken", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchSelf", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchReadToken", + "rpcName": "FetchSelf", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._FetchReadToken._get_response( + response = DeveloperConnectRestTransport._FetchSelf._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3805,23 +5969,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.FetchReadTokenResponse() - pb_resp = developer_connect.FetchReadTokenResponse.pb(resp) + resp = developer_connect.User() + pb_resp = developer_connect.User.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_read_token(resp) + resp = self._interceptor.post_fetch_self(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_read_token_with_metadata( + resp, _ = self._interceptor.post_fetch_self_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = developer_connect.FetchReadTokenResponse.to_json( - response - ) + response_payload = developer_connect.User.to_json(response) except: response_payload = None http_response = { @@ -3830,22 +5992,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_read_token", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_self", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchReadToken", + "rpcName": "FetchSelf", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchReadWriteToken( - _BaseDeveloperConnectRestTransport._BaseFetchReadWriteToken, - DeveloperConnectRestStub, + class _FinishOAuth( + _BaseDeveloperConnectRestTransport._BaseFinishOAuth, DeveloperConnectRestStub ): def __hash__(self): - return hash("DeveloperConnectRestTransport.FetchReadWriteToken") + return hash("DeveloperConnectRestTransport.FinishOAuth") @staticmethod def _get_response( @@ -3866,24 +6027,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: developer_connect.FetchReadWriteTokenRequest, + request: developer_connect.FinishOAuthRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.FetchReadWriteTokenResponse: - r"""Call the fetch read write token method over HTTP. + ) -> developer_connect.FinishOAuthResponse: + r"""Call the finish o auth method over HTTP. Args: - request (~.developer_connect.FetchReadWriteTokenRequest): - The request object. Message for fetching SCM read/write - token. + request (~.developer_connect.FinishOAuthRequest): + The request object. Message for finishing an OAuth flow. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -3893,22 +6052,22 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.FetchReadWriteTokenResponse: - Message for responding to get - read/write token. + ~.developer_connect.FinishOAuthResponse: + Message for responding to finishing + an OAuth flow. """ - http_options = _BaseDeveloperConnectRestTransport._BaseFetchReadWriteToken._get_http_options() - request, metadata = self._interceptor.pre_fetch_read_write_token( - request, metadata + http_options = ( + _BaseDeveloperConnectRestTransport._BaseFinishOAuth._get_http_options() ) + request, metadata = self._interceptor.pre_finish_o_auth(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseFetchReadWriteToken, - "_BaseFetchReadWriteToken__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseFinishOAuth, + "_BaseFinishOAuth__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -3932,24 +6091,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchReadWriteToken", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FinishOAuth", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchReadWriteToken", + "rpcName": "FinishOAuth", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._FetchReadWriteToken._get_response( + response = DeveloperConnectRestTransport._FinishOAuth._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -3958,22 +6116,22 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.FetchReadWriteTokenResponse() - pb_resp = developer_connect.FetchReadWriteTokenResponse.pb(resp) + resp = developer_connect.FinishOAuthResponse() + pb_resp = developer_connect.FinishOAuthResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_read_write_token(resp) + resp = self._interceptor.post_finish_o_auth(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_read_write_token_with_metadata( + resp, _ = self._interceptor.post_finish_o_auth_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - developer_connect.FetchReadWriteTokenResponse.to_json(response) + response_payload = developer_connect.FinishOAuthResponse.to_json( + response ) except: response_payload = None @@ -3983,21 +6141,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_read_write_token", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.finish_o_auth", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchReadWriteToken", + "rpcName": "FinishOAuth", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FetchSelf( - _BaseDeveloperConnectRestTransport._BaseFetchSelf, DeveloperConnectRestStub + class _GetAccountConnector( + _BaseDeveloperConnectRestTransport._BaseGetAccountConnector, + DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.FetchSelf") + return hash("DeveloperConnectRestTransport.GetAccountConnector") @staticmethod def _get_response( @@ -4023,18 +6182,18 @@ def _get_response( def __call__( self, - request: developer_connect.FetchSelfRequest, + request: developer_connect.GetAccountConnectorRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.User: - r"""Call the fetch self method over HTTP. + ) -> developer_connect.AccountConnector: + r"""Call the get account connector method over HTTP. Args: - request (~.developer_connect.FetchSelfRequest): - The request object. Message for fetching a User of the - user themselves. + request (~.developer_connect.GetAccountConnectorRequest): + The request object. Message for getting a + AccountConnector retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4044,23 +6203,27 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.User: - User represents a user connected to - the service providers through a - AccountConnector. + ~.developer_connect.AccountConnector: + AccountConnector encapsulates what a + platform administrator needs to + configure for users to connect to the + service providers, which includes, among + other fields, the OAuth client ID, + client secret, and authorization and + token endpoints. """ - http_options = ( - _BaseDeveloperConnectRestTransport._BaseFetchSelf._get_http_options() + http_options = _BaseDeveloperConnectRestTransport._BaseGetAccountConnector._get_http_options() + request, metadata = self._interceptor.pre_get_account_connector( + request, metadata ) - request, metadata = self._interceptor.pre_fetch_self(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseFetchSelf, - "_BaseFetchSelf__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseGetAccountConnector, + "_BaseGetAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4084,17 +6247,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FetchSelf", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.GetAccountConnector", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchSelf", + "rpcName": "GetAccountConnector", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._FetchSelf._get_response( + response = DeveloperConnectRestTransport._GetAccountConnector._get_response( self._host, metadata, query_params, @@ -4109,21 +6272,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.User() - pb_resp = developer_connect.User.pb(resp) + resp = developer_connect.AccountConnector() + pb_resp = developer_connect.AccountConnector.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_fetch_self(resp) + resp = self._interceptor.post_get_account_connector(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_fetch_self_with_metadata( + resp, _ = self._interceptor.post_get_account_connector_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = developer_connect.User.to_json(response) + response_payload = developer_connect.AccountConnector.to_json( + response + ) except: response_payload = None http_response = { @@ -4132,21 +6297,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_self", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.get_account_connector", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FetchSelf", + "rpcName": "GetAccountConnector", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _FinishOAuth( - _BaseDeveloperConnectRestTransport._BaseFinishOAuth, DeveloperConnectRestStub + class _GetConnection( + _BaseDeveloperConnectRestTransport._BaseGetConnection, DeveloperConnectRestStub ): def __hash__(self): - return hash("DeveloperConnectRestTransport.FinishOAuth") + return hash("DeveloperConnectRestTransport.GetConnection") @staticmethod def _get_response( @@ -4172,17 +6337,17 @@ def _get_response( def __call__( self, - request: developer_connect.FinishOAuthRequest, + request: developer_connect.GetConnectionRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.FinishOAuthResponse: - r"""Call the finish o auth method over HTTP. + ) -> developer_connect.Connection: + r"""Call the get connection method over HTTP. Args: - request (~.developer_connect.FinishOAuthRequest): - The request object. Message for finishing an OAuth flow. + request (~.developer_connect.GetConnectionRequest): + The request object. Message for getting a Connection retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4192,22 +6357,18 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.FinishOAuthResponse: - Message for responding to finishing - an OAuth flow. - + ~.developer_connect.Connection: + Message describing Connection object """ - http_options = ( - _BaseDeveloperConnectRestTransport._BaseFinishOAuth._get_http_options() - ) - request, metadata = self._interceptor.pre_finish_o_auth(request, metadata) + http_options = _BaseDeveloperConnectRestTransport._BaseGetConnection._get_http_options() + request, metadata = self._interceptor.pre_get_connection(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseFinishOAuth, - "_BaseFinishOAuth__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseGetConnection, + "_BaseGetConnection__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4231,17 +6392,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.FinishOAuth", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.GetConnection", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FinishOAuth", + "rpcName": "GetConnection", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._FinishOAuth._get_response( + response = DeveloperConnectRestTransport._GetConnection._get_response( self._host, metadata, query_params, @@ -4256,23 +6417,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.FinishOAuthResponse() - pb_resp = developer_connect.FinishOAuthResponse.pb(resp) + resp = developer_connect.Connection() + pb_resp = developer_connect.Connection.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_finish_o_auth(resp) + resp = self._interceptor.post_get_connection(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_finish_o_auth_with_metadata( + resp, _ = self._interceptor.post_get_connection_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = developer_connect.FinishOAuthResponse.to_json( - response - ) + response_payload = developer_connect.Connection.to_json(response) except: response_payload = None http_response = { @@ -4281,22 +6440,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.finish_o_auth", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.get_connection", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "FinishOAuth", + "rpcName": "GetConnection", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetAccountConnector( - _BaseDeveloperConnectRestTransport._BaseGetAccountConnector, + class _GetGitRepositoryLink( + _BaseDeveloperConnectRestTransport._BaseGetGitRepositoryLink, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.GetAccountConnector") + return hash("DeveloperConnectRestTransport.GetGitRepositoryLink") @staticmethod def _get_response( @@ -4322,48 +6481,43 @@ def _get_response( def __call__( self, - request: developer_connect.GetAccountConnectorRequest, + request: developer_connect.GetGitRepositoryLinkRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.AccountConnector: - r"""Call the get account connector method over HTTP. + ) -> developer_connect.GitRepositoryLink: + r"""Call the get git repository link method over HTTP. Args: - request (~.developer_connect.GetAccountConnectorRequest): + request (~.developer_connect.GetGitRepositoryLinkRequest): The request object. Message for getting a - AccountConnector + GitRepositoryLink 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: - ~.developer_connect.AccountConnector: - AccountConnector encapsulates what a - platform administrator needs to - configure for users to connect to the - service providers, which includes, among - other fields, the OAuth client ID, - client secret, and authorization and - token endpoints. + be of type `bytes`. + + Returns: + ~.developer_connect.GitRepositoryLink: + Message describing the + GitRepositoryLink object """ - http_options = _BaseDeveloperConnectRestTransport._BaseGetAccountConnector._get_http_options() - request, metadata = self._interceptor.pre_get_account_connector( + http_options = _BaseDeveloperConnectRestTransport._BaseGetGitRepositoryLink._get_http_options() + request, metadata = self._interceptor.pre_get_git_repository_link( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseGetAccountConnector, - "_BaseGetAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseGetGitRepositoryLink, + "_BaseGetGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4387,23 +6541,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.GetAccountConnector", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.GetGitRepositoryLink", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "GetAccountConnector", + "rpcName": "GetGitRepositoryLink", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._GetAccountConnector._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + DeveloperConnectRestTransport._GetGitRepositoryLink._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4412,21 +6568,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.AccountConnector() - pb_resp = developer_connect.AccountConnector.pb(resp) + resp = developer_connect.GitRepositoryLink() + pb_resp = developer_connect.GitRepositoryLink.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_account_connector(resp) + resp = self._interceptor.post_get_git_repository_link(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_account_connector_with_metadata( + resp, _ = self._interceptor.post_get_git_repository_link_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = developer_connect.AccountConnector.to_json( + response_payload = developer_connect.GitRepositoryLink.to_json( response ) except: @@ -4437,21 +6593,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.get_account_connector", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.get_git_repository_link", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "GetAccountConnector", + "rpcName": "GetGitRepositoryLink", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetConnection( - _BaseDeveloperConnectRestTransport._BaseGetConnection, DeveloperConnectRestStub + class _ListAccountConnectors( + _BaseDeveloperConnectRestTransport._BaseListAccountConnectors, + DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.GetConnection") + return hash("DeveloperConnectRestTransport.ListAccountConnectors") @staticmethod def _get_response( @@ -4477,17 +6634,18 @@ def _get_response( def __call__( self, - request: developer_connect.GetConnectionRequest, + request: developer_connect.ListAccountConnectorsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.Connection: - r"""Call the get connection method over HTTP. + ) -> developer_connect.ListAccountConnectorsResponse: + r"""Call the list account connectors method over HTTP. Args: - request (~.developer_connect.GetConnectionRequest): - The request object. Message for getting a Connection + request (~.developer_connect.ListAccountConnectorsRequest): + The request object. Message for requesting list of + AccountConnectors retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4497,18 +6655,22 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.Connection: - Message describing Connection object + ~.developer_connect.ListAccountConnectorsResponse: + Message for response to listing + AccountConnectors + """ - http_options = _BaseDeveloperConnectRestTransport._BaseGetConnection._get_http_options() - request, metadata = self._interceptor.pre_get_connection(request, metadata) + http_options = _BaseDeveloperConnectRestTransport._BaseListAccountConnectors._get_http_options() + request, metadata = self._interceptor.pre_list_account_connectors( + request, metadata + ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseGetConnection, - "_BaseGetConnection__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseListAccountConnectors, + "_BaseListAccountConnectors__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4532,23 +6694,25 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.GetConnection", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.ListAccountConnectors", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "GetConnection", + "rpcName": "ListAccountConnectors", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._GetConnection._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, + response = ( + DeveloperConnectRestTransport._ListAccountConnectors._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4557,21 +6721,25 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.Connection() - pb_resp = developer_connect.Connection.pb(resp) + resp = developer_connect.ListAccountConnectorsResponse() + pb_resp = developer_connect.ListAccountConnectorsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_connection(resp) + resp = self._interceptor.post_list_account_connectors(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_connection_with_metadata( + resp, _ = self._interceptor.post_list_account_connectors_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = developer_connect.Connection.to_json(response) + response_payload = ( + developer_connect.ListAccountConnectorsResponse.to_json( + response + ) + ) except: response_payload = None http_response = { @@ -4580,22 +6748,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.get_connection", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.list_account_connectors", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "GetConnection", + "rpcName": "ListAccountConnectors", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetGitRepositoryLink( - _BaseDeveloperConnectRestTransport._BaseGetGitRepositoryLink, + class _ListConnections( + _BaseDeveloperConnectRestTransport._BaseListConnections, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.GetGitRepositoryLink") + return hash("DeveloperConnectRestTransport.ListConnections") @staticmethod def _get_response( @@ -4621,18 +6789,18 @@ def _get_response( def __call__( self, - request: developer_connect.GetGitRepositoryLinkRequest, + request: developer_connect.ListConnectionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.GitRepositoryLink: - r"""Call the get git repository link method over HTTP. + ) -> developer_connect.ListConnectionsResponse: + r"""Call the list connections method over HTTP. Args: - request (~.developer_connect.GetGitRepositoryLinkRequest): - The request object. Message for getting a - GitRepositoryLink + request (~.developer_connect.ListConnectionsRequest): + The request object. Message for requesting list of + Connections retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4642,22 +6810,22 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.GitRepositoryLink: - Message describing the - GitRepositoryLink object + ~.developer_connect.ListConnectionsResponse: + Message for response to listing + Connections """ - http_options = _BaseDeveloperConnectRestTransport._BaseGetGitRepositoryLink._get_http_options() - request, metadata = self._interceptor.pre_get_git_repository_link( + http_options = _BaseDeveloperConnectRestTransport._BaseListConnections._get_http_options() + request, metadata = self._interceptor.pre_list_connections( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseGetGitRepositoryLink, - "_BaseGetGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseListConnections, + "_BaseListConnections__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4681,25 +6849,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.GetGitRepositoryLink", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.ListConnections", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "GetGitRepositoryLink", + "rpcName": "ListConnections", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - DeveloperConnectRestTransport._GetGitRepositoryLink._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = DeveloperConnectRestTransport._ListConnections._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -4708,22 +6874,22 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.GitRepositoryLink() - pb_resp = developer_connect.GitRepositoryLink.pb(resp) + resp = developer_connect.ListConnectionsResponse() + pb_resp = developer_connect.ListConnectionsResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_git_repository_link(resp) + resp = self._interceptor.post_list_connections(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_git_repository_link_with_metadata( + resp, _ = self._interceptor.post_list_connections_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = developer_connect.GitRepositoryLink.to_json( - response + response_payload = ( + developer_connect.ListConnectionsResponse.to_json(response) ) except: response_payload = None @@ -4733,22 +6899,22 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.get_git_repository_link", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.list_connections", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "GetGitRepositoryLink", + "rpcName": "ListConnections", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListAccountConnectors( - _BaseDeveloperConnectRestTransport._BaseListAccountConnectors, + class _ListGitRepositoryLinks( + _BaseDeveloperConnectRestTransport._BaseListGitRepositoryLinks, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.ListAccountConnectors") + return hash("DeveloperConnectRestTransport.ListGitRepositoryLinks") @staticmethod def _get_response( @@ -4774,18 +6940,18 @@ def _get_response( def __call__( self, - request: developer_connect.ListAccountConnectorsRequest, + request: developer_connect.ListGitRepositoryLinksRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.ListAccountConnectorsResponse: - r"""Call the list account connectors method over HTTP. + ) -> developer_connect.ListGitRepositoryLinksResponse: + r"""Call the list git repository links method over HTTP. Args: - request (~.developer_connect.ListAccountConnectorsRequest): - The request object. Message for requesting list of - AccountConnectors + request (~.developer_connect.ListGitRepositoryLinksRequest): + The request object. Message for requesting a list of + GitRepositoryLinks retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4795,22 +6961,22 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.ListAccountConnectorsResponse: + ~.developer_connect.ListGitRepositoryLinksResponse: Message for response to listing - AccountConnectors + GitRepositoryLinks """ - http_options = _BaseDeveloperConnectRestTransport._BaseListAccountConnectors._get_http_options() - request, metadata = self._interceptor.pre_list_account_connectors( + http_options = _BaseDeveloperConnectRestTransport._BaseListGitRepositoryLinks._get_http_options() + request, metadata = self._interceptor.pre_list_git_repository_links( request, metadata ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseListAccountConnectors, - "_BaseListAccountConnectors__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseListGitRepositoryLinks, + "_BaseListGitRepositoryLinks__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4834,10 +7000,10 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.ListAccountConnectors", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.ListGitRepositoryLinks", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "ListAccountConnectors", + "rpcName": "ListGitRepositoryLinks", "httpRequest": http_request, "metadata": http_request["headers"], }, @@ -4845,7 +7011,7 @@ def __call__( # Send the request response = ( - DeveloperConnectRestTransport._ListAccountConnectors._get_response( + DeveloperConnectRestTransport._ListGitRepositoryLinks._get_response( self._host, metadata, query_params, @@ -4861,14 +7027,14 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.ListAccountConnectorsResponse() - pb_resp = developer_connect.ListAccountConnectorsResponse.pb(resp) + resp = developer_connect.ListGitRepositoryLinksResponse() + pb_resp = developer_connect.ListGitRepositoryLinksResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_account_connectors(resp) + resp = self._interceptor.post_list_git_repository_links(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_account_connectors_with_metadata( + resp, _ = self._interceptor.post_list_git_repository_links_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -4876,7 +7042,7 @@ def __call__( ): # pragma: NO COVER try: response_payload = ( - developer_connect.ListAccountConnectorsResponse.to_json( + developer_connect.ListGitRepositoryLinksResponse.to_json( response ) ) @@ -4888,22 +7054,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.list_account_connectors", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.list_git_repository_links", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "ListAccountConnectors", + "rpcName": "ListGitRepositoryLinks", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListConnections( - _BaseDeveloperConnectRestTransport._BaseListConnections, - DeveloperConnectRestStub, + class _ListUsers( + _BaseDeveloperConnectRestTransport._BaseListUsers, DeveloperConnectRestStub ): def __hash__(self): - return hash("DeveloperConnectRestTransport.ListConnections") + return hash("DeveloperConnectRestTransport.ListUsers") @staticmethod def _get_response( @@ -4929,18 +7094,18 @@ def _get_response( def __call__( self, - request: developer_connect.ListConnectionsRequest, + request: developer_connect.ListUsersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.ListConnectionsResponse: - r"""Call the list connections method over HTTP. + ) -> developer_connect.ListUsersResponse: + r"""Call the list users method over HTTP. Args: - request (~.developer_connect.ListConnectionsRequest): - The request object. Message for requesting list of - Connections + request (~.developer_connect.ListUsersRequest): + The request object. Message for requesting a list of + Users retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -4950,22 +7115,20 @@ def __call__( be of type `bytes`. Returns: - ~.developer_connect.ListConnectionsResponse: - Message for response to listing - Connections - + ~.developer_connect.ListUsersResponse: + Message for response to listing Users """ - http_options = _BaseDeveloperConnectRestTransport._BaseListConnections._get_http_options() - request, metadata = self._interceptor.pre_list_connections( - request, metadata + http_options = ( + _BaseDeveloperConnectRestTransport._BaseListUsers._get_http_options() ) + request, metadata = self._interceptor.pre_list_users(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseListConnections, - "_BaseListConnections__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseListUsers, + "_BaseListUsers__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -4989,17 +7152,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.ListConnections", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.ListUsers", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "ListConnections", + "rpcName": "ListUsers", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._ListConnections._get_response( + response = DeveloperConnectRestTransport._ListUsers._get_response( self._host, metadata, query_params, @@ -5014,22 +7177,22 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.ListConnectionsResponse() - pb_resp = developer_connect.ListConnectionsResponse.pb(resp) + resp = developer_connect.ListUsersResponse() + pb_resp = developer_connect.ListUsersResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_connections(resp) + resp = self._interceptor.post_list_users(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_connections_with_metadata( + resp, _ = self._interceptor.post_list_users_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - developer_connect.ListConnectionsResponse.to_json(response) + response_payload = developer_connect.ListUsersResponse.to_json( + response ) except: response_payload = None @@ -5039,22 +7202,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.list_connections", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.list_users", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "ListConnections", + "rpcName": "ListUsers", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListGitRepositoryLinks( - _BaseDeveloperConnectRestTransport._BaseListGitRepositoryLinks, + class _ModifyGitRepositoryLinkPullRequest( + _BaseDeveloperConnectRestTransport._BaseModifyGitRepositoryLinkPullRequest, DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.ListGitRepositoryLinks") + return hash( + "DeveloperConnectRestTransport.ModifyGitRepositoryLinkPullRequest" + ) @staticmethod def _get_response( @@ -5075,48 +7240,52 @@ 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: developer_connect.ListGitRepositoryLinksRequest, + request: developer_connect.ModifyGitRepositoryLinkPullRequestRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.ListGitRepositoryLinksResponse: - r"""Call the list git repository links method over HTTP. + ) -> developer_connect.PullRequest: + r"""Call the modify git repository + link pull request method over HTTP. - Args: - request (~.developer_connect.ListGitRepositoryLinksRequest): - The request object. Message for requesting a list of - GitRepositoryLinks - 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 (~.developer_connect.ModifyGitRepositoryLinkPullRequestRequest): + The request object. Message for modifying SCM Pull + Request. + 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: - ~.developer_connect.ListGitRepositoryLinksResponse: - Message for response to listing - GitRepositoryLinks + Returns: + ~.developer_connect.PullRequest: + Message representing a SCM Pull + Request. """ - http_options = _BaseDeveloperConnectRestTransport._BaseListGitRepositoryLinks._get_http_options() - request, metadata = self._interceptor.pre_list_git_repository_links( - request, metadata + http_options = _BaseDeveloperConnectRestTransport._BaseModifyGitRepositoryLinkPullRequest._get_http_options() + request, metadata = ( + self._interceptor.pre_modify_git_repository_link_pull_request( + request, metadata + ) ) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseListGitRepositoryLinks, - "_BaseListGitRepositoryLinks__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseModifyGitRepositoryLinkPullRequest, + "_BaseModifyGitRepositoryLinkPullRequest__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5140,25 +7309,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.ListGitRepositoryLinks", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.ModifyGitRepositoryLinkPullRequest", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "ListGitRepositoryLinks", + "rpcName": "ModifyGitRepositoryLinkPullRequest", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = ( - DeveloperConnectRestTransport._ListGitRepositoryLinks._get_response( - self._host, - metadata, - query_params, - self._session, - timeout, - transcoded_request, - ) + response = DeveloperConnectRestTransport._ModifyGitRepositoryLinkPullRequest._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -5167,25 +7335,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.ListGitRepositoryLinksResponse() - pb_resp = developer_connect.ListGitRepositoryLinksResponse.pb(resp) + resp = developer_connect.PullRequest() + pb_resp = developer_connect.PullRequest.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_git_repository_links(resp) + resp = self._interceptor.post_modify_git_repository_link_pull_request(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_git_repository_links_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_modify_git_repository_link_pull_request_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - developer_connect.ListGitRepositoryLinksResponse.to_json( - response - ) - ) + response_payload = developer_connect.PullRequest.to_json(response) except: response_payload = None http_response = { @@ -5194,21 +7360,24 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.list_git_repository_links", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.modify_git_repository_link_pull_request", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "ListGitRepositoryLinks", + "rpcName": "ModifyGitRepositoryLinkPullRequest", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListUsers( - _BaseDeveloperConnectRestTransport._BaseListUsers, DeveloperConnectRestStub + class _OpenGitRepositoryLinkPullRequest( + _BaseDeveloperConnectRestTransport._BaseOpenGitRepositoryLinkPullRequest, + DeveloperConnectRestStub, ): def __hash__(self): - return hash("DeveloperConnectRestTransport.ListUsers") + return hash( + "DeveloperConnectRestTransport.OpenGitRepositoryLinkPullRequest" + ) @staticmethod def _get_response( @@ -5229,46 +7398,51 @@ 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: developer_connect.ListUsersRequest, + request: developer_connect.OpenGitRepositoryLinkPullRequestRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> developer_connect.ListUsersResponse: - r"""Call the list users method over HTTP. + ) -> developer_connect.PullRequest: + r"""Call the open git repository link + pull request method over HTTP. - Args: - request (~.developer_connect.ListUsersRequest): - The request object. Message for requesting a list of - Users - 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 (~.developer_connect.OpenGitRepositoryLinkPullRequestRequest): + The request object. Message for opening SCM Pull Request. + 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: + ~.developer_connect.PullRequest: + Message representing a SCM Pull + Request. - Returns: - ~.developer_connect.ListUsersResponse: - Message for response to listing Users """ - http_options = ( - _BaseDeveloperConnectRestTransport._BaseListUsers._get_http_options() + http_options = _BaseDeveloperConnectRestTransport._BaseOpenGitRepositoryLinkPullRequest._get_http_options() + request, metadata = ( + self._interceptor.pre_open_git_repository_link_pull_request( + request, metadata + ) ) - request, metadata = self._interceptor.pre_list_users(request, metadata) transcoded_request, body, query_params = transcode_request( http_options, request, required_fields_default_values=getattr( - _BaseDeveloperConnectRestTransport._BaseListUsers, - "_BaseListUsers__REQUIRED_FIELDS_DEFAULT_VALUES", + _BaseDeveloperConnectRestTransport._BaseOpenGitRepositoryLinkPullRequest, + "_BaseOpenGitRepositoryLinkPullRequest__REQUIRED_FIELDS_DEFAULT_VALUES", None, ), rest_numeric_enums=True, @@ -5292,23 +7466,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.ListUsers", + f"Sending request for google.cloud.developerconnect_v1.DeveloperConnectClient.OpenGitRepositoryLinkPullRequest", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "ListUsers", + "rpcName": "OpenGitRepositoryLinkPullRequest", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = DeveloperConnectRestTransport._ListUsers._get_response( + response = DeveloperConnectRestTransport._OpenGitRepositoryLinkPullRequest._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -5317,23 +7492,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = developer_connect.ListUsersResponse() - pb_resp = developer_connect.ListUsersResponse.pb(resp) + resp = developer_connect.PullRequest() + pb_resp = developer_connect.PullRequest.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_users(resp) + resp = self._interceptor.post_open_git_repository_link_pull_request(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_users_with_metadata( - resp, response_metadata + resp, _ = ( + self._interceptor.post_open_git_repository_link_pull_request_with_metadata( + resp, response_metadata + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = developer_connect.ListUsersResponse.to_json( - response - ) + response_payload = developer_connect.PullRequest.to_json(response) except: response_payload = None http_response = { @@ -5342,10 +7517,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.list_users", + "Received response for google.cloud.developerconnect_v1.DeveloperConnectClient.open_git_repository_link_pull_request", extra={ "serviceName": "google.cloud.developerconnect.v1.DeveloperConnect", - "rpcName": "ListUsers", + "rpcName": "OpenGitRepositoryLinkPullRequest", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -5802,6 +7977,32 @@ def __call__( ) return resp + @property + def add_git_repository_link_pull_request_comment( + self, + ) -> Callable[ + [developer_connect.AddGitRepositoryLinkPullRequestCommentRequest], + developer_connect.PullRequestComment, + ]: + # 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._AddGitRepositoryLinkPullRequestComment( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def add_git_repository_link_pull_request_review_comment( + self, + ) -> Callable[ + [developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest], + developer_connect.PullRequestReviewComment, + ]: + # 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._AddGitRepositoryLinkPullRequestReviewComment( + self._session, self._host, self._interceptor + ) # type: ignore + @property def create_account_connector( self, @@ -5886,6 +8087,19 @@ def delete_user( # In C++ this would require a dynamic_cast return self._DeleteUser(self._session, self._host, self._interceptor) # type: ignore + @property + def diff_git_repository_link_commit( + self, + ) -> Callable[ + [developer_connect.DiffGitRepositoryLinkCommitRequest], + developer_connect.DiffGitRepositoryLinkCommitResponse, + ]: + # 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._DiffGitRepositoryLinkCommit( + self._session, self._host, self._interceptor + ) # type: ignore + @property def fetch_access_token( self, @@ -5920,6 +8134,71 @@ def fetch_git_refs( # In C++ this would require a dynamic_cast return self._FetchGitRefs(self._session, self._host, self._interceptor) # type: ignore + @property + def fetch_git_repository_link_commit( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkCommitRequest], + developer_connect.FetchGitRepositoryLinkCommitResponse, + ]: + # 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._FetchGitRepositoryLinkCommit( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def fetch_git_repository_link_commit_list( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkCommitListRequest], + developer_connect.FetchGitRepositoryLinkCommitListResponse, + ]: + # 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._FetchGitRepositoryLinkCommitList( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def fetch_git_repository_link_file_blame( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkFileBlameRequest], + developer_connect.FetchGitRepositoryLinkFileBlameResponse, + ]: + # 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._FetchGitRepositoryLinkFileBlame( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def fetch_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkPullRequestRequest], + developer_connect.PullRequest, + ]: + # 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._FetchGitRepositoryLinkPullRequest( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def fetch_git_repository_link_pull_request_list( + self, + ) -> Callable[ + [developer_connect.FetchGitRepositoryLinkPullRequestListRequest], + developer_connect.FetchGitRepositoryLinkPullRequestListResponse, + ]: + # 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._FetchGitRepositoryLinkPullRequestList( + self._session, self._host, self._interceptor + ) # type: ignore + @property def fetch_linkable_git_repositories( self, @@ -6050,6 +8329,32 @@ def list_users( # In C++ this would require a dynamic_cast return self._ListUsers(self._session, self._host, self._interceptor) # type: ignore + @property + def modify_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.ModifyGitRepositoryLinkPullRequestRequest], + developer_connect.PullRequest, + ]: + # 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._ModifyGitRepositoryLinkPullRequest( + self._session, self._host, self._interceptor + ) # type: ignore + + @property + def open_git_repository_link_pull_request( + self, + ) -> Callable[ + [developer_connect.OpenGitRepositoryLinkPullRequestRequest], + developer_connect.PullRequest, + ]: + # 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._OpenGitRepositoryLinkPullRequest( + self._session, self._host, self._interceptor + ) # type: ignore + @property def start_o_auth( self, diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/rest_base.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/rest_base.py index da169baed09e..b33c42be4de6 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/rest_base.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/services/developer_connect/transports/rest_base.py @@ -89,6 +89,40 @@ def __init__( api_audience=api_audience, ) + class _BaseAddGitRepositoryLinkPullRequestComment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:addPullRequestComment", + "body": "*", + }, + ] + return http_options + + class _BaseAddGitRepositoryLinkPullRequestReviewComment: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:addPullRequestReviewComment", + "body": "*", + }, + ] + return http_options + class _BaseCreateAccountConnector: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -226,6 +260,25 @@ def _get_http_options(): ] return http_options + class _BaseDiffGitRepositoryLinkCommit: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "baseSha": "", + "headSha": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:diffCommit", + }, + ] + return http_options + class _BaseFetchAccessToken: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -277,6 +330,93 @@ def _get_http_options(): ] return http_options + class _BaseFetchGitRepositoryLinkCommit: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "commitSha": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchCommit", + }, + ] + return http_options + + class _BaseFetchGitRepositoryLinkCommitList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchCommitList", + }, + ] + return http_options + + class _BaseFetchGitRepositoryLinkFileBlame: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "ref": "", + "path": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchFileBlame", + }, + ] + return http_options + + class _BaseFetchGitRepositoryLinkPullRequest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "pullRequestId": "", + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchPullRequest", + }, + ] + return http_options + + class _BaseFetchGitRepositoryLinkPullRequestList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchPullRequestList", + }, + ] + return http_options + class _BaseFetchLinkableGitRepositories: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -471,6 +611,40 @@ def _get_http_options(): ] return http_options + class _BaseModifyGitRepositoryLinkPullRequest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:modifyPullRequest", + "body": "*", + }, + ] + return http_options + + class _BaseOpenGitRepositoryLinkPullRequest: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:openPullRequest", + "body": "*", + }, + ] + return http_options + class _BaseStartOAuth: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/types/__init__.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/types/__init__.py index c67f4b9678e9..3851947d721c 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/types/__init__.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/types/__init__.py @@ -15,8 +15,12 @@ # from .developer_connect import ( AccountConnector, + AddGitRepositoryLinkPullRequestCommentRequest, + AddGitRepositoryLinkPullRequestReviewCommentRequest, BitbucketCloudConfig, BitbucketDataCenterConfig, + BlameRange, + CommitView, Connection, CreateAccountConnectorRequest, CreateConnectionRequest, @@ -27,6 +31,8 @@ DeleteGitRepositoryLinkRequest, DeleteSelfRequest, DeleteUserRequest, + DiffGitRepositoryLinkCommitRequest, + DiffGitRepositoryLinkCommitResponse, ExchangeError, FetchAccessTokenRequest, FetchAccessTokenResponse, @@ -34,6 +40,15 @@ FetchGitHubInstallationsResponse, FetchGitRefsRequest, FetchGitRefsResponse, + FetchGitRepositoryLinkCommitListRequest, + FetchGitRepositoryLinkCommitListResponse, + FetchGitRepositoryLinkCommitRequest, + FetchGitRepositoryLinkCommitResponse, + FetchGitRepositoryLinkFileBlameRequest, + FetchGitRepositoryLinkFileBlameResponse, + FetchGitRepositoryLinkPullRequestListRequest, + FetchGitRepositoryLinkPullRequestListResponse, + FetchGitRepositoryLinkPullRequestRequest, FetchLinkableGitRepositoriesRequest, FetchLinkableGitRepositoriesResponse, FetchReadTokenRequest, @@ -41,6 +56,7 @@ FetchReadWriteTokenRequest, FetchReadWriteTokenResponse, FetchSelfRequest, + FileDiff, FinishOAuthRequest, FinishOAuthResponse, GenericHTTPEndpointConfig, @@ -63,9 +79,15 @@ ListGitRepositoryLinksResponse, ListUsersRequest, ListUsersResponse, + ModifyGitRepositoryLinkPullRequestRequest, OAuthCredential, + OpenGitRepositoryLinkPullRequestRequest, OperationMetadata, ProviderOAuthConfig, + PullRequest, + PullRequestComment, + PullRequestReviewComment, + SCMCommit, SecureSourceManagerInstanceConfig, ServiceDirectoryConfig, StartOAuthRequest, @@ -102,8 +124,11 @@ __all__ = ( "AccountConnector", + "AddGitRepositoryLinkPullRequestCommentRequest", + "AddGitRepositoryLinkPullRequestReviewCommentRequest", "BitbucketCloudConfig", "BitbucketDataCenterConfig", + "BlameRange", "Connection", "CreateAccountConnectorRequest", "CreateConnectionRequest", @@ -114,6 +139,8 @@ "DeleteGitRepositoryLinkRequest", "DeleteSelfRequest", "DeleteUserRequest", + "DiffGitRepositoryLinkCommitRequest", + "DiffGitRepositoryLinkCommitResponse", "ExchangeError", "FetchAccessTokenRequest", "FetchAccessTokenResponse", @@ -121,6 +148,15 @@ "FetchGitHubInstallationsResponse", "FetchGitRefsRequest", "FetchGitRefsResponse", + "FetchGitRepositoryLinkCommitListRequest", + "FetchGitRepositoryLinkCommitListResponse", + "FetchGitRepositoryLinkCommitRequest", + "FetchGitRepositoryLinkCommitResponse", + "FetchGitRepositoryLinkFileBlameRequest", + "FetchGitRepositoryLinkFileBlameResponse", + "FetchGitRepositoryLinkPullRequestListRequest", + "FetchGitRepositoryLinkPullRequestListResponse", + "FetchGitRepositoryLinkPullRequestRequest", "FetchLinkableGitRepositoriesRequest", "FetchLinkableGitRepositoriesResponse", "FetchReadTokenRequest", @@ -128,6 +164,7 @@ "FetchReadWriteTokenRequest", "FetchReadWriteTokenResponse", "FetchSelfRequest", + "FileDiff", "FinishOAuthRequest", "FinishOAuthResponse", "GenericHTTPEndpointConfig", @@ -150,9 +187,15 @@ "ListGitRepositoryLinksResponse", "ListUsersRequest", "ListUsersResponse", + "ModifyGitRepositoryLinkPullRequestRequest", "OAuthCredential", + "OpenGitRepositoryLinkPullRequestRequest", "OperationMetadata", "ProviderOAuthConfig", + "PullRequest", + "PullRequestComment", + "PullRequestReviewComment", + "SCMCommit", "SecureSourceManagerInstanceConfig", "ServiceDirectoryConfig", "StartOAuthRequest", @@ -161,6 +204,7 @@ "UpdateConnectionRequest", "User", "UserCredential", + "CommitView", "SystemProvider", "AppHubService", "AppHubWorkload", diff --git a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/types/developer_connect.py b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/types/developer_connect.py index 0c23572ea781..e0bd048d31df 100644 --- a/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/types/developer_connect.py +++ b/packages/google-cloud-developerconnect/google/cloud/developerconnect_v1/types/developer_connect.py @@ -24,6 +24,7 @@ __protobuf__ = proto.module( package="google.cloud.developerconnect.v1", manifest={ + "CommitView", "SystemProvider", "ListUsersRequest", "ListUsersResponse", @@ -60,6 +61,9 @@ "DeleteSelfRequest", "FetchAccessTokenRequest", "FetchAccessTokenResponse", + "DiffGitRepositoryLinkCommitRequest", + "DiffGitRepositoryLinkCommitResponse", + "FileDiff", "StartOAuthRequest", "StartOAuthResponse", "FinishOAuthRequest", @@ -75,6 +79,7 @@ "FetchReadTokenRequest", "FetchReadTokenResponse", "FetchReadWriteTokenResponse", + "OpenGitRepositoryLinkPullRequestRequest", "FetchLinkableGitRepositoriesRequest", "FetchLinkableGitRepositoriesResponse", "LinkableGitRepository", @@ -82,6 +87,23 @@ "FetchGitHubInstallationsResponse", "FetchGitRefsRequest", "FetchGitRefsResponse", + "FetchGitRepositoryLinkCommitRequest", + "FetchGitRepositoryLinkCommitResponse", + "FetchGitRepositoryLinkCommitListRequest", + "FetchGitRepositoryLinkCommitListResponse", + "SCMCommit", + "FetchGitRepositoryLinkFileBlameRequest", + "BlameRange", + "FetchGitRepositoryLinkFileBlameResponse", + "FetchGitRepositoryLinkPullRequestRequest", + "PullRequest", + "PullRequestComment", + "AddGitRepositoryLinkPullRequestCommentRequest", + "PullRequestReviewComment", + "AddGitRepositoryLinkPullRequestReviewCommentRequest", + "ModifyGitRepositoryLinkPullRequestRequest", + "FetchGitRepositoryLinkPullRequestListRequest", + "FetchGitRepositoryLinkPullRequestListResponse", "AccountConnector", "User", "ProviderOAuthConfig", @@ -89,6 +111,25 @@ ) +class CommitView(proto.Enum): + r"""The level of commit details to return in the response. + + Values: + COMMIT_VIEW_UNSPECIFIED (0): + Unspecified, defaults to BASIC. + BASIC (1): + Basic view, returns commit metadata but no + file diffs. + FULL (2): + Full view, returns commit metadata and file + diffs. + """ + + COMMIT_VIEW_UNSPECIFIED = 0 + BASIC = 1 + FULL = 2 + + class SystemProvider(proto.Enum): r"""SystemProvider is a list of providers that are owned by Developer Connect. @@ -1873,6 +1914,90 @@ class FetchAccessTokenResponse(proto.Message): ) +class DiffGitRepositoryLinkCommitRequest(proto.Message): + r"""Request message for DiffGitRepositoryLinkCommit. + + Attributes: + name (str): + Required. The resource name of the + GitRepositoryLink. + base_sha (str): + Required. The base commit SHA or ref. + head_sha (str): + Required. The head commit SHA or ref. + path_filters (MutableSequence[str]): + Optional. Path patterns or exact paths to filter returned + files. When ``path_filters`` is specified, + ``FileDiff.patch`` is populated for all matching files (use + ``["**"]`` to include patches for all changed files). When + ``path_filters`` is omitted or empty, the full list of + ``FileDiff`` is returned without patch diffs + (``FileDiff.patch`` is empty). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + base_sha: str = proto.Field( + proto.STRING, + number=2, + ) + head_sha: str = proto.Field( + proto.STRING, + number=3, + ) + path_filters: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class DiffGitRepositoryLinkCommitResponse(proto.Message): + r"""Response message for DiffGitRepositoryLinkCommit. + + Attributes: + files (MutableSequence[google.cloud.developerconnect_v1.types.FileDiff]): + The file diff extracted from the unified + diff. + """ + + files: MutableSequence["FileDiff"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="FileDiff", + ) + + +class FileDiff(proto.Message): + r"""Message for a file diff. + + Attributes: + path (str): + Relative path to the file in the repository. + status (str): + Status of change: "ADDED", "MODIFIED", + "REMOVED", "RENAMED". + patch (str): + Standard unified diff patch hunk for the file. Only + populated when ``path_filters`` is specified in the request; + otherwise empty. + """ + + path: str = proto.Field( + proto.STRING, + number=1, + ) + status: str = proto.Field( + proto.STRING, + number=2, + ) + patch: str = proto.Field( + proto.STRING, + number=3, + ) + + class StartOAuthRequest(proto.Message): r"""Message for starting an OAuth flow. @@ -2476,6 +2601,29 @@ class FetchReadWriteTokenResponse(proto.Message): ) +class OpenGitRepositoryLinkPullRequestRequest(proto.Message): + r"""Message for opening SCM Pull Request. + + Attributes: + name (str): + Required. The GitRepositoryLink resource name in the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + pull_request (google.cloud.developerconnect_v1.types.PullRequest): + Required. The Pull Request details to open. Input fields + used: title, body, head_ref, base_ref. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + pull_request: "PullRequest" = proto.Field( + proto.MESSAGE, + number=2, + message="PullRequest", + ) + + class FetchLinkableGitRepositoriesRequest(proto.Message): r"""Request message for FetchLinkableGitRepositoriesRequest. @@ -2683,6 +2831,813 @@ def raw_page(self): ) +class FetchGitRepositoryLinkCommitRequest(proto.Message): + r"""Request message for FetchGitRepositoryLinkCommit. + + Attributes: + name (str): + Required. The resource name of the GitRepositoryLink in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + commit_sha (str): + Required. The commit SHA, or symbolic + revision (e.g., branch name, tag, or Git + reference). + view (google.cloud.developerconnect_v1.types.CommitView): + Optional. The level of commit details to return in the + response. Defaults to ``FULL`` if unspecified. In ``FULL`` + view, ``files`` metadata (paths and statuses) are returned; + ``path_filters`` must also be specified to populate line + patch hunks. + path_filters (MutableSequence[str]): + Optional. Path patterns or exact paths to filter returned + files (only applicable in ``FULL`` view). When + ``path_filters`` is specified, ``FileDiff.patch`` is + populated for all matching files (use ``["**"]`` to include + patches for all changed files). When ``path_filters`` is + omitted or empty, the full list of ``FileDiff`` is returned + without patch diffs (``FileDiff.patch`` is empty). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + commit_sha: str = proto.Field( + proto.STRING, + number=2, + ) + view: "CommitView" = proto.Field( + proto.ENUM, + number=3, + enum="CommitView", + ) + path_filters: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class FetchGitRepositoryLinkCommitResponse(proto.Message): + r"""Response message for FetchGitRepositoryLinkCommit. + + Attributes: + commit (google.cloud.developerconnect_v1.types.SCMCommit): + The commit metadata. + files (MutableSequence[google.cloud.developerconnect_v1.types.FileDiff]): + List of file changes and patch diffs. Omitted when view is + ``BASIC``. Patch diffs (``FileDiff.patch``) are only + populated when ``path_filters`` is specified in the request. + """ + + commit: "SCMCommit" = proto.Field( + proto.MESSAGE, + number=1, + message="SCMCommit", + ) + files: MutableSequence["FileDiff"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="FileDiff", + ) + + +class FetchGitRepositoryLinkCommitListRequest(proto.Message): + r"""Request message for FetchGitRepositoryLinkCommitList. + + Attributes: + name (str): + Required. The resource name of the GitRepositoryLink in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + ref (str): + Optional. The commit SHA, or symbolic + revision (e.g., branch name, tag, or Git + reference) from which to start listing commits. + page_size (int): + Optional. Number of results to return in the + list. Default is 50. Max is 100. + page_token (str): + Optional. A page token, received from a previous + ``FetchGitRepositoryLinkCommitList`` call. Provide this to + retrieve the subsequent page. + + When paginating, all other parameters provided to + ``FetchGitRepositoryLinkCommitList`` must match the call + that provided the page token. + view (google.cloud.developerconnect_v1.types.CommitView): + Optional. The level of commit details to return in the + response. Only ``BASIC`` is supported; ``FULL`` returns + ``INVALID_ARGUMENT``. Defaults to ``BASIC`` if unspecified. + Use ``FetchGitRepositoryLinkCommit`` to get file diffs for a + single commit. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ref: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + view: "CommitView" = proto.Field( + proto.ENUM, + number=5, + enum="CommitView", + ) + + +class FetchGitRepositoryLinkCommitListResponse(proto.Message): + r"""Response message for FetchGitRepositoryLinkCommitList. + + Attributes: + commits (MutableSequence[google.cloud.developerconnect_v1.types.SCMCommit]): + The list of commit metadata. + 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. + """ + + @property + def raw_page(self): + return self + + commits: MutableSequence["SCMCommit"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SCMCommit", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SCMCommit(proto.Message): + r"""SCMCommit represents commit metadata. + + Attributes: + sha (str): + Full 40-character SCM commit SHA. + message (str): + Commit message text. + author (str): + The author's display name. + author_email (str): + The author's email address. + commit_time (google.protobuf.timestamp_pb2.Timestamp): + Timestamp when the commit was authored. + url (str): + The SCM provider's HTML URL link for this + commit. + """ + + sha: str = proto.Field( + proto.STRING, + number=1, + ) + message: str = proto.Field( + proto.STRING, + number=2, + ) + author: str = proto.Field( + proto.STRING, + number=3, + ) + author_email: str = proto.Field( + proto.STRING, + number=4, + ) + commit_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + url: str = proto.Field( + proto.STRING, + number=6, + ) + + +class FetchGitRepositoryLinkFileBlameRequest(proto.Message): + r"""Request message for FetchGitRepositoryLinkFileBlame. + + Attributes: + name (str): + Required. The resource name of the GitRepositoryLink in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + ref (str): + Required. The SCM commit SHA, or symbolic + revision (e.g., branch name, tag) from which to + fetch the blame. + path (str): + Required. The file path within the + repository. + first_line (int): + Optional. The 1-indexed starting line number + of the range to blame (inclusive). If not + specified, blame begins at line 1. + last_line (int): + Optional. The 1-indexed ending line number of + the range to blame (inclusive). If not + specified, blame extends to the end of the file. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ref: str = proto.Field( + proto.STRING, + number=2, + ) + path: str = proto.Field( + proto.STRING, + number=3, + ) + first_line: int = proto.Field( + proto.INT32, + number=4, + ) + last_line: int = proto.Field( + proto.INT32, + number=5, + ) + + +class BlameRange(proto.Message): + r"""BlameRange represents blame information for a range of lines. + + Attributes: + first_line (int): + The 1-indexed starting line number of the + range (inclusive). + last_line (int): + The 1-indexed ending line number of the range + (inclusive). + commit (google.cloud.developerconnect_v1.types.SCMCommit): + The commit metadata for this line range. + """ + + first_line: int = proto.Field( + proto.INT32, + number=1, + ) + last_line: int = proto.Field( + proto.INT32, + number=2, + ) + commit: "SCMCommit" = proto.Field( + proto.MESSAGE, + number=3, + message="SCMCommit", + ) + + +class FetchGitRepositoryLinkFileBlameResponse(proto.Message): + r"""Response message for FetchGitRepositoryLinkFileBlame. + + Attributes: + ranges (MutableSequence[google.cloud.developerconnect_v1.types.BlameRange]): + The list of blame ranges for the file. + """ + + ranges: MutableSequence["BlameRange"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BlameRange", + ) + + +class FetchGitRepositoryLinkPullRequestRequest(proto.Message): + r"""Request message for FetchGitRepositoryLinkPullRequest. + + Attributes: + name (str): + Required. The resource name of the GitRepositoryLink in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + pull_request_id (str): + Required. The ID of the Pull Request. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + pull_request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class PullRequest(proto.Message): + r"""Message representing a SCM Pull Request. + + Attributes: + id (str): + Required. The ID of the PR. + title (str): + Required. The title of the PR. + body (str): + Optional. The body description of the PR. + head_ref (str): + Required. The source commit SHA of the head + branch. + base_ref (str): + Required. The target commit SHA of the base + branch. + author (str): + Output only. The username of the author. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the PR was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the PR was updated. + merge_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the PR was merged. + close_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the PR was closed. + decline_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the PR was declined. Only set for SCM + providers that support declining pull requests. Never set + for GitHub, GitHub Enterprise, GitLab, or GitLab Enterprise, + where a pull request closed without being merged is + ``CLOSED``. + state (google.cloud.developerconnect_v1.types.PullRequest.State): + Output only. The current state of the PR. + mergeability (google.cloud.developerconnect_v1.types.PullRequest.Mergeability): + Output only. The mergeability state of the + pull request. + html_url (str): + Output only. The HTML URL of the pull request + on the SCM provider. + """ + + class State(proto.Enum): + r"""The state of the PR. + + Values: + STATE_UNSPECIFIED (0): + Default value. + OPEN (1): + The PR is open. + CLOSED (2): + The PR is closed. + MERGED (3): + The PR is merged. + DECLINED (4): + The PR is declined. Only used by SCM providers that support + declining pull requests. Never used for GitHub, GitHub + Enterprise, GitLab, or GitLab Enterprise, where a pull + request closed without being merged is ``CLOSED``. + """ + + STATE_UNSPECIFIED = 0 + OPEN = 1 + CLOSED = 2 + MERGED = 3 + DECLINED = 4 + + class Mergeability(proto.Enum): + r"""The mergeability state of a pull request. + + Values: + MERGEABILITY_UNSPECIFIED (0): + Mergeability state is unspecified. + MERGEABLE (1): + The pull request can be merged cleanly + without Git conflicts. + CONFLICTING (2): + The pull request has merge conflicts and + cannot be merged cleanly. + COMPUTING (3): + The mergeability state is currently being + computed asynchronously by the upstream SCM + provider. + """ + + MERGEABILITY_UNSPECIFIED = 0 + MERGEABLE = 1 + CONFLICTING = 2 + COMPUTING = 3 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + title: str = proto.Field( + proto.STRING, + number=2, + ) + body: str = proto.Field( + proto.STRING, + number=3, + ) + head_ref: str = proto.Field( + proto.STRING, + number=4, + ) + base_ref: str = proto.Field( + proto.STRING, + number=5, + ) + author: str = proto.Field( + proto.STRING, + number=6, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + merge_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + close_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=10, + message=timestamp_pb2.Timestamp, + ) + decline_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=12, + enum=State, + ) + mergeability: Mergeability = proto.Field( + proto.ENUM, + number=13, + enum=Mergeability, + ) + html_url: str = proto.Field( + proto.STRING, + number=14, + ) + + +class PullRequestComment(proto.Message): + r"""Message representing a SCM Pull Request Comment. + + Attributes: + id (str): + Output only. The ID of the comment. + body (str): + Required. The body of the comment. + author (str): + Output only. The username of the author. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the comment was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the comment was updated. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + body: str = proto.Field( + proto.STRING, + number=2, + ) + author: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + + +class AddGitRepositoryLinkPullRequestCommentRequest(proto.Message): + r"""Request message for AddGitRepositoryLinkPullRequestComment. + + Attributes: + name (str): + Required. The resource name of the GitRepositoryLink in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + pull_request_id (str): + Required. The ID of the Pull Request. + comment (google.cloud.developerconnect_v1.types.PullRequestComment): + Required. The comment to add. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + pull_request_id: str = proto.Field( + proto.STRING, + number=2, + ) + comment: "PullRequestComment" = proto.Field( + proto.MESSAGE, + number=3, + message="PullRequestComment", + ) + + +class PullRequestReviewComment(proto.Message): + r"""Message representing a SCM Pull Request Review Comment + (inline on diff). + + Attributes: + id (str): + Output only. The ID of the comment. + body (str): + Required. The body of the comment. + path (str): + Required. The file path to comment on. + first_line (int): + Optional. The first line of the comment range (inclusive). + If not specified, the comment applies only to the + ``last_line``. + last_line (int): + Required. The last line of the comment range (inclusive). If + ``first_line`` is not specified, the comment applies only to + this line. + side (google.cloud.developerconnect_v1.types.PullRequestReviewComment.DiffSide): + Optional. The side of the diff to comment on. + Defaults to HEAD. + author (str): + Output only. The username of the author. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the comment was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the comment was updated. + commit_id (str): + Output only. The commit SHA the comment was + actually applied to. + """ + + class DiffSide(proto.Enum): + r"""DiffSide represents which side of the diff the comment is on. + + Values: + DIFF_SIDE_UNSPECIFIED (0): + Default value. This value is unused. + BASE (1): + The side of the diff before changes (deleted + or modified lines). + HEAD (2): + The side of the diff after changes (added or + modified lines). + """ + + DIFF_SIDE_UNSPECIFIED = 0 + BASE = 1 + HEAD = 2 + + id: str = proto.Field( + proto.STRING, + number=1, + ) + body: str = proto.Field( + proto.STRING, + number=2, + ) + path: str = proto.Field( + proto.STRING, + number=3, + ) + first_line: int = proto.Field( + proto.INT32, + number=4, + ) + last_line: int = proto.Field( + proto.INT32, + number=5, + ) + side: DiffSide = proto.Field( + proto.ENUM, + number=6, + enum=DiffSide, + ) + author: str = proto.Field( + proto.STRING, + number=7, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=9, + message=timestamp_pb2.Timestamp, + ) + commit_id: str = proto.Field( + proto.STRING, + number=10, + ) + + +class AddGitRepositoryLinkPullRequestReviewCommentRequest(proto.Message): + r"""Request message for + AddGitRepositoryLinkPullRequestReviewComment. + + Attributes: + name (str): + Required. The resource name of the GitRepositoryLink in the + format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + pull_request_id (str): + Required. The ID of the Pull Request. + comment (google.cloud.developerconnect_v1.types.PullRequestReviewComment): + Required. The review comment to add. + commit_id (str): + Optional. The commit SHA to comment on. If + not specified, defaults to the HEAD commit of + the Pull Request. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + pull_request_id: str = proto.Field( + proto.STRING, + number=2, + ) + comment: "PullRequestReviewComment" = proto.Field( + proto.MESSAGE, + number=3, + message="PullRequestReviewComment", + ) + commit_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ModifyGitRepositoryLinkPullRequestRequest(proto.Message): + r"""Message for modifying SCM Pull Request. + + Attributes: + name (str): + Required. The GitRepositoryLink resource name in the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + pull_request_id (str): + Required. The SCM-specific Pull Request + identifier (e.g., "45"). + title (str): + Optional. The title of the Pull Request. + body (str): + Optional. The body description of the Pull + Request. + base_ref (str): + Optional. The target branch to merge into. + state (google.cloud.developerconnect_v1.types.ModifyGitRepositoryLinkPullRequestRequest.State): + Optional. The state of the Pull Request. + """ + + class State(proto.Enum): + r"""State represents the state of the pull request. + + Values: + STATE_UNSPECIFIED (0): + Default value. This value is unused. + OPEN (1): + The pull request is open. + CLOSED (2): + The pull request is closed. + """ + + STATE_UNSPECIFIED = 0 + OPEN = 1 + CLOSED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + pull_request_id: str = proto.Field( + proto.STRING, + number=2, + ) + title: str = proto.Field( + proto.STRING, + number=3, + ) + body: str = proto.Field( + proto.STRING, + number=4, + ) + base_ref: str = proto.Field( + proto.STRING, + number=5, + ) + state: State = proto.Field( + proto.ENUM, + number=6, + enum=State, + ) + + +class FetchGitRepositoryLinkPullRequestListRequest(proto.Message): + r"""Request message for FetchGitRepositoryLinkPullRequestList. + + Attributes: + name (str): + Required. The GitRepositoryLink resource name in the format + ``projects/*/locations/*/connections/*/gitRepositoryLinks/*``. + filter (str): + Optional. A filter expression that filters the pull requests + returned in the response. Only a single equality comparison + on ``state`` is supported, for example ``state = "OPEN"``. + Supported values are ``OPEN``, ``CLOSED``, and ``MERGED``. + ``DECLINED`` is only supported for SCM providers that + support declining pull requests, and returns + ``INVALID_ARGUMENT`` for GitHub, GitHub Enterprise, GitLab, + and GitLab Enterprise. Other values or expressions return + ``INVALID_ARGUMENT``. Defaults to ``state = "OPEN"`` if + unspecified. + page_size (int): + Optional. Number of results to return in the list. Default + is 20. Max is 100. A page may contain fewer than + ``page_size`` results even when more results are available; + use ``next_page_token`` to check for more pages. + page_token (str): + Optional. A page token, received from a previous + ``FetchGitRepositoryLinkPullRequestList`` call. Provide this + to retrieve the subsequent page. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + filter: str = proto.Field( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + + +class FetchGitRepositoryLinkPullRequestListResponse(proto.Message): + r"""Response message for FetchGitRepositoryLinkPullRequestList. + + Attributes: + pull_requests (MutableSequence[google.cloud.developerconnect_v1.types.PullRequest]): + The list of Pull Requests. + 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. + """ + + @property + def raw_page(self): + return self + + pull_requests: MutableSequence["PullRequest"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="PullRequest", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + class AccountConnector(proto.Message): r"""AccountConnector encapsulates what a platform administrator needs to configure for users to connect to the service diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_async.py new file mode 100644 index 000000000000..5570447c0f03 --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_async.py @@ -0,0 +1,60 @@ +# -*- 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 AddGitRepositoryLinkPullRequestComment +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestComment_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 developerconnect_v1 + + +async def sample_add_git_repository_link_pull_request_comment(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + comment = developerconnect_v1.PullRequestComment() + comment.body = "body_value" + + request = developerconnect_v1.AddGitRepositoryLinkPullRequestCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", + comment=comment, + ) + + # Make the request + response = await client.add_git_repository_link_pull_request_comment( + request=request + ) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestComment_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_sync.py new file mode 100644 index 000000000000..2ae8ead87e3b --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_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 AddGitRepositoryLinkPullRequestComment +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestComment_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 developerconnect_v1 + + +def sample_add_git_repository_link_pull_request_comment(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + comment = developerconnect_v1.PullRequestComment() + comment.body = "body_value" + + request = developerconnect_v1.AddGitRepositoryLinkPullRequestCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", + comment=comment, + ) + + # Make the request + response = client.add_git_repository_link_pull_request_comment(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestComment_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_async.py new file mode 100644 index 000000000000..b61c87f63f4b --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_async.py @@ -0,0 +1,62 @@ +# -*- 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 AddGitRepositoryLinkPullRequestReviewComment +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestReviewComment_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 developerconnect_v1 + + +async def sample_add_git_repository_link_pull_request_review_comment(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + comment = developerconnect_v1.PullRequestReviewComment() + comment.body = "body_value" + comment.path = "path_value" + comment.last_line = 955 + + request = developerconnect_v1.AddGitRepositoryLinkPullRequestReviewCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", + comment=comment, + ) + + # Make the request + response = await client.add_git_repository_link_pull_request_review_comment( + request=request + ) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestReviewComment_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_sync.py new file mode 100644 index 000000000000..f9f93c7ac8e0 --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_sync.py @@ -0,0 +1,62 @@ +# -*- 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 AddGitRepositoryLinkPullRequestReviewComment +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestReviewComment_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 developerconnect_v1 + + +def sample_add_git_repository_link_pull_request_review_comment(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + comment = developerconnect_v1.PullRequestReviewComment() + comment.body = "body_value" + comment.path = "path_value" + comment.last_line = 955 + + request = developerconnect_v1.AddGitRepositoryLinkPullRequestReviewCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", + comment=comment, + ) + + # Make the request + response = client.add_git_repository_link_pull_request_review_comment( + request=request + ) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestReviewComment_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_async.py new file mode 100644 index 000000000000..8ea99dfa3d8a --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_async.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 DiffGitRepositoryLinkCommit +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_DiffGitRepositoryLinkCommit_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 developerconnect_v1 + + +async def sample_diff_git_repository_link_commit(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.DiffGitRepositoryLinkCommitRequest( + name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", + ) + + # Make the request + response = await client.diff_git_repository_link_commit(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_DiffGitRepositoryLinkCommit_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_sync.py new file mode 100644 index 000000000000..b1e19f42aeba --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_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 DiffGitRepositoryLinkCommit +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_DiffGitRepositoryLinkCommit_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 developerconnect_v1 + + +def sample_diff_git_repository_link_commit(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.DiffGitRepositoryLinkCommitRequest( + name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", + ) + + # Make the request + response = client.diff_git_repository_link_commit(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_DiffGitRepositoryLinkCommit_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_async.py new file mode 100644 index 000000000000..85ce446275ab --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_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 FetchGitRepositoryLinkCommit +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommit_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 developerconnect_v1 + + +async def sample_fetch_git_repository_link_commit(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkCommitRequest( + name="name_value", + commit_sha="commit_sha_value", + ) + + # Make the request + response = await client.fetch_git_repository_link_commit(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommit_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_list_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_list_async.py new file mode 100644 index 000000000000..73089f242c3d --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_list_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 FetchGitRepositoryLinkCommitList +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommitList_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 developerconnect_v1 + + +async def sample_fetch_git_repository_link_commit_list(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkCommitListRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_git_repository_link_commit_list(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommitList_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_list_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_list_sync.py new file mode 100644 index 000000000000..025d5f681651 --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_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 FetchGitRepositoryLinkCommitList +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommitList_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 developerconnect_v1 + + +def sample_fetch_git_repository_link_commit_list(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkCommitListRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_git_repository_link_commit_list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommitList_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_sync.py new file mode 100644 index 000000000000..7cecad29fd54 --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_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 FetchGitRepositoryLinkCommit +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommit_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 developerconnect_v1 + + +def sample_fetch_git_repository_link_commit(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkCommitRequest( + name="name_value", + commit_sha="commit_sha_value", + ) + + # Make the request + response = client.fetch_git_repository_link_commit(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommit_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_async.py new file mode 100644 index 000000000000..d4c1cf5e77ff --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_async.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 FetchGitRepositoryLinkFileBlame +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkFileBlame_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 developerconnect_v1 + + +async def sample_fetch_git_repository_link_file_blame(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkFileBlameRequest( + name="name_value", + ref="ref_value", + path="path_value", + ) + + # Make the request + response = await client.fetch_git_repository_link_file_blame(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkFileBlame_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_sync.py new file mode 100644 index 000000000000..c2397ab0a6db --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_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 FetchGitRepositoryLinkFileBlame +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkFileBlame_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 developerconnect_v1 + + +def sample_fetch_git_repository_link_file_blame(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkFileBlameRequest( + name="name_value", + ref="ref_value", + path="path_value", + ) + + # Make the request + response = client.fetch_git_repository_link_file_blame(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkFileBlame_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_async.py new file mode 100644 index 000000000000..b0b56f4afeb6 --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_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 FetchGitRepositoryLinkPullRequest +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequest_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 developerconnect_v1 + + +async def sample_fetch_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", + ) + + # Make the request + response = await client.fetch_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequest_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_list_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_list_async.py new file mode 100644 index 000000000000..a06044606bbd --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_list_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 FetchGitRepositoryLinkPullRequestList +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequestList_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 developerconnect_v1 + + +async def sample_fetch_git_repository_link_pull_request_list(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkPullRequestListRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_git_repository_link_pull_request_list(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequestList_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_list_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_list_sync.py new file mode 100644 index 000000000000..6623aa27b5ad --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_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 FetchGitRepositoryLinkPullRequestList +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequestList_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 developerconnect_v1 + + +def sample_fetch_git_repository_link_pull_request_list(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkPullRequestListRequest( + name="name_value", + ) + + # Make the request + page_result = client.fetch_git_repository_link_pull_request_list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequestList_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_sync.py new file mode 100644 index 000000000000..f15eb0b28736 --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_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 FetchGitRepositoryLinkPullRequest +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequest_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 developerconnect_v1 + + +def sample_fetch_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.FetchGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", + ) + + # Make the request + response = client.fetch_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequest_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_async.py new file mode 100644 index 000000000000..7ba466775dd1 --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_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 ModifyGitRepositoryLinkPullRequest +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_ModifyGitRepositoryLinkPullRequest_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 developerconnect_v1 + + +async def sample_modify_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + request = developerconnect_v1.ModifyGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", + ) + + # Make the request + response = await client.modify_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_ModifyGitRepositoryLinkPullRequest_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_sync.py new file mode 100644 index 000000000000..e60240e6d387 --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_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 ModifyGitRepositoryLinkPullRequest +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_ModifyGitRepositoryLinkPullRequest_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 developerconnect_v1 + + +def sample_modify_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + request = developerconnect_v1.ModifyGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", + ) + + # Make the request + response = client.modify_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_ModifyGitRepositoryLinkPullRequest_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_async.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_async.py new file mode 100644 index 000000000000..37d2ac51e938 --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_async.py @@ -0,0 +1,60 @@ +# -*- 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 OpenGitRepositoryLinkPullRequest +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_OpenGitRepositoryLinkPullRequest_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 developerconnect_v1 + + +async def sample_open_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectAsyncClient() + + # Initialize request argument(s) + pull_request = developerconnect_v1.PullRequest() + pull_request.id = "id_value" + pull_request.title = "title_value" + pull_request.head_ref = "head_ref_value" + pull_request.base_ref = "base_ref_value" + + request = developerconnect_v1.OpenGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request=pull_request, + ) + + # Make the request + response = await client.open_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_OpenGitRepositoryLinkPullRequest_async] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_sync.py b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_sync.py new file mode 100644 index 000000000000..7efd8ce66d2f --- /dev/null +++ b/packages/google-cloud-developerconnect/samples/generated_samples/developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_sync.py @@ -0,0 +1,60 @@ +# -*- 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 OpenGitRepositoryLinkPullRequest +# 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-developerconnect + + +# [START developerconnect_v1_generated_DeveloperConnect_OpenGitRepositoryLinkPullRequest_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 developerconnect_v1 + + +def sample_open_git_repository_link_pull_request(): + # Create a client + client = developerconnect_v1.DeveloperConnectClient() + + # Initialize request argument(s) + pull_request = developerconnect_v1.PullRequest() + pull_request.id = "id_value" + pull_request.title = "title_value" + pull_request.head_ref = "head_ref_value" + pull_request.base_ref = "base_ref_value" + + request = developerconnect_v1.OpenGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request=pull_request, + ) + + # Make the request + response = client.open_git_repository_link_pull_request(request=request) + + # Handle the response + print(response) + + +# [END developerconnect_v1_generated_DeveloperConnect_OpenGitRepositoryLinkPullRequest_sync] diff --git a/packages/google-cloud-developerconnect/samples/generated_samples/snippet_metadata_google.cloud.developerconnect.v1.json b/packages/google-cloud-developerconnect/samples/generated_samples/snippet_metadata_google.cloud.developerconnect.v1.json index 30108b040c36..72f91df6ba55 100644 --- a/packages/google-cloud-developerconnect/samples/generated_samples/snippet_metadata_google.cloud.developerconnect.v1.json +++ b/packages/google-cloud-developerconnect/samples/generated_samples/snippet_metadata_google.cloud.developerconnect.v1.json @@ -19,31 +19,31 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.create_account_connector", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.add_git_repository_link_pull_request_comment", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateAccountConnector", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.AddGitRepositoryLinkPullRequestComment", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "CreateAccountConnector" + "shortName": "AddGitRepositoryLinkPullRequestComment" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.CreateAccountConnectorRequest" + "type": "google.cloud.developerconnect_v1.types.AddGitRepositoryLinkPullRequestCommentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { - "name": "account_connector", - "type": "google.cloud.developerconnect_v1.types.AccountConnector" + "name": "pull_request_id", + "type": "str" }, { - "name": "account_connector_id", - "type": "str" + "name": "comment", + "type": "google.cloud.developerconnect_v1.types.PullRequestComment" }, { "name": "retry", @@ -58,22 +58,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_account_connector" + "resultType": "google.cloud.developerconnect_v1.types.PullRequestComment", + "shortName": "add_git_repository_link_pull_request_comment" }, - "description": "Sample for CreateAccountConnector", - "file": "developerconnect_v1_generated_developer_connect_create_account_connector_async.py", + "description": "Sample for AddGitRepositoryLinkPullRequestComment", + "file": "developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateAccountConnector_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestComment_async", "segments": [ { - "end": 61, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 56, "start": 27, "type": "SHORT" }, @@ -83,22 +83,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_create_account_connector_async.py" + "title": "developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_async.py" }, { "canonical": true, @@ -107,31 +107,31 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.create_account_connector", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.add_git_repository_link_pull_request_comment", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateAccountConnector", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.AddGitRepositoryLinkPullRequestComment", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "CreateAccountConnector" + "shortName": "AddGitRepositoryLinkPullRequestComment" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.CreateAccountConnectorRequest" + "type": "google.cloud.developerconnect_v1.types.AddGitRepositoryLinkPullRequestCommentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { - "name": "account_connector", - "type": "google.cloud.developerconnect_v1.types.AccountConnector" + "name": "pull_request_id", + "type": "str" }, { - "name": "account_connector_id", - "type": "str" + "name": "comment", + "type": "google.cloud.developerconnect_v1.types.PullRequestComment" }, { "name": "retry", @@ -146,22 +146,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_account_connector" + "resultType": "google.cloud.developerconnect_v1.types.PullRequestComment", + "shortName": "add_git_repository_link_pull_request_comment" }, - "description": "Sample for CreateAccountConnector", - "file": "developerconnect_v1_generated_developer_connect_create_account_connector_sync.py", + "description": "Sample for AddGitRepositoryLinkPullRequestComment", + "file": "developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateAccountConnector_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestComment_sync", "segments": [ { - "end": 61, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 61, + "end": 56, "start": 27, "type": "SHORT" }, @@ -171,22 +171,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 51, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 58, - "start": 52, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 62, - "start": 59, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_create_account_connector_sync.py" + "title": "developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_comment_sync.py" }, { "canonical": true, @@ -196,31 +196,31 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.create_connection", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.add_git_repository_link_pull_request_review_comment", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateConnection", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.AddGitRepositoryLinkPullRequestReviewComment", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "CreateConnection" + "shortName": "AddGitRepositoryLinkPullRequestReviewComment" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.CreateConnectionRequest" + "type": "google.cloud.developerconnect_v1.types.AddGitRepositoryLinkPullRequestReviewCommentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { - "name": "connection", - "type": "google.cloud.developerconnect_v1.types.Connection" + "name": "pull_request_id", + "type": "str" }, { - "name": "connection_id", - "type": "str" + "name": "comment", + "type": "google.cloud.developerconnect_v1.types.PullRequestReviewComment" }, { "name": "retry", @@ -235,22 +235,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_connection" + "resultType": "google.cloud.developerconnect_v1.types.PullRequestReviewComment", + "shortName": "add_git_repository_link_pull_request_review_comment" }, - "description": "Sample for CreateConnection", - "file": "developerconnect_v1_generated_developer_connect_create_connection_async.py", + "description": "Sample for AddGitRepositoryLinkPullRequestReviewComment", + "file": "developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateConnection_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestReviewComment_async", "segments": [ { - "end": 60, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 58, "start": 27, "type": "SHORT" }, @@ -260,22 +260,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_create_connection_async.py" + "title": "developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_async.py" }, { "canonical": true, @@ -284,31 +284,31 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.create_connection", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.add_git_repository_link_pull_request_review_comment", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateConnection", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.AddGitRepositoryLinkPullRequestReviewComment", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "CreateConnection" + "shortName": "AddGitRepositoryLinkPullRequestReviewComment" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.CreateConnectionRequest" + "type": "google.cloud.developerconnect_v1.types.AddGitRepositoryLinkPullRequestReviewCommentRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { - "name": "connection", - "type": "google.cloud.developerconnect_v1.types.Connection" + "name": "pull_request_id", + "type": "str" }, { - "name": "connection_id", - "type": "str" + "name": "comment", + "type": "google.cloud.developerconnect_v1.types.PullRequestReviewComment" }, { "name": "retry", @@ -323,22 +323,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_connection" + "resultType": "google.cloud.developerconnect_v1.types.PullRequestReviewComment", + "shortName": "add_git_repository_link_pull_request_review_comment" }, - "description": "Sample for CreateConnection", - "file": "developerconnect_v1_generated_developer_connect_create_connection_sync.py", + "description": "Sample for AddGitRepositoryLinkPullRequestReviewComment", + "file": "developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateConnection_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_AddGitRepositoryLinkPullRequestReviewComment_sync", "segments": [ { - "end": 60, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 58, "start": 27, "type": "SHORT" }, @@ -348,22 +348,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_create_connection_sync.py" + "title": "developerconnect_v1_generated_developer_connect_add_git_repository_link_pull_request_review_comment_sync.py" }, { "canonical": true, @@ -373,30 +373,30 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.create_git_repository_link", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.create_account_connector", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateGitRepositoryLink", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateAccountConnector", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "CreateGitRepositoryLink" + "shortName": "CreateAccountConnector" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.CreateGitRepositoryLinkRequest" + "type": "google.cloud.developerconnect_v1.types.CreateAccountConnectorRequest" }, { "name": "parent", "type": "str" }, { - "name": "git_repository_link", - "type": "google.cloud.developerconnect_v1.types.GitRepositoryLink" + "name": "account_connector", + "type": "google.cloud.developerconnect_v1.types.AccountConnector" }, { - "name": "git_repository_link_id", + "name": "account_connector_id", "type": "str" }, { @@ -413,21 +413,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_git_repository_link" + "shortName": "create_account_connector" }, - "description": "Sample for CreateGitRepositoryLink", - "file": "developerconnect_v1_generated_developer_connect_create_git_repository_link_async.py", + "description": "Sample for CreateAccountConnector", + "file": "developerconnect_v1_generated_developer_connect_create_account_connector_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateGitRepositoryLink_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateAccountConnector_async", "segments": [ { - "end": 60, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 61, "start": 27, "type": "SHORT" }, @@ -437,22 +437,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_create_git_repository_link_async.py" + "title": "developerconnect_v1_generated_developer_connect_create_account_connector_async.py" }, { "canonical": true, @@ -461,30 +461,30 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.create_git_repository_link", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.create_account_connector", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateGitRepositoryLink", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateAccountConnector", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "CreateGitRepositoryLink" + "shortName": "CreateAccountConnector" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.CreateGitRepositoryLinkRequest" + "type": "google.cloud.developerconnect_v1.types.CreateAccountConnectorRequest" }, { "name": "parent", "type": "str" }, { - "name": "git_repository_link", - "type": "google.cloud.developerconnect_v1.types.GitRepositoryLink" + "name": "account_connector", + "type": "google.cloud.developerconnect_v1.types.AccountConnector" }, { - "name": "git_repository_link_id", + "name": "account_connector_id", "type": "str" }, { @@ -501,21 +501,21 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "create_git_repository_link" + "shortName": "create_account_connector" }, - "description": "Sample for CreateGitRepositoryLink", - "file": "developerconnect_v1_generated_developer_connect_create_git_repository_link_sync.py", + "description": "Sample for CreateAccountConnector", + "file": "developerconnect_v1_generated_developer_connect_create_account_connector_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateGitRepositoryLink_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateAccountConnector_sync", "segments": [ { - "end": 60, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 61, "start": 27, "type": "SHORT" }, @@ -525,22 +525,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_create_git_repository_link_sync.py" + "title": "developerconnect_v1_generated_developer_connect_create_account_connector_sync.py" }, { "canonical": true, @@ -550,22 +550,30 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_account_connector", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.create_connection", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteAccountConnector", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateConnection", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteAccountConnector" + "shortName": "CreateConnection" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteAccountConnectorRequest" + "type": "google.cloud.developerconnect_v1.types.CreateConnectionRequest" }, { - "name": "name", + "name": "parent", + "type": "str" + }, + { + "name": "connection", + "type": "google.cloud.developerconnect_v1.types.Connection" + }, + { + "name": "connection_id", "type": "str" }, { @@ -582,21 +590,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_account_connector" + "shortName": "create_connection" }, - "description": "Sample for DeleteAccountConnector", - "file": "developerconnect_v1_generated_developer_connect_delete_account_connector_async.py", + "description": "Sample for CreateConnection", + "file": "developerconnect_v1_generated_developer_connect_create_connection_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteAccountConnector_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateConnection_async", "segments": [ { - "end": 55, + "end": 60, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 60, "start": 27, "type": "SHORT" }, @@ -606,22 +614,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 57, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 61, + "start": 58, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_delete_account_connector_async.py" + "title": "developerconnect_v1_generated_developer_connect_create_connection_async.py" }, { "canonical": true, @@ -630,27 +638,35 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_account_connector", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.create_connection", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteAccountConnector", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateConnection", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteAccountConnector" + "shortName": "CreateConnection" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteAccountConnectorRequest" + "type": "google.cloud.developerconnect_v1.types.CreateConnectionRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { - "name": "retry", - "type": "google.api_core.retry.Retry" + "name": "connection", + "type": "google.cloud.developerconnect_v1.types.Connection" + }, + { + "name": "connection_id", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" }, { "name": "timeout", @@ -662,21 +678,1671 @@ } ], "resultType": "google.api_core.operation.Operation", - "shortName": "delete_account_connector" + "shortName": "create_connection" + }, + "description": "Sample for CreateConnection", + "file": "developerconnect_v1_generated_developer_connect_create_connection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateConnection_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "developerconnect_v1_generated_developer_connect_create_connection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.create_git_repository_link", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateGitRepositoryLink", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "CreateGitRepositoryLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.CreateGitRepositoryLinkRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "git_repository_link", + "type": "google.cloud.developerconnect_v1.types.GitRepositoryLink" + }, + { + "name": "git_repository_link_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_git_repository_link" + }, + "description": "Sample for CreateGitRepositoryLink", + "file": "developerconnect_v1_generated_developer_connect_create_git_repository_link_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateGitRepositoryLink_async", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "developerconnect_v1_generated_developer_connect_create_git_repository_link_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.create_git_repository_link", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.CreateGitRepositoryLink", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "CreateGitRepositoryLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.CreateGitRepositoryLinkRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "git_repository_link", + "type": "google.cloud.developerconnect_v1.types.GitRepositoryLink" + }, + { + "name": "git_repository_link_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_git_repository_link" + }, + "description": "Sample for CreateGitRepositoryLink", + "file": "developerconnect_v1_generated_developer_connect_create_git_repository_link_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_CreateGitRepositoryLink_sync", + "segments": [ + { + "end": 60, + "start": 27, + "type": "FULL" + }, + { + "end": 60, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 57, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 61, + "start": 58, + "type": "RESPONSE_HANDLING" + } + ], + "title": "developerconnect_v1_generated_developer_connect_create_git_repository_link_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_account_connector", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteAccountConnector", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteAccountConnector" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteAccountConnectorRequest" + }, + { + "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_account_connector" + }, + "description": "Sample for DeleteAccountConnector", + "file": "developerconnect_v1_generated_developer_connect_delete_account_connector_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteAccountConnector_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": "developerconnect_v1_generated_developer_connect_delete_account_connector_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_account_connector", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteAccountConnector", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteAccountConnector" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteAccountConnectorRequest" + }, + { + "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_account_connector" + }, + "description": "Sample for DeleteAccountConnector", + "file": "developerconnect_v1_generated_developer_connect_delete_account_connector_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteAccountConnector_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": "developerconnect_v1_generated_developer_connect_delete_account_connector_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_connection", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteConnection", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteConnectionRequest" + }, + { + "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_connection" + }, + "description": "Sample for DeleteConnection", + "file": "developerconnect_v1_generated_developer_connect_delete_connection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteConnection_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": "developerconnect_v1_generated_developer_connect_delete_connection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_connection", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteConnection", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteConnection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteConnectionRequest" + }, + { + "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_connection" + }, + "description": "Sample for DeleteConnection", + "file": "developerconnect_v1_generated_developer_connect_delete_connection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteConnection_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": "developerconnect_v1_generated_developer_connect_delete_connection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_git_repository_link", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteGitRepositoryLink", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteGitRepositoryLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteGitRepositoryLinkRequest" + }, + { + "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_git_repository_link" + }, + "description": "Sample for DeleteGitRepositoryLink", + "file": "developerconnect_v1_generated_developer_connect_delete_git_repository_link_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteGitRepositoryLink_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": "developerconnect_v1_generated_developer_connect_delete_git_repository_link_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_git_repository_link", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteGitRepositoryLink", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteGitRepositoryLink" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteGitRepositoryLinkRequest" + }, + { + "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_git_repository_link" + }, + "description": "Sample for DeleteGitRepositoryLink", + "file": "developerconnect_v1_generated_developer_connect_delete_git_repository_link_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteGitRepositoryLink_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": "developerconnect_v1_generated_developer_connect_delete_git_repository_link_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_self", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteSelf", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteSelf" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteSelfRequest" + }, + { + "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_self" + }, + "description": "Sample for DeleteSelf", + "file": "developerconnect_v1_generated_developer_connect_delete_self_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteSelf_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": "developerconnect_v1_generated_developer_connect_delete_self_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_self", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteSelf", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteSelf" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteSelfRequest" + }, + { + "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_self" + }, + "description": "Sample for DeleteSelf", + "file": "developerconnect_v1_generated_developer_connect_delete_self_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteSelf_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": "developerconnect_v1_generated_developer_connect_delete_self_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_user", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteUser", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteUserRequest" + }, + { + "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_user" + }, + "description": "Sample for DeleteUser", + "file": "developerconnect_v1_generated_developer_connect_delete_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteUser_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": "developerconnect_v1_generated_developer_connect_delete_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_user", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteUser", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DeleteUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DeleteUserRequest" + }, + { + "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_user" + }, + "description": "Sample for DeleteUser", + "file": "developerconnect_v1_generated_developer_connect_delete_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteUser_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": "developerconnect_v1_generated_developer_connect_delete_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.diff_git_repository_link_commit", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DiffGitRepositoryLinkCommit", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DiffGitRepositoryLinkCommit" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DiffGitRepositoryLinkCommitRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "base_sha", + "type": "str" + }, + { + "name": "head_sha", + "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.developerconnect_v1.types.DiffGitRepositoryLinkCommitResponse", + "shortName": "diff_git_repository_link_commit" + }, + "description": "Sample for DiffGitRepositoryLinkCommit", + "file": "developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DiffGitRepositoryLinkCommit_async", + "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": "developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.diff_git_repository_link_commit", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DiffGitRepositoryLinkCommit", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "DiffGitRepositoryLinkCommit" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.DiffGitRepositoryLinkCommitRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "base_sha", + "type": "str" + }, + { + "name": "head_sha", + "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.developerconnect_v1.types.DiffGitRepositoryLinkCommitResponse", + "shortName": "diff_git_repository_link_commit" + }, + "description": "Sample for DiffGitRepositoryLinkCommit", + "file": "developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_DiffGitRepositoryLinkCommit_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": "developerconnect_v1_generated_developer_connect_diff_git_repository_link_commit_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_access_token", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchAccessToken", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "FetchAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.FetchAccessTokenRequest" + }, + { + "name": "account_connector", + "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.developerconnect_v1.types.FetchAccessTokenResponse", + "shortName": "fetch_access_token" + }, + "description": "Sample for FetchAccessToken", + "file": "developerconnect_v1_generated_developer_connect_fetch_access_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchAccessToken_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": "developerconnect_v1_generated_developer_connect_fetch_access_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_access_token", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchAccessToken", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "FetchAccessToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.FetchAccessTokenRequest" + }, + { + "name": "account_connector", + "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.developerconnect_v1.types.FetchAccessTokenResponse", + "shortName": "fetch_access_token" + }, + "description": "Sample for FetchAccessToken", + "file": "developerconnect_v1_generated_developer_connect_fetch_access_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchAccessToken_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": "developerconnect_v1_generated_developer_connect_fetch_access_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_git_hub_installations", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitHubInstallations", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "FetchGitHubInstallations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.FetchGitHubInstallationsRequest" + }, + { + "name": "connection", + "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.developerconnect_v1.types.FetchGitHubInstallationsResponse", + "shortName": "fetch_git_hub_installations" + }, + "description": "Sample for FetchGitHubInstallations", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_hub_installations_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitHubInstallations_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": "developerconnect_v1_generated_developer_connect_fetch_git_hub_installations_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_hub_installations", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitHubInstallations", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "FetchGitHubInstallations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.FetchGitHubInstallationsRequest" + }, + { + "name": "connection", + "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.developerconnect_v1.types.FetchGitHubInstallationsResponse", + "shortName": "fetch_git_hub_installations" + }, + "description": "Sample for FetchGitHubInstallations", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_hub_installations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitHubInstallations_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": "developerconnect_v1_generated_developer_connect_fetch_git_hub_installations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", + "shortName": "DeveloperConnectAsyncClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_git_refs", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRefs", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "FetchGitRefs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.FetchGitRefsRequest" + }, + { + "name": "git_repository_link", + "type": "str" + }, + { + "name": "ref_type", + "type": "google.cloud.developerconnect_v1.types.FetchGitRefsRequest.RefType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchGitRefsAsyncPager", + "shortName": "fetch_git_refs" + }, + "description": "Sample for FetchGitRefs", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_refs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRefs_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "developerconnect_v1_generated_developer_connect_fetch_git_refs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", + "shortName": "DeveloperConnectClient" + }, + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_refs", + "method": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRefs", + "service": { + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", + "shortName": "DeveloperConnect" + }, + "shortName": "FetchGitRefs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.developerconnect_v1.types.FetchGitRefsRequest" + }, + { + "name": "git_repository_link", + "type": "str" + }, + { + "name": "ref_type", + "type": "google.cloud.developerconnect_v1.types.FetchGitRefsRequest.RefType" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchGitRefsPager", + "shortName": "fetch_git_refs" }, - "description": "Sample for DeleteAccountConnector", - "file": "developerconnect_v1_generated_developer_connect_delete_account_connector_sync.py", + "description": "Sample for FetchGitRefs", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_refs_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteAccountConnector_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRefs_sync", "segments": [ { - "end": 55, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 53, "start": 27, "type": "SHORT" }, @@ -686,22 +2352,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 54, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_delete_account_connector_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_refs_sync.py" }, { "canonical": true, @@ -711,24 +2377,28 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_connection", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_git_repository_link_commit_list", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteConnection", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkCommitList", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteConnection" + "shortName": "FetchGitRepositoryLinkCommitList" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteConnectionRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListRequest" }, { "name": "name", "type": "str" }, + { + "name": "ref", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -742,22 +2412,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_connection" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchGitRepositoryLinkCommitListAsyncPager", + "shortName": "fetch_git_repository_link_commit_list" }, - "description": "Sample for DeleteConnection", - "file": "developerconnect_v1_generated_developer_connect_delete_connection_async.py", + "description": "Sample for FetchGitRepositoryLinkCommitList", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_list_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteConnection_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommitList_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -772,17 +2442,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": "developerconnect_v1_generated_developer_connect_delete_connection_async.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_list_async.py" }, { "canonical": true, @@ -791,24 +2461,28 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_connection", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_commit_list", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteConnection", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkCommitList", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteConnection" + "shortName": "FetchGitRepositoryLinkCommitList" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteConnectionRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitListRequest" }, { "name": "name", "type": "str" }, + { + "name": "ref", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -822,22 +2496,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_connection" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchGitRepositoryLinkCommitListPager", + "shortName": "fetch_git_repository_link_commit_list" }, - "description": "Sample for DeleteConnection", - "file": "developerconnect_v1_generated_developer_connect_delete_connection_sync.py", + "description": "Sample for FetchGitRepositoryLinkCommitList", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteConnection_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommitList_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -852,17 +2526,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": "developerconnect_v1_generated_developer_connect_delete_connection_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_list_sync.py" }, { "canonical": true, @@ -872,24 +2546,28 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_git_repository_link", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_git_repository_link_commit", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteGitRepositoryLink", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkCommit", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteGitRepositoryLink" + "shortName": "FetchGitRepositoryLinkCommit" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteGitRepositoryLinkRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitRequest" }, { "name": "name", "type": "str" }, + { + "name": "commit_sha", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -903,22 +2581,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_git_repository_link" + "resultType": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitResponse", + "shortName": "fetch_git_repository_link_commit" }, - "description": "Sample for DeleteGitRepositoryLink", - "file": "developerconnect_v1_generated_developer_connect_delete_git_repository_link_async.py", + "description": "Sample for FetchGitRepositoryLinkCommit", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteGitRepositoryLink_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommit_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -928,22 +2606,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_delete_git_repository_link_async.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_async.py" }, { "canonical": true, @@ -952,24 +2630,28 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_git_repository_link", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_commit", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteGitRepositoryLink", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkCommit", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteGitRepositoryLink" + "shortName": "FetchGitRepositoryLinkCommit" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteGitRepositoryLinkRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitRequest" }, { "name": "name", "type": "str" }, + { + "name": "commit_sha", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -983,22 +2665,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_git_repository_link" + "resultType": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkCommitResponse", + "shortName": "fetch_git_repository_link_commit" }, - "description": "Sample for DeleteGitRepositoryLink", - "file": "developerconnect_v1_generated_developer_connect_delete_git_repository_link_sync.py", + "description": "Sample for FetchGitRepositoryLinkCommit", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteGitRepositoryLink_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkCommit_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1008,22 +2690,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_delete_git_repository_link_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_commit_sync.py" }, { "canonical": true, @@ -1033,24 +2715,32 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_self", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_git_repository_link_file_blame", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteSelf", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkFileBlame", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteSelf" + "shortName": "FetchGitRepositoryLinkFileBlame" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteSelfRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkFileBlameRequest" }, { "name": "name", "type": "str" }, + { + "name": "ref", + "type": "str" + }, + { + "name": "path", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1064,22 +2754,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_self" + "resultType": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkFileBlameResponse", + "shortName": "fetch_git_repository_link_file_blame" }, - "description": "Sample for DeleteSelf", - "file": "developerconnect_v1_generated_developer_connect_delete_self_async.py", + "description": "Sample for FetchGitRepositoryLinkFileBlame", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteSelf_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkFileBlame_async", "segments": [ { - "end": 55, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 53, "start": 27, "type": "SHORT" }, @@ -1089,22 +2779,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_delete_self_async.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_async.py" }, { "canonical": true, @@ -1113,24 +2803,32 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_self", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_file_blame", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteSelf", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkFileBlame", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteSelf" + "shortName": "FetchGitRepositoryLinkFileBlame" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteSelfRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkFileBlameRequest" }, { "name": "name", "type": "str" }, + { + "name": "ref", + "type": "str" + }, + { + "name": "path", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1144,22 +2842,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_self" + "resultType": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkFileBlameResponse", + "shortName": "fetch_git_repository_link_file_blame" }, - "description": "Sample for DeleteSelf", - "file": "developerconnect_v1_generated_developer_connect_delete_self_sync.py", + "description": "Sample for FetchGitRepositoryLinkFileBlame", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteSelf_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkFileBlame_sync", "segments": [ { - "end": 55, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 53, "start": 27, "type": "SHORT" }, @@ -1169,22 +2867,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 46, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_delete_self_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_file_blame_sync.py" }, { "canonical": true, @@ -1194,19 +2892,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.delete_user", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_git_repository_link_pull_request_list", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteUser", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkPullRequestList", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteUser" + "shortName": "FetchGitRepositoryLinkPullRequestList" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteUserRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListRequest" }, { "name": "name", @@ -1225,22 +2923,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_user" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchGitRepositoryLinkPullRequestListAsyncPager", + "shortName": "fetch_git_repository_link_pull_request_list" }, - "description": "Sample for DeleteUser", - "file": "developerconnect_v1_generated_developer_connect_delete_user_async.py", + "description": "Sample for FetchGitRepositoryLinkPullRequestList", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_list_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteUser_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequestList_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1255,17 +2953,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": "developerconnect_v1_generated_developer_connect_delete_user_async.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_list_async.py" }, { "canonical": true, @@ -1274,19 +2972,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.delete_user", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_pull_request_list", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.DeleteUser", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkPullRequestList", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "DeleteUser" + "shortName": "FetchGitRepositoryLinkPullRequestList" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.DeleteUserRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestListRequest" }, { "name": "name", @@ -1305,22 +3003,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_user" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchGitRepositoryLinkPullRequestListPager", + "shortName": "fetch_git_repository_link_pull_request_list" }, - "description": "Sample for DeleteUser", - "file": "developerconnect_v1_generated_developer_connect_delete_user_sync.py", + "description": "Sample for FetchGitRepositoryLinkPullRequestList", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_DeleteUser_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequestList_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1335,17 +3033,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": "developerconnect_v1_generated_developer_connect_delete_user_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_list_sync.py" }, { "canonical": true, @@ -1355,22 +3053,26 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_access_token", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_git_repository_link_pull_request", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchAccessToken", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkPullRequest", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchAccessToken" + "shortName": "FetchGitRepositoryLinkPullRequest" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchAccessTokenRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestRequest" }, { - "name": "account_connector", + "name": "name", + "type": "str" + }, + { + "name": "pull_request_id", "type": "str" }, { @@ -1386,22 +3088,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FetchAccessTokenResponse", - "shortName": "fetch_access_token" + "resultType": "google.cloud.developerconnect_v1.types.PullRequest", + "shortName": "fetch_git_repository_link_pull_request" }, - "description": "Sample for FetchAccessToken", - "file": "developerconnect_v1_generated_developer_connect_fetch_access_token_async.py", + "description": "Sample for FetchGitRepositoryLinkPullRequest", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchAccessToken_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequest_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1411,22 +3113,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": "developerconnect_v1_generated_developer_connect_fetch_access_token_async.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_async.py" }, { "canonical": true, @@ -1435,22 +3137,26 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_access_token", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_repository_link_pull_request", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchAccessToken", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRepositoryLinkPullRequest", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchAccessToken" + "shortName": "FetchGitRepositoryLinkPullRequest" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchAccessTokenRequest" + "type": "google.cloud.developerconnect_v1.types.FetchGitRepositoryLinkPullRequestRequest" + }, + { + "name": "name", + "type": "str" }, { - "name": "account_connector", + "name": "pull_request_id", "type": "str" }, { @@ -1466,22 +3172,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FetchAccessTokenResponse", - "shortName": "fetch_access_token" + "resultType": "google.cloud.developerconnect_v1.types.PullRequest", + "shortName": "fetch_git_repository_link_pull_request" }, - "description": "Sample for FetchAccessToken", - "file": "developerconnect_v1_generated_developer_connect_fetch_access_token_sync.py", + "description": "Sample for FetchGitRepositoryLinkPullRequest", + "file": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchAccessToken_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRepositoryLinkPullRequest_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1491,22 +3197,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": "developerconnect_v1_generated_developer_connect_fetch_access_token_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_git_repository_link_pull_request_sync.py" }, { "canonical": true, @@ -1516,19 +3222,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_git_hub_installations", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_linkable_git_repositories", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitHubInstallations", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchLinkableGitRepositories", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchGitHubInstallations" + "shortName": "FetchLinkableGitRepositories" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchGitHubInstallationsRequest" + "type": "google.cloud.developerconnect_v1.types.FetchLinkableGitRepositoriesRequest" }, { "name": "connection", @@ -1547,22 +3253,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FetchGitHubInstallationsResponse", - "shortName": "fetch_git_hub_installations" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchLinkableGitRepositoriesAsyncPager", + "shortName": "fetch_linkable_git_repositories" }, - "description": "Sample for FetchGitHubInstallations", - "file": "developerconnect_v1_generated_developer_connect_fetch_git_hub_installations_async.py", + "description": "Sample for FetchLinkableGitRepositories", + "file": "developerconnect_v1_generated_developer_connect_fetch_linkable_git_repositories_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitHubInstallations_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchLinkableGitRepositories_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1582,12 +3288,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_git_hub_installations_async.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_linkable_git_repositories_async.py" }, { "canonical": true, @@ -1596,19 +3302,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_hub_installations", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_linkable_git_repositories", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitHubInstallations", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchLinkableGitRepositories", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchGitHubInstallations" + "shortName": "FetchLinkableGitRepositories" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchGitHubInstallationsRequest" + "type": "google.cloud.developerconnect_v1.types.FetchLinkableGitRepositoriesRequest" }, { "name": "connection", @@ -1627,22 +3333,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FetchGitHubInstallationsResponse", - "shortName": "fetch_git_hub_installations" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchLinkableGitRepositoriesPager", + "shortName": "fetch_linkable_git_repositories" }, - "description": "Sample for FetchGitHubInstallations", - "file": "developerconnect_v1_generated_developer_connect_fetch_git_hub_installations_sync.py", + "description": "Sample for FetchLinkableGitRepositories", + "file": "developerconnect_v1_generated_developer_connect_fetch_linkable_git_repositories_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitHubInstallations_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchLinkableGitRepositories_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -1662,12 +3368,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_git_hub_installations_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_linkable_git_repositories_sync.py" }, { "canonical": true, @@ -1677,28 +3383,24 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_git_refs", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_read_token", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRefs", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchReadToken", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchGitRefs" + "shortName": "FetchReadToken" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchGitRefsRequest" + "type": "google.cloud.developerconnect_v1.types.FetchReadTokenRequest" }, { "name": "git_repository_link", "type": "str" }, - { - "name": "ref_type", - "type": "google.cloud.developerconnect_v1.types.FetchGitRefsRequest.RefType" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1712,22 +3414,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchGitRefsAsyncPager", - "shortName": "fetch_git_refs" + "resultType": "google.cloud.developerconnect_v1.types.FetchReadTokenResponse", + "shortName": "fetch_read_token" }, - "description": "Sample for FetchGitRefs", - "file": "developerconnect_v1_generated_developer_connect_fetch_git_refs_async.py", + "description": "Sample for FetchReadToken", + "file": "developerconnect_v1_generated_developer_connect_fetch_read_token_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRefs_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchReadToken_async", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1737,22 +3439,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": 54, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_git_refs_async.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_read_token_async.py" }, { "canonical": true, @@ -1761,28 +3463,24 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_git_refs", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_read_token", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchGitRefs", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchReadToken", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchGitRefs" + "shortName": "FetchReadToken" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchGitRefsRequest" + "type": "google.cloud.developerconnect_v1.types.FetchReadTokenRequest" }, { "name": "git_repository_link", "type": "str" }, - { - "name": "ref_type", - "type": "google.cloud.developerconnect_v1.types.FetchGitRefsRequest.RefType" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -1796,22 +3494,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchGitRefsPager", - "shortName": "fetch_git_refs" + "resultType": "google.cloud.developerconnect_v1.types.FetchReadTokenResponse", + "shortName": "fetch_read_token" }, - "description": "Sample for FetchGitRefs", - "file": "developerconnect_v1_generated_developer_connect_fetch_git_refs_sync.py", + "description": "Sample for FetchReadToken", + "file": "developerconnect_v1_generated_developer_connect_fetch_read_token_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchGitRefs_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchReadToken_sync", "segments": [ { - "end": 53, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1821,22 +3519,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": 54, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_git_refs_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_read_token_sync.py" }, { "canonical": true, @@ -1846,22 +3544,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_linkable_git_repositories", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_read_write_token", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchLinkableGitRepositories", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchReadWriteToken", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchLinkableGitRepositories" + "shortName": "FetchReadWriteToken" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchLinkableGitRepositoriesRequest" + "type": "google.cloud.developerconnect_v1.types.FetchReadWriteTokenRequest" }, { - "name": "connection", + "name": "git_repository_link", "type": "str" }, { @@ -1877,22 +3575,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchLinkableGitRepositoriesAsyncPager", - "shortName": "fetch_linkable_git_repositories" + "resultType": "google.cloud.developerconnect_v1.types.FetchReadWriteTokenResponse", + "shortName": "fetch_read_write_token" }, - "description": "Sample for FetchLinkableGitRepositories", - "file": "developerconnect_v1_generated_developer_connect_fetch_linkable_git_repositories_async.py", + "description": "Sample for FetchReadWriteToken", + "file": "developerconnect_v1_generated_developer_connect_fetch_read_write_token_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchLinkableGitRepositories_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchReadWriteToken_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1912,12 +3610,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_linkable_git_repositories_async.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_read_write_token_async.py" }, { "canonical": true, @@ -1926,22 +3624,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_linkable_git_repositories", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_read_write_token", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchLinkableGitRepositories", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchReadWriteToken", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchLinkableGitRepositories" + "shortName": "FetchReadWriteToken" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchLinkableGitRepositoriesRequest" + "type": "google.cloud.developerconnect_v1.types.FetchReadWriteTokenRequest" }, { - "name": "connection", + "name": "git_repository_link", "type": "str" }, { @@ -1957,22 +3655,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.FetchLinkableGitRepositoriesPager", - "shortName": "fetch_linkable_git_repositories" + "resultType": "google.cloud.developerconnect_v1.types.FetchReadWriteTokenResponse", + "shortName": "fetch_read_write_token" }, - "description": "Sample for FetchLinkableGitRepositories", - "file": "developerconnect_v1_generated_developer_connect_fetch_linkable_git_repositories_sync.py", + "description": "Sample for FetchReadWriteToken", + "file": "developerconnect_v1_generated_developer_connect_fetch_read_write_token_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchLinkableGitRepositories_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchReadWriteToken_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1992,12 +3690,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_linkable_git_repositories_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_read_write_token_sync.py" }, { "canonical": true, @@ -2007,22 +3705,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_read_token", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_self", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchReadToken", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchSelf", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchReadToken" + "shortName": "FetchSelf" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchReadTokenRequest" + "type": "google.cloud.developerconnect_v1.types.FetchSelfRequest" }, { - "name": "git_repository_link", + "name": "name", "type": "str" }, { @@ -2038,14 +3736,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FetchReadTokenResponse", - "shortName": "fetch_read_token" + "resultType": "google.cloud.developerconnect_v1.types.User", + "shortName": "fetch_self" }, - "description": "Sample for FetchReadToken", - "file": "developerconnect_v1_generated_developer_connect_fetch_read_token_async.py", + "description": "Sample for FetchSelf", + "file": "developerconnect_v1_generated_developer_connect_fetch_self_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchReadToken_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchSelf_async", "segments": [ { "end": 51, @@ -2078,7 +3776,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_read_token_async.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_self_async.py" }, { "canonical": true, @@ -2087,22 +3785,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_read_token", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_self", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchReadToken", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchSelf", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchReadToken" + "shortName": "FetchSelf" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchReadTokenRequest" + "type": "google.cloud.developerconnect_v1.types.FetchSelfRequest" }, { - "name": "git_repository_link", + "name": "name", "type": "str" }, { @@ -2118,14 +3816,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FetchReadTokenResponse", - "shortName": "fetch_read_token" + "resultType": "google.cloud.developerconnect_v1.types.User", + "shortName": "fetch_self" }, - "description": "Sample for FetchReadToken", - "file": "developerconnect_v1_generated_developer_connect_fetch_read_token_sync.py", + "description": "Sample for FetchSelf", + "file": "developerconnect_v1_generated_developer_connect_fetch_self_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchReadToken_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchSelf_sync", "segments": [ { "end": 51, @@ -2158,7 +3856,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_read_token_sync.py" + "title": "developerconnect_v1_generated_developer_connect_fetch_self_sync.py" }, { "canonical": true, @@ -2168,22 +3866,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_read_write_token", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.finish_o_auth", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchReadWriteToken", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FinishOAuth", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchReadWriteToken" + "shortName": "FinishOAuth" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchReadWriteTokenRequest" + "type": "google.cloud.developerconnect_v1.types.FinishOAuthRequest" }, { - "name": "git_repository_link", + "name": "account_connector", "type": "str" }, { @@ -2199,22 +3897,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FetchReadWriteTokenResponse", - "shortName": "fetch_read_write_token" + "resultType": "google.cloud.developerconnect_v1.types.FinishOAuthResponse", + "shortName": "finish_o_auth" }, - "description": "Sample for FetchReadWriteToken", - "file": "developerconnect_v1_generated_developer_connect_fetch_read_write_token_async.py", + "description": "Sample for FinishOAuth", + "file": "developerconnect_v1_generated_developer_connect_finish_o_auth_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchReadWriteToken_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FinishOAuth_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -2224,22 +3922,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_read_write_token_async.py" + "title": "developerconnect_v1_generated_developer_connect_finish_o_auth_async.py" }, { "canonical": true, @@ -2248,22 +3946,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_read_write_token", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.finish_o_auth", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchReadWriteToken", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FinishOAuth", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchReadWriteToken" + "shortName": "FinishOAuth" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchReadWriteTokenRequest" + "type": "google.cloud.developerconnect_v1.types.FinishOAuthRequest" }, { - "name": "git_repository_link", + "name": "account_connector", "type": "str" }, { @@ -2279,22 +3977,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FetchReadWriteTokenResponse", - "shortName": "fetch_read_write_token" + "resultType": "google.cloud.developerconnect_v1.types.FinishOAuthResponse", + "shortName": "finish_o_auth" }, - "description": "Sample for FetchReadWriteToken", - "file": "developerconnect_v1_generated_developer_connect_fetch_read_write_token_sync.py", + "description": "Sample for FinishOAuth", + "file": "developerconnect_v1_generated_developer_connect_finish_o_auth_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchReadWriteToken_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_FinishOAuth_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -2304,22 +4002,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_read_write_token_sync.py" + "title": "developerconnect_v1_generated_developer_connect_finish_o_auth_sync.py" }, { "canonical": true, @@ -2329,19 +4027,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.fetch_self", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.get_account_connector", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchSelf", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetAccountConnector", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchSelf" + "shortName": "GetAccountConnector" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchSelfRequest" + "type": "google.cloud.developerconnect_v1.types.GetAccountConnectorRequest" }, { "name": "name", @@ -2360,14 +4058,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.User", - "shortName": "fetch_self" + "resultType": "google.cloud.developerconnect_v1.types.AccountConnector", + "shortName": "get_account_connector" }, - "description": "Sample for FetchSelf", - "file": "developerconnect_v1_generated_developer_connect_fetch_self_async.py", + "description": "Sample for GetAccountConnector", + "file": "developerconnect_v1_generated_developer_connect_get_account_connector_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchSelf_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetAccountConnector_async", "segments": [ { "end": 51, @@ -2400,7 +4098,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_self_async.py" + "title": "developerconnect_v1_generated_developer_connect_get_account_connector_async.py" }, { "canonical": true, @@ -2409,19 +4107,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.fetch_self", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.get_account_connector", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FetchSelf", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetAccountConnector", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FetchSelf" + "shortName": "GetAccountConnector" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FetchSelfRequest" + "type": "google.cloud.developerconnect_v1.types.GetAccountConnectorRequest" }, { "name": "name", @@ -2440,14 +4138,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.User", - "shortName": "fetch_self" + "resultType": "google.cloud.developerconnect_v1.types.AccountConnector", + "shortName": "get_account_connector" }, - "description": "Sample for FetchSelf", - "file": "developerconnect_v1_generated_developer_connect_fetch_self_sync.py", + "description": "Sample for GetAccountConnector", + "file": "developerconnect_v1_generated_developer_connect_get_account_connector_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FetchSelf_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetAccountConnector_sync", "segments": [ { "end": 51, @@ -2480,7 +4178,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_fetch_self_sync.py" + "title": "developerconnect_v1_generated_developer_connect_get_account_connector_sync.py" }, { "canonical": true, @@ -2490,22 +4188,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.finish_o_auth", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.get_connection", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FinishOAuth", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetConnection", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FinishOAuth" + "shortName": "GetConnection" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FinishOAuthRequest" + "type": "google.cloud.developerconnect_v1.types.GetConnectionRequest" }, { - "name": "account_connector", + "name": "name", "type": "str" }, { @@ -2521,22 +4219,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FinishOAuthResponse", - "shortName": "finish_o_auth" + "resultType": "google.cloud.developerconnect_v1.types.Connection", + "shortName": "get_connection" }, - "description": "Sample for FinishOAuth", - "file": "developerconnect_v1_generated_developer_connect_finish_o_auth_async.py", + "description": "Sample for GetConnection", + "file": "developerconnect_v1_generated_developer_connect_get_connection_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FinishOAuth_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetConnection_async", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2546,22 +4244,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_finish_o_auth_async.py" + "title": "developerconnect_v1_generated_developer_connect_get_connection_async.py" }, { "canonical": true, @@ -2570,22 +4268,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.finish_o_auth", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.get_connection", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.FinishOAuth", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetConnection", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "FinishOAuth" + "shortName": "GetConnection" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.FinishOAuthRequest" + "type": "google.cloud.developerconnect_v1.types.GetConnectionRequest" }, { - "name": "account_connector", + "name": "name", "type": "str" }, { @@ -2601,22 +4299,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.FinishOAuthResponse", - "shortName": "finish_o_auth" + "resultType": "google.cloud.developerconnect_v1.types.Connection", + "shortName": "get_connection" }, - "description": "Sample for FinishOAuth", - "file": "developerconnect_v1_generated_developer_connect_finish_o_auth_sync.py", + "description": "Sample for GetConnection", + "file": "developerconnect_v1_generated_developer_connect_get_connection_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_FinishOAuth_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetConnection_sync", "segments": [ { - "end": 56, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 56, + "end": 51, "start": 27, "type": "SHORT" }, @@ -2626,22 +4324,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 53, - "start": 51, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 57, - "start": 54, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_finish_o_auth_sync.py" + "title": "developerconnect_v1_generated_developer_connect_get_connection_sync.py" }, { "canonical": true, @@ -2651,19 +4349,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.get_account_connector", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.get_git_repository_link", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetAccountConnector", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetGitRepositoryLink", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "GetAccountConnector" + "shortName": "GetGitRepositoryLink" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.GetAccountConnectorRequest" + "type": "google.cloud.developerconnect_v1.types.GetGitRepositoryLinkRequest" }, { "name": "name", @@ -2682,14 +4380,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.AccountConnector", - "shortName": "get_account_connector" + "resultType": "google.cloud.developerconnect_v1.types.GitRepositoryLink", + "shortName": "get_git_repository_link" }, - "description": "Sample for GetAccountConnector", - "file": "developerconnect_v1_generated_developer_connect_get_account_connector_async.py", + "description": "Sample for GetGitRepositoryLink", + "file": "developerconnect_v1_generated_developer_connect_get_git_repository_link_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetAccountConnector_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetGitRepositoryLink_async", "segments": [ { "end": 51, @@ -2722,7 +4420,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_get_account_connector_async.py" + "title": "developerconnect_v1_generated_developer_connect_get_git_repository_link_async.py" }, { "canonical": true, @@ -2731,19 +4429,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.get_account_connector", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.get_git_repository_link", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetAccountConnector", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetGitRepositoryLink", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "GetAccountConnector" + "shortName": "GetGitRepositoryLink" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.GetAccountConnectorRequest" + "type": "google.cloud.developerconnect_v1.types.GetGitRepositoryLinkRequest" }, { "name": "name", @@ -2762,14 +4460,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.AccountConnector", - "shortName": "get_account_connector" + "resultType": "google.cloud.developerconnect_v1.types.GitRepositoryLink", + "shortName": "get_git_repository_link" }, - "description": "Sample for GetAccountConnector", - "file": "developerconnect_v1_generated_developer_connect_get_account_connector_sync.py", + "description": "Sample for GetGitRepositoryLink", + "file": "developerconnect_v1_generated_developer_connect_get_git_repository_link_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetAccountConnector_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetGitRepositoryLink_sync", "segments": [ { "end": 51, @@ -2802,7 +4500,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_get_account_connector_sync.py" + "title": "developerconnect_v1_generated_developer_connect_get_git_repository_link_sync.py" }, { "canonical": true, @@ -2812,22 +4510,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.get_connection", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.list_account_connectors", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetConnection", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListAccountConnectors", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "GetConnection" + "shortName": "ListAccountConnectors" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.GetConnectionRequest" + "type": "google.cloud.developerconnect_v1.types.ListAccountConnectorsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2843,22 +4541,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.Connection", - "shortName": "get_connection" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListAccountConnectorsAsyncPager", + "shortName": "list_account_connectors" }, - "description": "Sample for GetConnection", - "file": "developerconnect_v1_generated_developer_connect_get_connection_async.py", + "description": "Sample for ListAccountConnectors", + "file": "developerconnect_v1_generated_developer_connect_list_account_connectors_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetConnection_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListAccountConnectors_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2878,12 +4576,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_get_connection_async.py" + "title": "developerconnect_v1_generated_developer_connect_list_account_connectors_async.py" }, { "canonical": true, @@ -2892,22 +4590,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.get_connection", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.list_account_connectors", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetConnection", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListAccountConnectors", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "GetConnection" + "shortName": "ListAccountConnectors" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.GetConnectionRequest" + "type": "google.cloud.developerconnect_v1.types.ListAccountConnectorsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -2923,22 +4621,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.Connection", - "shortName": "get_connection" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListAccountConnectorsPager", + "shortName": "list_account_connectors" }, - "description": "Sample for GetConnection", - "file": "developerconnect_v1_generated_developer_connect_get_connection_sync.py", + "description": "Sample for ListAccountConnectors", + "file": "developerconnect_v1_generated_developer_connect_list_account_connectors_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetConnection_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListAccountConnectors_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -2958,12 +4656,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_get_connection_sync.py" + "title": "developerconnect_v1_generated_developer_connect_list_account_connectors_sync.py" }, { "canonical": true, @@ -2973,22 +4671,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.get_git_repository_link", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.list_connections", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetGitRepositoryLink", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListConnections", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "GetGitRepositoryLink" + "shortName": "ListConnections" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.GetGitRepositoryLinkRequest" + "type": "google.cloud.developerconnect_v1.types.ListConnectionsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3004,22 +4702,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.GitRepositoryLink", - "shortName": "get_git_repository_link" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListConnectionsAsyncPager", + "shortName": "list_connections" }, - "description": "Sample for GetGitRepositoryLink", - "file": "developerconnect_v1_generated_developer_connect_get_git_repository_link_async.py", + "description": "Sample for ListConnections", + "file": "developerconnect_v1_generated_developer_connect_list_connections_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetGitRepositoryLink_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListConnections_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3039,12 +4737,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_get_git_repository_link_async.py" + "title": "developerconnect_v1_generated_developer_connect_list_connections_async.py" }, { "canonical": true, @@ -3053,22 +4751,22 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.get_git_repository_link", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.list_connections", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.GetGitRepositoryLink", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListConnections", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "GetGitRepositoryLink" + "shortName": "ListConnections" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.GetGitRepositoryLinkRequest" + "type": "google.cloud.developerconnect_v1.types.ListConnectionsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -3084,22 +4782,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.types.GitRepositoryLink", - "shortName": "get_git_repository_link" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListConnectionsPager", + "shortName": "list_connections" }, - "description": "Sample for GetGitRepositoryLink", - "file": "developerconnect_v1_generated_developer_connect_get_git_repository_link_sync.py", + "description": "Sample for ListConnections", + "file": "developerconnect_v1_generated_developer_connect_list_connections_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_GetGitRepositoryLink_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListConnections_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -3119,12 +4817,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_get_git_repository_link_sync.py" + "title": "developerconnect_v1_generated_developer_connect_list_connections_sync.py" }, { "canonical": true, @@ -3134,19 +4832,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.list_account_connectors", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.list_git_repository_links", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListAccountConnectors", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListGitRepositoryLinks", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "ListAccountConnectors" + "shortName": "ListGitRepositoryLinks" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.ListAccountConnectorsRequest" + "type": "google.cloud.developerconnect_v1.types.ListGitRepositoryLinksRequest" }, { "name": "parent", @@ -3165,14 +4863,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListAccountConnectorsAsyncPager", - "shortName": "list_account_connectors" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListGitRepositoryLinksAsyncPager", + "shortName": "list_git_repository_links" }, - "description": "Sample for ListAccountConnectors", - "file": "developerconnect_v1_generated_developer_connect_list_account_connectors_async.py", + "description": "Sample for ListGitRepositoryLinks", + "file": "developerconnect_v1_generated_developer_connect_list_git_repository_links_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListAccountConnectors_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListGitRepositoryLinks_async", "segments": [ { "end": 52, @@ -3205,7 +4903,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_list_account_connectors_async.py" + "title": "developerconnect_v1_generated_developer_connect_list_git_repository_links_async.py" }, { "canonical": true, @@ -3214,19 +4912,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.list_account_connectors", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.list_git_repository_links", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListAccountConnectors", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListGitRepositoryLinks", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "ListAccountConnectors" + "shortName": "ListGitRepositoryLinks" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.ListAccountConnectorsRequest" + "type": "google.cloud.developerconnect_v1.types.ListGitRepositoryLinksRequest" }, { "name": "parent", @@ -3245,14 +4943,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListAccountConnectorsPager", - "shortName": "list_account_connectors" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListGitRepositoryLinksPager", + "shortName": "list_git_repository_links" }, - "description": "Sample for ListAccountConnectors", - "file": "developerconnect_v1_generated_developer_connect_list_account_connectors_sync.py", + "description": "Sample for ListGitRepositoryLinks", + "file": "developerconnect_v1_generated_developer_connect_list_git_repository_links_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListAccountConnectors_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListGitRepositoryLinks_sync", "segments": [ { "end": 52, @@ -3285,7 +4983,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_list_account_connectors_sync.py" + "title": "developerconnect_v1_generated_developer_connect_list_git_repository_links_sync.py" }, { "canonical": true, @@ -3295,19 +4993,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.list_connections", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.list_users", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListConnections", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListUsers", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "ListConnections" + "shortName": "ListUsers" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.ListConnectionsRequest" + "type": "google.cloud.developerconnect_v1.types.ListUsersRequest" }, { "name": "parent", @@ -3326,14 +5024,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListConnectionsAsyncPager", - "shortName": "list_connections" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListUsersAsyncPager", + "shortName": "list_users" }, - "description": "Sample for ListConnections", - "file": "developerconnect_v1_generated_developer_connect_list_connections_async.py", + "description": "Sample for ListUsers", + "file": "developerconnect_v1_generated_developer_connect_list_users_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListConnections_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListUsers_async", "segments": [ { "end": 52, @@ -3366,7 +5064,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_list_connections_async.py" + "title": "developerconnect_v1_generated_developer_connect_list_users_async.py" }, { "canonical": true, @@ -3375,19 +5073,19 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.list_connections", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.list_users", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListConnections", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListUsers", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "ListConnections" + "shortName": "ListUsers" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.ListConnectionsRequest" + "type": "google.cloud.developerconnect_v1.types.ListUsersRequest" }, { "name": "parent", @@ -3406,14 +5104,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListConnectionsPager", - "shortName": "list_connections" + "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListUsersPager", + "shortName": "list_users" }, - "description": "Sample for ListConnections", - "file": "developerconnect_v1_generated_developer_connect_list_connections_sync.py", + "description": "Sample for ListUsers", + "file": "developerconnect_v1_generated_developer_connect_list_users_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListConnections_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListUsers_sync", "segments": [ { "end": 52, @@ -3446,7 +5144,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_list_connections_sync.py" + "title": "developerconnect_v1_generated_developer_connect_list_users_sync.py" }, { "canonical": true, @@ -3456,22 +5154,26 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.list_git_repository_links", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.modify_git_repository_link_pull_request", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListGitRepositoryLinks", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ModifyGitRepositoryLinkPullRequest", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "ListGitRepositoryLinks" + "shortName": "ModifyGitRepositoryLinkPullRequest" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.ListGitRepositoryLinksRequest" + "type": "google.cloud.developerconnect_v1.types.ModifyGitRepositoryLinkPullRequestRequest" }, { - "name": "parent", + "name": "name", + "type": "str" + }, + { + "name": "pull_request_id", "type": "str" }, { @@ -3487,14 +5189,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListGitRepositoryLinksAsyncPager", - "shortName": "list_git_repository_links" + "resultType": "google.cloud.developerconnect_v1.types.PullRequest", + "shortName": "modify_git_repository_link_pull_request" }, - "description": "Sample for ListGitRepositoryLinks", - "file": "developerconnect_v1_generated_developer_connect_list_git_repository_links_async.py", + "description": "Sample for ModifyGitRepositoryLinkPullRequest", + "file": "developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListGitRepositoryLinks_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ModifyGitRepositoryLinkPullRequest_async", "segments": [ { "end": 52, @@ -3512,22 +5214,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": "developerconnect_v1_generated_developer_connect_list_git_repository_links_async.py" + "title": "developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_async.py" }, { "canonical": true, @@ -3536,22 +5238,26 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.list_git_repository_links", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.modify_git_repository_link_pull_request", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListGitRepositoryLinks", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ModifyGitRepositoryLinkPullRequest", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "ListGitRepositoryLinks" + "shortName": "ModifyGitRepositoryLinkPullRequest" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.ListGitRepositoryLinksRequest" + "type": "google.cloud.developerconnect_v1.types.ModifyGitRepositoryLinkPullRequestRequest" }, { - "name": "parent", + "name": "name", + "type": "str" + }, + { + "name": "pull_request_id", "type": "str" }, { @@ -3567,14 +5273,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListGitRepositoryLinksPager", - "shortName": "list_git_repository_links" + "resultType": "google.cloud.developerconnect_v1.types.PullRequest", + "shortName": "modify_git_repository_link_pull_request" }, - "description": "Sample for ListGitRepositoryLinks", - "file": "developerconnect_v1_generated_developer_connect_list_git_repository_links_sync.py", + "description": "Sample for ModifyGitRepositoryLinkPullRequest", + "file": "developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListGitRepositoryLinks_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_ModifyGitRepositoryLinkPullRequest_sync", "segments": [ { "end": 52, @@ -3592,22 +5298,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": "developerconnect_v1_generated_developer_connect_list_git_repository_links_sync.py" + "title": "developerconnect_v1_generated_developer_connect_modify_git_repository_link_pull_request_sync.py" }, { "canonical": true, @@ -3617,24 +5323,28 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient", "shortName": "DeveloperConnectAsyncClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.list_users", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectAsyncClient.open_git_repository_link_pull_request", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListUsers", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.OpenGitRepositoryLinkPullRequest", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "ListUsers" + "shortName": "OpenGitRepositoryLinkPullRequest" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.ListUsersRequest" + "type": "google.cloud.developerconnect_v1.types.OpenGitRepositoryLinkPullRequestRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, + { + "name": "pull_request", + "type": "google.cloud.developerconnect_v1.types.PullRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -3648,22 +5358,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListUsersAsyncPager", - "shortName": "list_users" + "resultType": "google.cloud.developerconnect_v1.types.PullRequest", + "shortName": "open_git_repository_link_pull_request" }, - "description": "Sample for ListUsers", - "file": "developerconnect_v1_generated_developer_connect_list_users_async.py", + "description": "Sample for OpenGitRepositoryLinkPullRequest", + "file": "developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListUsers_async", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_OpenGitRepositoryLinkPullRequest_async", "segments": [ { - "end": 52, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 58, "start": 27, "type": "SHORT" }, @@ -3673,22 +5383,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_list_users_async.py" + "title": "developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_async.py" }, { "canonical": true, @@ -3697,24 +5407,28 @@ "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient", "shortName": "DeveloperConnectClient" }, - "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.list_users", + "fullName": "google.cloud.developerconnect_v1.DeveloperConnectClient.open_git_repository_link_pull_request", "method": { - "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.ListUsers", + "fullName": "google.cloud.developerconnect.v1.DeveloperConnect.OpenGitRepositoryLinkPullRequest", "service": { "fullName": "google.cloud.developerconnect.v1.DeveloperConnect", "shortName": "DeveloperConnect" }, - "shortName": "ListUsers" + "shortName": "OpenGitRepositoryLinkPullRequest" }, "parameters": [ { "name": "request", - "type": "google.cloud.developerconnect_v1.types.ListUsersRequest" + "type": "google.cloud.developerconnect_v1.types.OpenGitRepositoryLinkPullRequestRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, + { + "name": "pull_request", + "type": "google.cloud.developerconnect_v1.types.PullRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -3728,22 +5442,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.developerconnect_v1.services.developer_connect.pagers.ListUsersPager", - "shortName": "list_users" + "resultType": "google.cloud.developerconnect_v1.types.PullRequest", + "shortName": "open_git_repository_link_pull_request" }, - "description": "Sample for ListUsers", - "file": "developerconnect_v1_generated_developer_connect_list_users_sync.py", + "description": "Sample for OpenGitRepositoryLinkPullRequest", + "file": "developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "developerconnect_v1_generated_DeveloperConnect_ListUsers_sync", + "regionTag": "developerconnect_v1_generated_DeveloperConnect_OpenGitRepositoryLinkPullRequest_sync", "segments": [ { - "end": 52, + "end": 58, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 58, "start": 27, "type": "SHORT" }, @@ -3753,22 +5467,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 52, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 55, + "start": 53, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 59, + "start": 56, "type": "RESPONSE_HANDLING" } ], - "title": "developerconnect_v1_generated_developer_connect_list_users_sync.py" + "title": "developerconnect_v1_generated_developer_connect_open_git_repository_link_pull_request_sync.py" }, { "canonical": true, diff --git a/packages/google-cloud-developerconnect/tests/unit/gapic/developerconnect_v1/test_developer_connect.py b/packages/google-cloud-developerconnect/tests/unit/gapic/developerconnect_v1/test_developer_connect.py index 81f06d8367e7..d1c8412e9ec8 100644 --- a/packages/google-cloud-developerconnect/tests/unit/gapic/developerconnect_v1/test_developer_connect.py +++ b/packages/google-cloud-developerconnect/tests/unit/gapic/developerconnect_v1/test_developer_connect.py @@ -5410,11 +5410,11 @@ async def test_fetch_read_token_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchLinkableGitRepositoriesRequest(), + developer_connect.OpenGitRepositoryLinkPullRequestRequest(), {}, ], ) -def test_fetch_linkable_git_repositories(request_type, transport: str = "grpc"): +def test_open_git_repository_link_pull_request(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5426,26 +5426,42 @@ def test_fetch_linkable_git_repositories(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), "__call__" + type(client.transport.open_git_repository_link_pull_request), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse( - next_page_token="next_page_token_value", - ) - response = client.fetch_linkable_git_repositories(request) + call.return_value = developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", + ) + response = client.open_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.FetchLinkableGitRepositoriesRequest() + request = developer_connect.OpenGitRepositoryLinkPullRequestRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchLinkableGitRepositoriesPager) - assert response.next_page_token == "next_page_token_value" - - -def test_fetch_linkable_git_repositories_non_empty_request_with_auto_populated_field(): + assert isinstance(response, developer_connect.PullRequest) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.body == "body_value" + assert response.head_ref == "head_ref_value" + assert response.base_ref == "base_ref_value" + assert response.author == "author_value" + assert response.state == developer_connect.PullRequest.State.OPEN + assert response.mergeability == developer_connect.PullRequest.Mergeability.MERGEABLE + assert response.html_url == "html_url_value" + + +def test_open_git_repository_link_pull_request_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 = DeveloperConnectClient( @@ -5456,29 +5472,27 @@ def test_fetch_linkable_git_repositories_non_empty_request_with_auto_populated_f # 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 = developer_connect.FetchLinkableGitRepositoriesRequest( - connection="connection_value", - page_token="page_token_value", + request = developer_connect.OpenGitRepositoryLinkPullRequestRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), "__call__" + type(client.transport.open_git_repository_link_pull_request), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.fetch_linkable_git_repositories(request=request) + client.open_git_repository_link_pull_request(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchLinkableGitRepositoriesRequest( - connection="connection_value", - page_token="page_token_value", + request_msg = developer_connect.OpenGitRepositoryLinkPullRequestRequest( + name="name_value", ) assert args[0] == request_msg -def test_fetch_linkable_git_repositories_use_cached_wrapped_rpc(): +def test_open_git_repository_link_pull_request_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: @@ -5493,7 +5507,7 @@ def test_fetch_linkable_git_repositories_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_linkable_git_repositories + client._transport.open_git_repository_link_pull_request in client._transport._wrapped_methods ) @@ -5503,15 +5517,15 @@ def test_fetch_linkable_git_repositories_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_linkable_git_repositories + client._transport.open_git_repository_link_pull_request ] = mock_rpc request = {} - client.fetch_linkable_git_repositories(request) + client.open_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_linkable_git_repositories(request) + client.open_git_repository_link_pull_request(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5519,7 +5533,7 @@ def test_fetch_linkable_git_repositories_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_fetch_linkable_git_repositories_async_use_cached_wrapped_rpc( +async def test_open_git_repository_link_pull_request_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5536,7 +5550,7 @@ async def test_fetch_linkable_git_repositories_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.fetch_linkable_git_repositories + client._client._transport.open_git_repository_link_pull_request in client._client._transport._wrapped_methods ) @@ -5544,16 +5558,16 @@ async def test_fetch_linkable_git_repositories_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.fetch_linkable_git_repositories + client._client._transport.open_git_repository_link_pull_request ] = mock_rpc request = {} - await client.fetch_linkable_git_repositories(request) + await client.open_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_linkable_git_repositories(request) + await client.open_git_repository_link_pull_request(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5564,11 +5578,11 @@ async def test_fetch_linkable_git_repositories_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchLinkableGitRepositoriesRequest(), + developer_connect.OpenGitRepositoryLinkPullRequestRequest(), {}, ], ) -async def test_fetch_linkable_git_repositories_async( +async def test_open_git_repository_link_pull_request_async( request_type, transport: str = "grpc_asyncio" ): client = DeveloperConnectAsyncClient( @@ -5582,44 +5596,60 @@ async def test_fetch_linkable_git_repositories_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), "__call__" + type(client.transport.open_git_repository_link_pull_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchLinkableGitRepositoriesResponse( - next_page_token="next_page_token_value", + developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", ) ) - response = await client.fetch_linkable_git_repositories(request) + response = await client.open_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.FetchLinkableGitRepositoriesRequest() + request = developer_connect.OpenGitRepositoryLinkPullRequestRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchLinkableGitRepositoriesAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, developer_connect.PullRequest) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.body == "body_value" + assert response.head_ref == "head_ref_value" + assert response.base_ref == "base_ref_value" + assert response.author == "author_value" + assert response.state == developer_connect.PullRequest.State.OPEN + assert response.mergeability == developer_connect.PullRequest.Mergeability.MERGEABLE + assert response.html_url == "html_url_value" -def test_fetch_linkable_git_repositories_field_headers(): +def test_open_git_repository_link_pull_request_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.FetchLinkableGitRepositoriesRequest() + request = developer_connect.OpenGitRepositoryLinkPullRequestRequest() - request.connection = "connection_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), "__call__" + type(client.transport.open_git_repository_link_pull_request), "__call__" ) as call: - call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() - client.fetch_linkable_git_repositories(request) + call.return_value = developer_connect.PullRequest() + client.open_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5630,30 +5660,30 @@ def test_fetch_linkable_git_repositories_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "connection=connection_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_fetch_linkable_git_repositories_field_headers_async(): +async def test_open_git_repository_link_pull_request_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.FetchLinkableGitRepositoriesRequest() + request = developer_connect.OpenGitRepositoryLinkPullRequestRequest() - request.connection = "connection_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), "__call__" + type(client.transport.open_git_repository_link_pull_request), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchLinkableGitRepositoriesResponse() + developer_connect.PullRequest() ) - await client.fetch_linkable_git_repositories(request) + await client.open_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5664,37 +5694,41 @@ async def test_fetch_linkable_git_repositories_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "connection=connection_value", + "name=name_value", ) in kw["metadata"] -def test_fetch_linkable_git_repositories_flattened(): +def test_open_git_repository_link_pull_request_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), "__call__" + type(client.transport.open_git_repository_link_pull_request), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() + call.return_value = developer_connect.PullRequest() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.fetch_linkable_git_repositories( - connection="connection_value", + client.open_git_repository_link_pull_request( + name="name_value", + pull_request=developer_connect.PullRequest(id="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].connection - mock_val = "connection_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].pull_request + mock_val = developer_connect.PullRequest(id="id_value") assert arg == mock_val -def test_fetch_linkable_git_repositories_flattened_error(): +def test_open_git_repository_link_pull_request_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5702,45 +5736,50 @@ def test_fetch_linkable_git_repositories_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_linkable_git_repositories( - developer_connect.FetchLinkableGitRepositoriesRequest(), - connection="connection_value", + client.open_git_repository_link_pull_request( + developer_connect.OpenGitRepositoryLinkPullRequestRequest(), + name="name_value", + pull_request=developer_connect.PullRequest(id="id_value"), ) @pytest.mark.asyncio -async def test_fetch_linkable_git_repositories_flattened_async(): +async def test_open_git_repository_link_pull_request_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), "__call__" + type(client.transport.open_git_repository_link_pull_request), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() + call.return_value = developer_connect.PullRequest() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchLinkableGitRepositoriesResponse() + developer_connect.PullRequest() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.fetch_linkable_git_repositories( - connection="connection_value", + response = await client.open_git_repository_link_pull_request( + name="name_value", + pull_request=developer_connect.PullRequest(id="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].connection - mock_val = "connection_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].pull_request + mock_val = developer_connect.PullRequest(id="id_value") assert arg == mock_val @pytest.mark.asyncio -async def test_fetch_linkable_git_repositories_flattened_error_async(): +async def test_open_git_repository_link_pull_request_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5748,297 +5787,92 @@ async def test_fetch_linkable_git_repositories_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.fetch_linkable_git_repositories( - developer_connect.FetchLinkableGitRepositoriesRequest(), - connection="connection_value", + await client.open_git_repository_link_pull_request( + developer_connect.OpenGitRepositoryLinkPullRequestRequest(), + name="name_value", + pull_request=developer_connect.PullRequest(id="id_value"), ) -def test_fetch_linkable_git_repositories_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.FetchLinkableGitRepositoriesRequest(), + {}, + ], +) +def test_fetch_linkable_git_repositories(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.fetch_linkable_git_repositories), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - next_page_token="abc", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[], - next_page_token="def", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - ], - next_page_token="ghi", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("connection", ""),)), - ) - pager = client.fetch_linkable_git_repositories( - request={}, retry=retry, timeout=timeout + # Designate an appropriate return value for the call. + call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse( + next_page_token="next_page_token_value", ) + response = client.fetch_linkable_git_repositories(request) - 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__}<") + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.FetchLinkableGitRepositoriesRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all( - isinstance(i, developer_connect.LinkableGitRepository) for i in results - ) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchLinkableGitRepositoriesPager) + assert response.next_page_token == "next_page_token_value" -def test_fetch_linkable_git_repositories_pages(transport_name: str = "grpc"): +def test_fetch_linkable_git_repositories_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + 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 = developer_connect.FetchLinkableGitRepositoriesRequest( + connection="connection_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.fetch_linkable_git_repositories), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - next_page_token="abc", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[], - next_page_token="def", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - ], - next_page_token="ghi", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - ), - RuntimeError, + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - pages = list(client.fetch_linkable_git_repositories(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.fetch_linkable_git_repositories(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchLinkableGitRepositoriesRequest( + connection="connection_value", + page_token="page_token_value", + ) + assert args[0] == request_msg -@pytest.mark.asyncio -async def test_fetch_linkable_git_repositories_async_pager(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - next_page_token="abc", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[], - next_page_token="def", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - ], - next_page_token="ghi", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - ), - RuntimeError, - ) - async_pager = await client.fetch_linkable_git_repositories( - 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, developer_connect.LinkableGitRepository) for i in responses - ) - - -@pytest.mark.asyncio -async def test_fetch_linkable_git_repositories_async_pages(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - next_page_token="abc", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[], - next_page_token="def", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - ], - next_page_token="ghi", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in ( - await client.fetch_linkable_git_repositories(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", - [ - developer_connect.FetchGitHubInstallationsRequest(), - {}, - ], -) -def test_fetch_git_hub_installations(request_type, transport: str = "grpc"): - client = DeveloperConnectClient( - 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.fetch_git_hub_installations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchGitHubInstallationsResponse() - response = client.fetch_git_hub_installations(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = developer_connect.FetchGitHubInstallationsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.FetchGitHubInstallationsResponse) - - -def test_fetch_git_hub_installations_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 = DeveloperConnectClient( - 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 = developer_connect.FetchGitHubInstallationsRequest( - connection="connection_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_git_hub_installations), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.fetch_git_hub_installations(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchGitHubInstallationsRequest( - connection="connection_value", - ) - assert args[0] == request_msg - - -def test_fetch_git_hub_installations_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 = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) +def test_fetch_linkable_git_repositories_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 = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -6046,7 +5880,7 @@ def test_fetch_git_hub_installations_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_git_hub_installations + client._transport.fetch_linkable_git_repositories in client._transport._wrapped_methods ) @@ -6056,15 +5890,15 @@ def test_fetch_git_hub_installations_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.fetch_git_hub_installations + client._transport.fetch_linkable_git_repositories ] = mock_rpc request = {} - client.fetch_git_hub_installations(request) + client.fetch_linkable_git_repositories(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_git_hub_installations(request) + client.fetch_linkable_git_repositories(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6072,7 +5906,7 @@ def test_fetch_git_hub_installations_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_fetch_git_hub_installations_async_use_cached_wrapped_rpc( +async def test_fetch_linkable_git_repositories_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6089,7 +5923,7 @@ async def test_fetch_git_hub_installations_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.fetch_git_hub_installations + client._client._transport.fetch_linkable_git_repositories in client._client._transport._wrapped_methods ) @@ -6097,16 +5931,16 @@ async def test_fetch_git_hub_installations_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.fetch_git_hub_installations + client._client._transport.fetch_linkable_git_repositories ] = mock_rpc request = {} - await client.fetch_git_hub_installations(request) + await client.fetch_linkable_git_repositories(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_git_hub_installations(request) + await client.fetch_linkable_git_repositories(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6117,11 +5951,11 @@ async def test_fetch_git_hub_installations_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchGitHubInstallationsRequest(), + developer_connect.FetchLinkableGitRepositoriesRequest(), {}, ], ) -async def test_fetch_git_hub_installations_async( +async def test_fetch_linkable_git_repositories_async( request_type, transport: str = "grpc_asyncio" ): client = DeveloperConnectAsyncClient( @@ -6135,41 +5969,44 @@ async def test_fetch_git_hub_installations_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_git_hub_installations), "__call__" + type(client.transport.fetch_linkable_git_repositories), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchGitHubInstallationsResponse() + developer_connect.FetchLinkableGitRepositoriesResponse( + next_page_token="next_page_token_value", + ) ) - response = await client.fetch_git_hub_installations(request) + response = await client.fetch_linkable_git_repositories(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.FetchGitHubInstallationsRequest() + request = developer_connect.FetchLinkableGitRepositoriesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.FetchGitHubInstallationsResponse) + assert isinstance(response, pagers.FetchLinkableGitRepositoriesAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_fetch_git_hub_installations_field_headers(): +def test_fetch_linkable_git_repositories_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.FetchGitHubInstallationsRequest() + request = developer_connect.FetchLinkableGitRepositoriesRequest() request.connection = "connection_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_git_hub_installations), "__call__" + type(client.transport.fetch_linkable_git_repositories), "__call__" ) as call: - call.return_value = developer_connect.FetchGitHubInstallationsResponse() - client.fetch_git_hub_installations(request) + call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() + client.fetch_linkable_git_repositories(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6185,25 +6022,25 @@ def test_fetch_git_hub_installations_field_headers(): @pytest.mark.asyncio -async def test_fetch_git_hub_installations_field_headers_async(): +async def test_fetch_linkable_git_repositories_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.FetchGitHubInstallationsRequest() + request = developer_connect.FetchLinkableGitRepositoriesRequest() request.connection = "connection_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_git_hub_installations), "__call__" + type(client.transport.fetch_linkable_git_repositories), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchGitHubInstallationsResponse() + developer_connect.FetchLinkableGitRepositoriesResponse() ) - await client.fetch_git_hub_installations(request) + await client.fetch_linkable_git_repositories(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6218,20 +6055,20 @@ async def test_fetch_git_hub_installations_field_headers_async(): ) in kw["metadata"] -def test_fetch_git_hub_installations_flattened(): +def test_fetch_linkable_git_repositories_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_git_hub_installations), "__call__" + type(client.transport.fetch_linkable_git_repositories), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchGitHubInstallationsResponse() + call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.fetch_git_hub_installations( + client.fetch_linkable_git_repositories( connection="connection_value", ) @@ -6244,7 +6081,7 @@ def test_fetch_git_hub_installations_flattened(): assert arg == mock_val -def test_fetch_git_hub_installations_flattened_error(): +def test_fetch_linkable_git_repositories_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6252,31 +6089,31 @@ def test_fetch_git_hub_installations_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_git_hub_installations( - developer_connect.FetchGitHubInstallationsRequest(), + client.fetch_linkable_git_repositories( + developer_connect.FetchLinkableGitRepositoriesRequest(), connection="connection_value", ) @pytest.mark.asyncio -async def test_fetch_git_hub_installations_flattened_async(): +async def test_fetch_linkable_git_repositories_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_git_hub_installations), "__call__" + type(client.transport.fetch_linkable_git_repositories), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchGitHubInstallationsResponse() + call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchGitHubInstallationsResponse() + developer_connect.FetchLinkableGitRepositoriesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.fetch_git_hub_installations( + response = await client.fetch_linkable_git_repositories( connection="connection_value", ) @@ -6290,7 +6127,7 @@ async def test_fetch_git_hub_installations_flattened_async(): @pytest.mark.asyncio -async def test_fetch_git_hub_installations_flattened_error_async(): +async def test_fetch_linkable_git_repositories_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6298,51 +6135,259 @@ async def test_fetch_git_hub_installations_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.fetch_git_hub_installations( - developer_connect.FetchGitHubInstallationsRequest(), + await client.fetch_linkable_git_repositories( + developer_connect.FetchLinkableGitRepositoriesRequest(), connection="connection_value", ) -@pytest.mark.parametrize( - "request_type", - [ - developer_connect.FetchGitRefsRequest(), - {}, - ], -) -def test_fetch_git_refs(request_type, transport: str = "grpc"): +def test_fetch_linkable_git_repositories_pager(transport_name: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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.fetch_git_refs), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchGitRefsResponse( - ref_names=["ref_names_value"], - next_page_token="next_page_token_value", + with mock.patch.object( + type(client.transport.fetch_linkable_git_repositories), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + next_page_token="abc", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[], + next_page_token="def", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + ], + next_page_token="ghi", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + ), + RuntimeError, ) - response = client.fetch_git_refs(request) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("connection", ""),)), + ) + pager = client.fetch_linkable_git_repositories( + 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, developer_connect.LinkableGitRepository) for i in results + ) + + +def test_fetch_linkable_git_repositories_pages(transport_name: str = "grpc"): + client = DeveloperConnectClient( + 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.fetch_linkable_git_repositories), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + next_page_token="abc", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[], + next_page_token="def", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + ], + next_page_token="ghi", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + ), + RuntimeError, + ) + pages = list(client.fetch_linkable_git_repositories(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_fetch_linkable_git_repositories_async_pager(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_linkable_git_repositories), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + next_page_token="abc", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[], + next_page_token="def", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + ], + next_page_token="ghi", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_linkable_git_repositories( + 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, developer_connect.LinkableGitRepository) for i in responses + ) + + +@pytest.mark.asyncio +async def test_fetch_linkable_git_repositories_async_pages(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_linkable_git_repositories), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + next_page_token="abc", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[], + next_page_token="def", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + ], + next_page_token="ghi", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.fetch_linkable_git_repositories(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", + [ + developer_connect.FetchGitHubInstallationsRequest(), + {}, + ], +) +def test_fetch_git_hub_installations(request_type, transport: str = "grpc"): + client = DeveloperConnectClient( + 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.fetch_git_hub_installations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.FetchGitHubInstallationsResponse() + response = client.fetch_git_hub_installations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.FetchGitRefsRequest() + request = developer_connect.FetchGitHubInstallationsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchGitRefsPager) - assert response.ref_names == ["ref_names_value"] - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, developer_connect.FetchGitHubInstallationsResponse) -def test_fetch_git_refs_non_empty_request_with_auto_populated_field(): +def test_fetch_git_hub_installations_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 = DeveloperConnectClient( @@ -6353,27 +6398,27 @@ def test_fetch_git_refs_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 = developer_connect.FetchGitRefsRequest( - git_repository_link="git_repository_link_value", - page_token="page_token_value", + request = developer_connect.FetchGitHubInstallationsRequest( + connection="connection_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_hub_installations), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.fetch_git_refs(request=request) + client.fetch_git_hub_installations(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchGitRefsRequest( - git_repository_link="git_repository_link_value", - page_token="page_token_value", + request_msg = developer_connect.FetchGitHubInstallationsRequest( + connection="connection_value", ) assert args[0] == request_msg -def test_fetch_git_refs_use_cached_wrapped_rpc(): +def test_fetch_git_hub_installations_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: @@ -6387,21 +6432,26 @@ def test_fetch_git_refs_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.fetch_git_refs in client._transport._wrapped_methods + assert ( + client._transport.fetch_git_hub_installations + 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.fetch_git_refs] = mock_rpc + client._transport._wrapped_methods[ + client._transport.fetch_git_hub_installations + ] = mock_rpc request = {} - client.fetch_git_refs(request) + client.fetch_git_hub_installations(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_git_refs(request) + client.fetch_git_hub_installations(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6409,7 +6459,7 @@ def test_fetch_git_refs_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_fetch_git_refs_async_use_cached_wrapped_rpc( +async def test_fetch_git_hub_installations_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6426,7 +6476,7 @@ async def test_fetch_git_refs_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.fetch_git_refs + client._client._transport.fetch_git_hub_installations in client._client._transport._wrapped_methods ) @@ -6434,16 +6484,16 @@ async def test_fetch_git_refs_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.fetch_git_refs + client._client._transport.fetch_git_hub_installations ] = mock_rpc request = {} - await client.fetch_git_refs(request) + await client.fetch_git_hub_installations(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_git_refs(request) + await client.fetch_git_hub_installations(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6454,11 +6504,13 @@ async def test_fetch_git_refs_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchGitRefsRequest(), + developer_connect.FetchGitHubInstallationsRequest(), {}, ], ) -async def test_fetch_git_refs_async(request_type, transport: str = "grpc_asyncio"): +async def test_fetch_git_hub_installations_async( + request_type, transport: str = "grpc_asyncio" +): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -6469,43 +6521,42 @@ async def test_fetch_git_refs_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.fetch_git_refs), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_hub_installations), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchGitRefsResponse( - ref_names=["ref_names_value"], - next_page_token="next_page_token_value", - ) + developer_connect.FetchGitHubInstallationsResponse() ) - response = await client.fetch_git_refs(request) + response = await client.fetch_git_hub_installations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.FetchGitRefsRequest() + request = developer_connect.FetchGitHubInstallationsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchGitRefsAsyncPager) - assert response.ref_names == ["ref_names_value"] - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, developer_connect.FetchGitHubInstallationsResponse) -def test_fetch_git_refs_field_headers(): +def test_fetch_git_hub_installations_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.FetchGitRefsRequest() + request = developer_connect.FetchGitHubInstallationsRequest() - request.git_repository_link = "git_repository_link_value" + request.connection = "connection_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: - call.return_value = developer_connect.FetchGitRefsResponse() - client.fetch_git_refs(request) + with mock.patch.object( + type(client.transport.fetch_git_hub_installations), "__call__" + ) as call: + call.return_value = developer_connect.FetchGitHubInstallationsResponse() + client.fetch_git_hub_installations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6516,28 +6567,30 @@ def test_fetch_git_refs_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "git_repository_link=git_repository_link_value", + "connection=connection_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_fetch_git_refs_field_headers_async(): +async def test_fetch_git_hub_installations_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.FetchGitRefsRequest() + request = developer_connect.FetchGitHubInstallationsRequest() - request.git_repository_link = "git_repository_link_value" + request.connection = "connection_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_hub_installations), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchGitRefsResponse() + developer_connect.FetchGitHubInstallationsResponse() ) - await client.fetch_git_refs(request) + await client.fetch_git_hub_installations(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6548,39 +6601,37 @@ async def test_fetch_git_refs_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "git_repository_link=git_repository_link_value", + "connection=connection_value", ) in kw["metadata"] -def test_fetch_git_refs_flattened(): +def test_fetch_git_hub_installations_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_hub_installations), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchGitRefsResponse() + call.return_value = developer_connect.FetchGitHubInstallationsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.fetch_git_refs( - git_repository_link="git_repository_link_value", - ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, + client.fetch_git_hub_installations( + connection="connection_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].git_repository_link - mock_val = "git_repository_link_value" - assert arg == mock_val - arg = args[0].ref_type - mock_val = developer_connect.FetchGitRefsRequest.RefType.TAG + arg = args[0].connection + mock_val = "connection_value" assert arg == mock_val -def test_fetch_git_refs_flattened_error(): +def test_fetch_git_hub_installations_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6588,48 +6639,45 @@ def test_fetch_git_refs_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_git_refs( - developer_connect.FetchGitRefsRequest(), - git_repository_link="git_repository_link_value", - ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, + client.fetch_git_hub_installations( + developer_connect.FetchGitHubInstallationsRequest(), + connection="connection_value", ) @pytest.mark.asyncio -async def test_fetch_git_refs_flattened_async(): +async def test_fetch_git_hub_installations_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_hub_installations), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchGitRefsResponse() + call.return_value = developer_connect.FetchGitHubInstallationsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchGitRefsResponse() + developer_connect.FetchGitHubInstallationsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.fetch_git_refs( - git_repository_link="git_repository_link_value", - ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, + response = await client.fetch_git_hub_installations( + connection="connection_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].git_repository_link - mock_val = "git_repository_link_value" - assert arg == mock_val - arg = args[0].ref_type - mock_val = developer_connect.FetchGitRefsRequest.RefType.TAG + arg = args[0].connection + mock_val = "connection_value" assert arg == mock_val @pytest.mark.asyncio -async def test_fetch_git_refs_flattened_error_async(): +async def test_fetch_git_hub_installations_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6637,286 +6685,82 @@ async def test_fetch_git_refs_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.fetch_git_refs( - developer_connect.FetchGitRefsRequest(), - git_repository_link="git_repository_link_value", - ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, + await client.fetch_git_hub_installations( + developer_connect.FetchGitHubInstallationsRequest(), + connection="connection_value", ) -def test_fetch_git_refs_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.FetchGitRefsRequest(), + {}, + ], +) +def test_fetch_git_refs(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - str(), - ], - next_page_token="abc", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[], - next_page_token="def", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - ], - next_page_token="ghi", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("git_repository_link", ""),)), + # Designate an appropriate return value for the call. + call.return_value = developer_connect.FetchGitRefsResponse( + ref_names=["ref_names_value"], + next_page_token="next_page_token_value", ) - pager = client.fetch_git_refs(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + response = client.fetch_git_refs(request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.FetchGitRefsRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, str) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchGitRefsPager) + assert response.ref_names == ["ref_names_value"] + assert response.next_page_token == "next_page_token_value" -def test_fetch_git_refs_pages(transport_name: str = "grpc"): +def test_fetch_git_refs_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + 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 = developer_connect.FetchGitRefsRequest( + git_repository_link="git_repository_link_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - str(), - ], - next_page_token="abc", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[], - next_page_token="def", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - ], - next_page_token="ghi", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - ], - ), - RuntimeError, + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - pages = list(client.fetch_git_refs(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_fetch_git_refs_async_pager(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_git_refs), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - str(), - ], - next_page_token="abc", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[], - next_page_token="def", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - ], - next_page_token="ghi", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - ], - ), - RuntimeError, - ) - async_pager = await client.fetch_git_refs( - 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, str) for i in responses) - - -@pytest.mark.asyncio -async def test_fetch_git_refs_async_pages(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.fetch_git_refs), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - str(), - ], - next_page_token="abc", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[], - next_page_token="def", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - ], - next_page_token="ghi", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.fetch_git_refs(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", - [ - developer_connect.ListAccountConnectorsRequest(), - {}, - ], -) -def test_list_account_connectors(request_type, transport: str = "grpc"): - client = DeveloperConnectClient( - 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_account_connectors), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = developer_connect.ListAccountConnectorsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_account_connectors(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = developer_connect.ListAccountConnectorsRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountConnectorsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - - -def test_list_account_connectors_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 = DeveloperConnectClient( - 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 = developer_connect.ListAccountConnectorsRequest( - 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_account_connectors), "__call__" - ) as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. - ) - client.list_account_connectors(request=request) + client.fetch_git_refs(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListAccountConnectorsRequest( - parent="parent_value", + request_msg = developer_connect.FetchGitRefsRequest( + git_repository_link="git_repository_link_value", page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", ) assert args[0] == request_msg -def test_list_account_connectors_use_cached_wrapped_rpc(): +def test_fetch_git_refs_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: @@ -6930,26 +6774,21 @@ def test_list_account_connectors_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_account_connectors - in client._transport._wrapped_methods - ) + assert client._transport.fetch_git_refs 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_account_connectors - ] = mock_rpc + client._transport._wrapped_methods[client._transport.fetch_git_refs] = mock_rpc request = {} - client.list_account_connectors(request) + client.fetch_git_refs(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_account_connectors(request) + client.fetch_git_refs(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6957,7 +6796,7 @@ def test_list_account_connectors_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_account_connectors_async_use_cached_wrapped_rpc( +async def test_fetch_git_refs_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6974,7 +6813,7 @@ async def test_list_account_connectors_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_account_connectors + client._client._transport.fetch_git_refs in client._client._transport._wrapped_methods ) @@ -6982,16 +6821,16 @@ async def test_list_account_connectors_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_account_connectors + client._client._transport.fetch_git_refs ] = mock_rpc request = {} - await client.list_account_connectors(request) + await client.fetch_git_refs(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_account_connectors(request) + await client.fetch_git_refs(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7002,13 +6841,11 @@ async def test_list_account_connectors_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.ListAccountConnectorsRequest(), + developer_connect.FetchGitRefsRequest(), {}, ], ) -async def test_list_account_connectors_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_fetch_git_refs_async(request_type, transport: str = "grpc_asyncio"): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -7019,47 +6856,43 @@ async def test_list_account_connectors_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_connectors), "__call__" - ) as call: + with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListAccountConnectorsResponse( + developer_connect.FetchGitRefsResponse( + ref_names=["ref_names_value"], next_page_token="next_page_token_value", - unreachable=["unreachable_value"], ) ) - response = await client.list_account_connectors(request) + response = await client.fetch_git_refs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.ListAccountConnectorsRequest() + request = developer_connect.FetchGitRefsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAccountConnectorsAsyncPager) + assert isinstance(response, pagers.FetchGitRefsAsyncPager) + assert response.ref_names == ["ref_names_value"] assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] -def test_list_account_connectors_field_headers(): +def test_fetch_git_refs_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.ListAccountConnectorsRequest() + request = developer_connect.FetchGitRefsRequest() - request.parent = "parent_value" + request.git_repository_link = "git_repository_link_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_connectors), "__call__" - ) as call: - call.return_value = developer_connect.ListAccountConnectorsResponse() - client.list_account_connectors(request) + with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: + call.return_value = developer_connect.FetchGitRefsResponse() + client.fetch_git_refs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7070,30 +6903,28 @@ def test_list_account_connectors_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "git_repository_link=git_repository_link_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_account_connectors_field_headers_async(): +async def test_fetch_git_refs_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.ListAccountConnectorsRequest() + request = developer_connect.FetchGitRefsRequest() - request.parent = "parent_value" + request.git_repository_link = "git_repository_link_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_connectors), "__call__" - ) as call: + with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListAccountConnectorsResponse() + developer_connect.FetchGitRefsResponse() ) - await client.list_account_connectors(request) + await client.fetch_git_refs(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7104,37 +6935,39 @@ async def test_list_account_connectors_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "git_repository_link=git_repository_link_value", ) in kw["metadata"] -def test_list_account_connectors_flattened(): +def test_fetch_git_refs_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_connectors), "__call__" - ) as call: + with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.ListAccountConnectorsResponse() + call.return_value = developer_connect.FetchGitRefsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_account_connectors( - parent="parent_value", + client.fetch_git_refs( + git_repository_link="git_repository_link_value", + ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].git_repository_link + mock_val = "git_repository_link_value" + assert arg == mock_val + arg = args[0].ref_type + mock_val = developer_connect.FetchGitRefsRequest.RefType.TAG assert arg == mock_val -def test_list_account_connectors_flattened_error(): +def test_fetch_git_refs_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7142,45 +6975,48 @@ def test_list_account_connectors_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_account_connectors( - developer_connect.ListAccountConnectorsRequest(), - parent="parent_value", + client.fetch_git_refs( + developer_connect.FetchGitRefsRequest(), + git_repository_link="git_repository_link_value", + ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, ) @pytest.mark.asyncio -async def test_list_account_connectors_flattened_async(): +async def test_fetch_git_refs_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_account_connectors), "__call__" - ) as call: + with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.ListAccountConnectorsResponse() + call.return_value = developer_connect.FetchGitRefsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListAccountConnectorsResponse() + developer_connect.FetchGitRefsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_account_connectors( - parent="parent_value", + response = await client.fetch_git_refs( + git_repository_link="git_repository_link_value", + ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].git_repository_link + mock_val = "git_repository_link_value" + assert arg == mock_val + arg = args[0].ref_type + mock_val = developer_connect.FetchGitRefsRequest.RefType.TAG assert arg == mock_val @pytest.mark.asyncio -async def test_list_account_connectors_flattened_error_async(): +async def test_fetch_git_refs_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -7188,46 +7024,45 @@ async def test_list_account_connectors_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.list_account_connectors( - developer_connect.ListAccountConnectorsRequest(), - parent="parent_value", + await client.fetch_git_refs( + developer_connect.FetchGitRefsRequest(), + git_repository_link="git_repository_link_value", + ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, ) -def test_list_account_connectors_pager(transport_name: str = "grpc"): +def test_fetch_git_refs_pager(transport_name: str = "grpc"): client = DeveloperConnectClient( 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_account_connectors), "__call__" - ) as call: + with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), + str(), ], next_page_token="abc", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[], + developer_connect.FetchGitRefsResponse( + ref_names=[], next_page_token="def", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), ], next_page_token="ghi", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), ], ), RuntimeError, @@ -7237,9 +7072,9 @@ def test_list_account_connectors_pager(transport_name: str = "grpc"): retry = retries.Retry() timeout = 5 expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata((("git_repository_link", ""),)), ) - pager = client.list_account_connectors(request={}, retry=retry, timeout=timeout) + pager = client.fetch_git_refs(request={}, retry=retry, timeout=timeout) assert pager._metadata == expected_metadata assert pager._retry == retry @@ -7250,93 +7085,89 @@ def test_list_account_connectors_pager(transport_name: str = "grpc"): results = list(pager) assert len(results) == 6 - assert all(isinstance(i, developer_connect.AccountConnector) for i in results) + assert all(isinstance(i, str) for i in results) -def test_list_account_connectors_pages(transport_name: str = "grpc"): +def test_fetch_git_refs_pages(transport_name: str = "grpc"): client = DeveloperConnectClient( 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_account_connectors), "__call__" - ) as call: + with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), + str(), ], next_page_token="abc", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[], + developer_connect.FetchGitRefsResponse( + ref_names=[], next_page_token="def", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), ], next_page_token="ghi", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), ], ), RuntimeError, ) - pages = list(client.list_account_connectors(request={}).pages) + pages = list(client.fetch_git_refs(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_account_connectors_async_pager(): +async def test_fetch_git_refs_async_pager(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_connectors), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.fetch_git_refs), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), + str(), ], next_page_token="abc", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[], + developer_connect.FetchGitRefsResponse( + ref_names=[], next_page_token="def", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), ], next_page_token="ghi", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), ], ), RuntimeError, ) - async_pager = await client.list_account_connectors( + async_pager = await client.fetch_git_refs( request={}, ) assert async_pager.next_page_token == "abc" @@ -7347,51 +7178,49 @@ async def test_list_account_connectors_async_pager(): responses.append(response) assert len(responses) == 6 - assert all(isinstance(i, developer_connect.AccountConnector) for i in responses) + assert all(isinstance(i, str) for i in responses) @pytest.mark.asyncio -async def test_list_account_connectors_async_pages(): +async def test_fetch_git_refs_async_pages(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_account_connectors), - "__call__", - new_callable=mock.AsyncMock, + type(client.transport.fetch_git_refs), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), + str(), ], next_page_token="abc", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[], + developer_connect.FetchGitRefsResponse( + ref_names=[], next_page_token="def", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), ], next_page_token="ghi", ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), ], ), RuntimeError, ) pages = [] - async for page_ in (await client.list_account_connectors(request={})).pages: + async for page_ in (await client.fetch_git_refs(request={})).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @@ -7400,11 +7229,11 @@ async def test_list_account_connectors_async_pages(): @pytest.mark.parametrize( "request_type", [ - developer_connect.GetAccountConnectorRequest(), + developer_connect.DiffGitRepositoryLinkCommitRequest(), {}, ], ) -def test_get_account_connector(request_type, transport: str = "grpc"): +def test_diff_git_repository_link_commit(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7416,30 +7245,23 @@ def test_get_account_connector(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_connector), "__call__" + type(client.transport.diff_git_repository_link_commit), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.AccountConnector( - name="name_value", - etag="etag_value", - oauth_start_uri="oauth_start_uri_value", - ) - response = client.get_account_connector(request) + call.return_value = developer_connect.DiffGitRepositoryLinkCommitResponse() + response = client.diff_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.GetAccountConnectorRequest() + request = developer_connect.DiffGitRepositoryLinkCommitRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.AccountConnector) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.oauth_start_uri == "oauth_start_uri_value" + assert isinstance(response, developer_connect.DiffGitRepositoryLinkCommitResponse) -def test_get_account_connector_non_empty_request_with_auto_populated_field(): +def test_diff_git_repository_link_commit_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 = DeveloperConnectClient( @@ -7450,27 +7272,31 @@ def test_get_account_connector_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 = developer_connect.GetAccountConnectorRequest( + request = developer_connect.DiffGitRepositoryLinkCommitRequest( name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_connector), "__call__" + type(client.transport.diff_git_repository_link_commit), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_account_connector(request=request) + client.diff_git_repository_link_commit(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.GetAccountConnectorRequest( + request_msg = developer_connect.DiffGitRepositoryLinkCommitRequest( name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", ) assert args[0] == request_msg -def test_get_account_connector_use_cached_wrapped_rpc(): +def test_diff_git_repository_link_commit_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: @@ -7485,7 +7311,7 @@ def test_get_account_connector_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.get_account_connector + client._transport.diff_git_repository_link_commit in client._transport._wrapped_methods ) @@ -7494,16 +7320,16 @@ def test_get_account_connector_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.get_account_connector] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.diff_git_repository_link_commit + ] = mock_rpc request = {} - client.get_account_connector(request) + client.diff_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_account_connector(request) + client.diff_git_repository_link_commit(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7511,7 +7337,7 @@ def test_get_account_connector_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_account_connector_async_use_cached_wrapped_rpc( +async def test_diff_git_repository_link_commit_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -7528,7 +7354,7 @@ async def test_get_account_connector_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_account_connector + client._client._transport.diff_git_repository_link_commit in client._client._transport._wrapped_methods ) @@ -7536,16 +7362,16 @@ async def test_get_account_connector_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_account_connector + client._client._transport.diff_git_repository_link_commit ] = mock_rpc request = {} - await client.get_account_connector(request) + await client.diff_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_account_connector(request) + await client.diff_git_repository_link_commit(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7556,11 +7382,11 @@ async def test_get_account_connector_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.GetAccountConnectorRequest(), + developer_connect.DiffGitRepositoryLinkCommitRequest(), {}, ], ) -async def test_get_account_connector_async( +async def test_diff_git_repository_link_commit_async( request_type, transport: str = "grpc_asyncio" ): client = DeveloperConnectAsyncClient( @@ -7574,48 +7400,41 @@ async def test_get_account_connector_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_connector), "__call__" + type(client.transport.diff_git_repository_link_commit), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.AccountConnector( - name="name_value", - etag="etag_value", - oauth_start_uri="oauth_start_uri_value", - ) + developer_connect.DiffGitRepositoryLinkCommitResponse() ) - response = await client.get_account_connector(request) + response = await client.diff_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.GetAccountConnectorRequest() + request = developer_connect.DiffGitRepositoryLinkCommitRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.AccountConnector) - assert response.name == "name_value" - assert response.etag == "etag_value" - assert response.oauth_start_uri == "oauth_start_uri_value" + assert isinstance(response, developer_connect.DiffGitRepositoryLinkCommitResponse) -def test_get_account_connector_field_headers(): +def test_diff_git_repository_link_commit_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.GetAccountConnectorRequest() + request = developer_connect.DiffGitRepositoryLinkCommitRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_connector), "__call__" + type(client.transport.diff_git_repository_link_commit), "__call__" ) as call: - call.return_value = developer_connect.AccountConnector() - client.get_account_connector(request) + call.return_value = developer_connect.DiffGitRepositoryLinkCommitResponse() + client.diff_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7631,25 +7450,25 @@ def test_get_account_connector_field_headers(): @pytest.mark.asyncio -async def test_get_account_connector_field_headers_async(): +async def test_diff_git_repository_link_commit_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.GetAccountConnectorRequest() + request = developer_connect.DiffGitRepositoryLinkCommitRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_connector), "__call__" + type(client.transport.diff_git_repository_link_commit), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.AccountConnector() + developer_connect.DiffGitRepositoryLinkCommitResponse() ) - await client.get_account_connector(request) + await client.diff_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7664,21 +7483,23 @@ async def test_get_account_connector_field_headers_async(): ) in kw["metadata"] -def test_get_account_connector_flattened(): +def test_diff_git_repository_link_commit_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_connector), "__call__" + type(client.transport.diff_git_repository_link_commit), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.AccountConnector() + call.return_value = developer_connect.DiffGitRepositoryLinkCommitResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_account_connector( + client.diff_git_repository_link_commit( name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", ) # Establish that the underlying call was made with the expected @@ -7688,9 +7509,15 @@ def test_get_account_connector_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].base_sha + mock_val = "base_sha_value" + assert arg == mock_val + arg = args[0].head_sha + mock_val = "head_sha_value" + assert arg == mock_val -def test_get_account_connector_flattened_error(): +def test_diff_git_repository_link_commit_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7698,32 +7525,36 @@ def test_get_account_connector_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_account_connector( - developer_connect.GetAccountConnectorRequest(), + client.diff_git_repository_link_commit( + developer_connect.DiffGitRepositoryLinkCommitRequest(), name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", ) @pytest.mark.asyncio -async def test_get_account_connector_flattened_async(): +async def test_diff_git_repository_link_commit_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.get_account_connector), "__call__" + type(client.transport.diff_git_repository_link_commit), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.AccountConnector() + call.return_value = developer_connect.DiffGitRepositoryLinkCommitResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.AccountConnector() + developer_connect.DiffGitRepositoryLinkCommitResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_account_connector( + response = await client.diff_git_repository_link_commit( name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", ) # Establish that the underlying call was made with the expected @@ -7733,10 +7564,16 @@ async def test_get_account_connector_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].base_sha + mock_val = "base_sha_value" + assert arg == mock_val + arg = args[0].head_sha + mock_val = "head_sha_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_get_account_connector_flattened_error_async(): +async def test_diff_git_repository_link_commit_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -7744,20 +7581,22 @@ async def test_get_account_connector_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.get_account_connector( - developer_connect.GetAccountConnectorRequest(), + await client.diff_git_repository_link_commit( + developer_connect.DiffGitRepositoryLinkCommitRequest(), name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", ) @pytest.mark.parametrize( "request_type", [ - developer_connect.CreateAccountConnectorRequest(), + developer_connect.FetchGitRepositoryLinkCommitRequest(), {}, ], ) -def test_create_account_connector(request_type, transport: str = "grpc"): +def test_fetch_git_repository_link_commit(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7769,23 +7608,23 @@ def test_create_account_connector(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_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_account_connector(request) + call.return_value = developer_connect.FetchGitRepositoryLinkCommitResponse() + response = client.fetch_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.CreateAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkCommitRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, developer_connect.FetchGitRepositoryLinkCommitResponse) -def test_create_account_connector_non_empty_request_with_auto_populated_field(): +def test_fetch_git_repository_link_commit_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 = DeveloperConnectClient( @@ -7796,29 +7635,29 @@ def test_create_account_connector_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 = developer_connect.CreateAccountConnectorRequest( - parent="parent_value", - account_connector_id="account_connector_id_value", + request = developer_connect.FetchGitRepositoryLinkCommitRequest( + name="name_value", + commit_sha="commit_sha_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_account_connector(request=request) + client.fetch_git_repository_link_commit(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.CreateAccountConnectorRequest( - parent="parent_value", - account_connector_id="account_connector_id_value", + request_msg = developer_connect.FetchGitRepositoryLinkCommitRequest( + name="name_value", + commit_sha="commit_sha_value", ) assert args[0] == request_msg -def test_create_account_connector_use_cached_wrapped_rpc(): +def test_fetch_git_repository_link_commit_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: @@ -7833,7 +7672,7 @@ def test_create_account_connector_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_account_connector + client._transport.fetch_git_repository_link_commit in client._transport._wrapped_methods ) @@ -7843,20 +7682,15 @@ def test_create_account_connector_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_account_connector + client._transport.fetch_git_repository_link_commit ] = mock_rpc request = {} - client.create_account_connector(request) + client.fetch_git_repository_link_commit(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.create_account_connector(request) + client.fetch_git_repository_link_commit(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7864,7 +7698,7 @@ def test_create_account_connector_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_account_connector_async_use_cached_wrapped_rpc( +async def test_fetch_git_repository_link_commit_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -7881,7 +7715,7 @@ async def test_create_account_connector_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_account_connector + client._client._transport.fetch_git_repository_link_commit in client._client._transport._wrapped_methods ) @@ -7889,21 +7723,16 @@ async def test_create_account_connector_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_account_connector + client._client._transport.fetch_git_repository_link_commit ] = mock_rpc request = {} - await client.create_account_connector(request) + await client.fetch_git_repository_link_commit(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.create_account_connector(request) + await client.fetch_git_repository_link_commit(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7914,11 +7743,11 @@ async def test_create_account_connector_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.CreateAccountConnectorRequest(), + developer_connect.FetchGitRepositoryLinkCommitRequest(), {}, ], ) -async def test_create_account_connector_async( +async def test_fetch_git_repository_link_commit_async( request_type, transport: str = "grpc_asyncio" ): client = DeveloperConnectAsyncClient( @@ -7932,41 +7761,41 @@ async def test_create_account_connector_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.FetchGitRepositoryLinkCommitResponse() ) - response = await client.create_account_connector(request) + response = await client.fetch_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.CreateAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkCommitRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, developer_connect.FetchGitRepositoryLinkCommitResponse) -def test_create_account_connector_field_headers(): +def test_fetch_git_repository_link_commit_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.CreateAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkCommitRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_account_connector(request) + call.return_value = developer_connect.FetchGitRepositoryLinkCommitResponse() + client.fetch_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7977,30 +7806,30 @@ def test_create_account_connector_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_account_connector_field_headers_async(): +async def test_fetch_git_repository_link_commit_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.CreateAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkCommitRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + developer_connect.FetchGitRepositoryLinkCommitResponse() ) - await client.create_account_connector(request) + await client.fetch_git_repository_link_commit(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8011,53 +7840,41 @@ async def test_create_account_connector_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_create_account_connector_flattened(): +def test_fetch_git_repository_link_commit_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = developer_connect.FetchGitRepositoryLinkCommitResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_account_connector( - parent="parent_value", - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - account_connector_id="account_connector_id_value", + client.fetch_git_repository_link_commit( + name="name_value", + commit_sha="commit_sha_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].account_connector - mock_val = developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val - arg = args[0].account_connector_id - mock_val = "account_connector_id_value" + arg = args[0].commit_sha + mock_val = "commit_sha_value" assert arg == mock_val -def test_create_account_connector_flattened_error(): +def test_fetch_git_repository_link_commit_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8065,67 +7882,50 @@ def test_create_account_connector_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_account_connector( - developer_connect.CreateAccountConnectorRequest(), - parent="parent_value", - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - account_connector_id="account_connector_id_value", + client.fetch_git_repository_link_commit( + developer_connect.FetchGitRepositoryLinkCommitRequest(), + name="name_value", + commit_sha="commit_sha_value", ) @pytest.mark.asyncio -async def test_create_account_connector_flattened_async(): +async def test_fetch_git_repository_link_commit_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = developer_connect.FetchGitRepositoryLinkCommitResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.FetchGitRepositoryLinkCommitResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_account_connector( - parent="parent_value", - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - account_connector_id="account_connector_id_value", + response = await client.fetch_git_repository_link_commit( + name="name_value", + commit_sha="commit_sha_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].account_connector - mock_val = developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val - arg = args[0].account_connector_id - mock_val = "account_connector_id_value" + arg = args[0].commit_sha + mock_val = "commit_sha_value" assert arg == mock_val @pytest.mark.asyncio -async def test_create_account_connector_flattened_error_async(): +async def test_fetch_git_repository_link_commit_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8133,26 +7933,21 @@ async def test_create_account_connector_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.create_account_connector( - developer_connect.CreateAccountConnectorRequest(), - parent="parent_value", - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - account_connector_id="account_connector_id_value", + await client.fetch_git_repository_link_commit( + developer_connect.FetchGitRepositoryLinkCommitRequest(), + name="name_value", + commit_sha="commit_sha_value", ) @pytest.mark.parametrize( "request_type", [ - developer_connect.UpdateAccountConnectorRequest(), + developer_connect.FetchGitRepositoryLinkCommitListRequest(), {}, ], ) -def test_update_account_connector(request_type, transport: str = "grpc"): +def test_fetch_git_repository_link_commit_list(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8164,23 +7959,26 @@ def test_update_account_connector(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_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit_list), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_account_connector(request) + call.return_value = developer_connect.FetchGitRepositoryLinkCommitListResponse( + next_page_token="next_page_token_value", + ) + response = client.fetch_git_repository_link_commit_list(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.UpdateAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkCommitListRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.FetchGitRepositoryLinkCommitListPager) + assert response.next_page_token == "next_page_token_value" -def test_update_account_connector_non_empty_request_with_auto_populated_field(): +def test_fetch_git_repository_link_commit_list_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 = DeveloperConnectClient( @@ -8191,23 +7989,31 @@ def test_update_account_connector_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 = developer_connect.UpdateAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkCommitListRequest( + name="name_value", + ref="ref_value", + page_token="page_token_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit_list), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_account_connector(request=request) + client.fetch_git_repository_link_commit_list(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.UpdateAccountConnectorRequest() + request_msg = developer_connect.FetchGitRepositoryLinkCommitListRequest( + name="name_value", + ref="ref_value", + page_token="page_token_value", + ) assert args[0] == request_msg -def test_update_account_connector_use_cached_wrapped_rpc(): +def test_fetch_git_repository_link_commit_list_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: @@ -8222,7 +8028,7 @@ def test_update_account_connector_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_account_connector + client._transport.fetch_git_repository_link_commit_list in client._transport._wrapped_methods ) @@ -8232,20 +8038,15 @@ def test_update_account_connector_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.update_account_connector + client._transport.fetch_git_repository_link_commit_list ] = mock_rpc request = {} - client.update_account_connector(request) + client.fetch_git_repository_link_commit_list(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.update_account_connector(request) + client.fetch_git_repository_link_commit_list(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8253,7 +8054,7 @@ def test_update_account_connector_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_account_connector_async_use_cached_wrapped_rpc( +async def test_fetch_git_repository_link_commit_list_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8270,7 +8071,7 @@ async def test_update_account_connector_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_account_connector + client._client._transport.fetch_git_repository_link_commit_list in client._client._transport._wrapped_methods ) @@ -8278,21 +8079,16 @@ async def test_update_account_connector_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_account_connector + client._client._transport.fetch_git_repository_link_commit_list ] = mock_rpc request = {} - await client.update_account_connector(request) + await client.fetch_git_repository_link_commit_list(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.update_account_connector(request) + await client.fetch_git_repository_link_commit_list(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8303,11 +8099,11 @@ async def test_update_account_connector_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.UpdateAccountConnectorRequest(), + developer_connect.FetchGitRepositoryLinkCommitListRequest(), {}, ], ) -async def test_update_account_connector_async( +async def test_fetch_git_repository_link_commit_list_async( request_type, transport: str = "grpc_asyncio" ): client = DeveloperConnectAsyncClient( @@ -8321,41 +8117,44 @@ async def test_update_account_connector_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit_list), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.FetchGitRepositoryLinkCommitListResponse( + next_page_token="next_page_token_value", + ) ) - response = await client.update_account_connector(request) + response = await client.fetch_git_repository_link_commit_list(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.UpdateAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkCommitListRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.FetchGitRepositoryLinkCommitListAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_update_account_connector_field_headers(): +def test_fetch_git_repository_link_commit_list_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.UpdateAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkCommitListRequest() - request.account_connector.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_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit_list), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_account_connector(request) + call.return_value = developer_connect.FetchGitRepositoryLinkCommitListResponse() + client.fetch_git_repository_link_commit_list(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8366,30 +8165,30 @@ def test_update_account_connector_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "account_connector.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_account_connector_field_headers_async(): +async def test_fetch_git_repository_link_commit_list_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.UpdateAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkCommitListRequest() - request.account_connector.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_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit_list), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + developer_connect.FetchGitRepositoryLinkCommitListResponse() ) - await client.update_account_connector(request) + await client.fetch_git_repository_link_commit_list(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8400,49 +8199,41 @@ async def test_update_account_connector_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "account_connector.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_account_connector_flattened(): +def test_fetch_git_repository_link_commit_list_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit_list), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = developer_connect.FetchGitRepositoryLinkCommitListResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_account_connector( - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.fetch_git_repository_link_commit_list( + name="name_value", + ref="ref_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].account_connector - mock_val = developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].ref + mock_val = "ref_value" assert arg == mock_val -def test_update_account_connector_flattened_error(): +def test_fetch_git_repository_link_commit_list_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8450,62 +8241,50 @@ def test_update_account_connector_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_account_connector( - developer_connect.UpdateAccountConnectorRequest(), - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.fetch_git_repository_link_commit_list( + developer_connect.FetchGitRepositoryLinkCommitListRequest(), + name="name_value", + ref="ref_value", ) @pytest.mark.asyncio -async def test_update_account_connector_flattened_async(): +async def test_fetch_git_repository_link_commit_list_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_commit_list), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = developer_connect.FetchGitRepositoryLinkCommitListResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.FetchGitRepositoryLinkCommitListResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_account_connector( - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.fetch_git_repository_link_commit_list( + name="name_value", + ref="ref_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].account_connector - mock_val = developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].ref + mock_val = "ref_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_account_connector_flattened_error_async(): +async def test_fetch_git_repository_link_commit_list_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8513,25 +8292,228 @@ async def test_update_account_connector_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_account_connector( - developer_connect.UpdateAccountConnectorRequest(), - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) + await client.fetch_git_repository_link_commit_list( + developer_connect.FetchGitRepositoryLinkCommitListRequest(), + name="name_value", + ref="ref_value", + ) + + +def test_fetch_git_repository_link_commit_list_pager(transport_name: str = "grpc"): + client = DeveloperConnectClient( + 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.fetch_git_repository_link_commit_list), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + next_page_token="abc", ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.fetch_git_repository_link_commit_list( + 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, developer_connect.SCMCommit) for i in results) + + +def test_fetch_git_repository_link_commit_list_pages(transport_name: str = "grpc"): + client = DeveloperConnectClient( + 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.fetch_git_repository_link_commit_list), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + ), + RuntimeError, + ) + pages = list(client.fetch_git_repository_link_commit_list(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_fetch_git_repository_link_commit_list_async_pager(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_commit_list), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_git_repository_link_commit_list( + 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, developer_connect.SCMCommit) for i in responses) + + +@pytest.mark.asyncio +async def test_fetch_git_repository_link_commit_list_async_pages(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_commit_list), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + ), + RuntimeError, ) + pages = [] + async for page_ in ( + await client.fetch_git_repository_link_commit_list(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", [ - developer_connect.DeleteAccountConnectorRequest(), + developer_connect.FetchGitRepositoryLinkFileBlameRequest(), {}, ], ) -def test_delete_account_connector(request_type, transport: str = "grpc"): +def test_fetch_git_repository_link_file_blame(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8543,23 +8525,25 @@ def test_delete_account_connector(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_file_blame), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_account_connector(request) + call.return_value = developer_connect.FetchGitRepositoryLinkFileBlameResponse() + response = client.fetch_git_repository_link_file_blame(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.DeleteAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkFileBlameRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance( + response, developer_connect.FetchGitRepositoryLinkFileBlameResponse + ) -def test_delete_account_connector_non_empty_request_with_auto_populated_field(): +def test_fetch_git_repository_link_file_blame_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 = DeveloperConnectClient( @@ -8570,29 +8554,31 @@ def test_delete_account_connector_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 = developer_connect.DeleteAccountConnectorRequest( + request = developer_connect.FetchGitRepositoryLinkFileBlameRequest( name="name_value", - etag="etag_value", + ref="ref_value", + path="path_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_file_blame), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_account_connector(request=request) + client.fetch_git_repository_link_file_blame(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteAccountConnectorRequest( + request_msg = developer_connect.FetchGitRepositoryLinkFileBlameRequest( name="name_value", - etag="etag_value", + ref="ref_value", + path="path_value", ) assert args[0] == request_msg -def test_delete_account_connector_use_cached_wrapped_rpc(): +def test_fetch_git_repository_link_file_blame_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: @@ -8607,7 +8593,7 @@ def test_delete_account_connector_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_account_connector + client._transport.fetch_git_repository_link_file_blame in client._transport._wrapped_methods ) @@ -8617,20 +8603,15 @@ def test_delete_account_connector_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_account_connector + client._transport.fetch_git_repository_link_file_blame ] = mock_rpc request = {} - client.delete_account_connector(request) + client.fetch_git_repository_link_file_blame(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_account_connector(request) + client.fetch_git_repository_link_file_blame(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8638,7 +8619,7 @@ def test_delete_account_connector_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_account_connector_async_use_cached_wrapped_rpc( +async def test_fetch_git_repository_link_file_blame_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8655,7 +8636,7 @@ async def test_delete_account_connector_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_account_connector + client._client._transport.fetch_git_repository_link_file_blame in client._client._transport._wrapped_methods ) @@ -8663,21 +8644,16 @@ async def test_delete_account_connector_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_account_connector + client._client._transport.fetch_git_repository_link_file_blame ] = mock_rpc request = {} - await client.delete_account_connector(request) + await client.fetch_git_repository_link_file_blame(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_account_connector(request) + await client.fetch_git_repository_link_file_blame(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8688,11 +8664,11 @@ async def test_delete_account_connector_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.DeleteAccountConnectorRequest(), + developer_connect.FetchGitRepositoryLinkFileBlameRequest(), {}, ], ) -async def test_delete_account_connector_async( +async def test_fetch_git_repository_link_file_blame_async( request_type, transport: str = "grpc_asyncio" ): client = DeveloperConnectAsyncClient( @@ -8706,41 +8682,43 @@ async def test_delete_account_connector_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_file_blame), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.FetchGitRepositoryLinkFileBlameResponse() ) - response = await client.delete_account_connector(request) + response = await client.fetch_git_repository_link_file_blame(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.DeleteAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkFileBlameRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance( + response, developer_connect.FetchGitRepositoryLinkFileBlameResponse + ) -def test_delete_account_connector_field_headers(): +def test_fetch_git_repository_link_file_blame_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.DeleteAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkFileBlameRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_file_blame), "__call__" ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_account_connector(request) + call.return_value = developer_connect.FetchGitRepositoryLinkFileBlameResponse() + client.fetch_git_repository_link_file_blame(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8756,25 +8734,25 @@ def test_delete_account_connector_field_headers(): @pytest.mark.asyncio -async def test_delete_account_connector_field_headers_async(): +async def test_fetch_git_repository_link_file_blame_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.DeleteAccountConnectorRequest() + request = developer_connect.FetchGitRepositoryLinkFileBlameRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_file_blame), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + developer_connect.FetchGitRepositoryLinkFileBlameResponse() ) - await client.delete_account_connector(request) + await client.fetch_git_repository_link_file_blame(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8789,21 +8767,23 @@ async def test_delete_account_connector_field_headers_async(): ) in kw["metadata"] -def test_delete_account_connector_flattened(): +def test_fetch_git_repository_link_file_blame_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_file_blame), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = developer_connect.FetchGitRepositoryLinkFileBlameResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_account_connector( + client.fetch_git_repository_link_file_blame( name="name_value", + ref="ref_value", + path="path_value", ) # Establish that the underlying call was made with the expected @@ -8813,9 +8793,15 @@ def test_delete_account_connector_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].ref + mock_val = "ref_value" + assert arg == mock_val + arg = args[0].path + mock_val = "path_value" + assert arg == mock_val -def test_delete_account_connector_flattened_error(): +def test_fetch_git_repository_link_file_blame_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8823,32 +8809,36 @@ def test_delete_account_connector_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_account_connector( - developer_connect.DeleteAccountConnectorRequest(), + client.fetch_git_repository_link_file_blame( + developer_connect.FetchGitRepositoryLinkFileBlameRequest(), name="name_value", + ref="ref_value", + path="path_value", ) @pytest.mark.asyncio -async def test_delete_account_connector_flattened_async(): +async def test_fetch_git_repository_link_file_blame_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.delete_account_connector), "__call__" + type(client.transport.fetch_git_repository_link_file_blame), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = developer_connect.FetchGitRepositoryLinkFileBlameResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.FetchGitRepositoryLinkFileBlameResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_account_connector( + response = await client.fetch_git_repository_link_file_blame( name="name_value", + ref="ref_value", + path="path_value", ) # Establish that the underlying call was made with the expected @@ -8858,10 +8848,16 @@ async def test_delete_account_connector_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].ref + mock_val = "ref_value" + assert arg == mock_val + arg = args[0].path + mock_val = "path_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_delete_account_connector_flattened_error_async(): +async def test_fetch_git_repository_link_file_blame_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8869,20 +8865,22 @@ async def test_delete_account_connector_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.delete_account_connector( - developer_connect.DeleteAccountConnectorRequest(), + await client.fetch_git_repository_link_file_blame( + developer_connect.FetchGitRepositoryLinkFileBlameRequest(), name="name_value", + ref="ref_value", + path="path_value", ) @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchAccessTokenRequest(), + developer_connect.FetchGitRepositoryLinkPullRequestRequest(), {}, ], ) -def test_fetch_access_token(request_type, transport: str = "grpc"): +def test_fetch_git_repository_link_pull_request(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8894,28 +8892,42 @@ def test_fetch_access_token(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_access_token), "__call__" + type(client.transport.fetch_git_repository_link_pull_request), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchAccessTokenResponse( - token="token_value", - scopes=["scopes_value"], - ) - response = client.fetch_access_token(request) + call.return_value = developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", + ) + response = client.fetch_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.FetchAccessTokenRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.FetchAccessTokenResponse) - assert response.token == "token_value" - assert response.scopes == ["scopes_value"] - - -def test_fetch_access_token_non_empty_request_with_auto_populated_field(): + assert isinstance(response, developer_connect.PullRequest) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.body == "body_value" + assert response.head_ref == "head_ref_value" + assert response.base_ref == "base_ref_value" + assert response.author == "author_value" + assert response.state == developer_connect.PullRequest.State.OPEN + assert response.mergeability == developer_connect.PullRequest.Mergeability.MERGEABLE + assert response.html_url == "html_url_value" + + +def test_fetch_git_repository_link_pull_request_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 = DeveloperConnectClient( @@ -8926,27 +8938,29 @@ def test_fetch_access_token_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 = developer_connect.FetchAccessTokenRequest( - account_connector="account_connector_value", + request = developer_connect.FetchGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_access_token), "__call__" + type(client.transport.fetch_git_repository_link_pull_request), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.fetch_access_token(request=request) + client.fetch_git_repository_link_pull_request(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchAccessTokenRequest( - account_connector="account_connector_value", + request_msg = developer_connect.FetchGitRepositoryLinkPullRequestRequest( + name="name_value", + pull_request_id="pull_request_id_value", ) assert args[0] == request_msg -def test_fetch_access_token_use_cached_wrapped_rpc(): +def test_fetch_git_repository_link_pull_request_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: @@ -8961,7 +8975,8 @@ def test_fetch_access_token_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.fetch_access_token in client._transport._wrapped_methods + client._transport.fetch_git_repository_link_pull_request + in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -8969,16 +8984,16 @@ def test_fetch_access_token_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.fetch_access_token] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.fetch_git_repository_link_pull_request + ] = mock_rpc request = {} - client.fetch_access_token(request) + client.fetch_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_access_token(request) + client.fetch_git_repository_link_pull_request(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8986,7 +9001,7 @@ def test_fetch_access_token_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_fetch_access_token_async_use_cached_wrapped_rpc( +async def test_fetch_git_repository_link_pull_request_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9003,7 +9018,7 @@ async def test_fetch_access_token_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.fetch_access_token + client._client._transport.fetch_git_repository_link_pull_request in client._client._transport._wrapped_methods ) @@ -9011,16 +9026,16 @@ async def test_fetch_access_token_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.fetch_access_token + client._client._transport.fetch_git_repository_link_pull_request ] = mock_rpc request = {} - await client.fetch_access_token(request) + await client.fetch_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_access_token(request) + await client.fetch_git_repository_link_pull_request(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9031,11 +9046,13 @@ async def test_fetch_access_token_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchAccessTokenRequest(), + developer_connect.FetchGitRepositoryLinkPullRequestRequest(), {}, ], ) -async def test_fetch_access_token_async(request_type, transport: str = "grpc_asyncio"): +async def test_fetch_git_repository_link_pull_request_async( + request_type, transport: str = "grpc_asyncio" +): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9047,46 +9064,60 @@ async def test_fetch_access_token_async(request_type, transport: str = "grpc_asy # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_access_token), "__call__" + type(client.transport.fetch_git_repository_link_pull_request), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchAccessTokenResponse( - token="token_value", - scopes=["scopes_value"], + developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", ) ) - response = await client.fetch_access_token(request) + response = await client.fetch_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.FetchAccessTokenRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.FetchAccessTokenResponse) - assert response.token == "token_value" - assert response.scopes == ["scopes_value"] + assert isinstance(response, developer_connect.PullRequest) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.body == "body_value" + assert response.head_ref == "head_ref_value" + assert response.base_ref == "base_ref_value" + assert response.author == "author_value" + assert response.state == developer_connect.PullRequest.State.OPEN + assert response.mergeability == developer_connect.PullRequest.Mergeability.MERGEABLE + assert response.html_url == "html_url_value" -def test_fetch_access_token_field_headers(): +def test_fetch_git_repository_link_pull_request_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.FetchAccessTokenRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestRequest() - request.account_connector = "account_connector_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_access_token), "__call__" + type(client.transport.fetch_git_repository_link_pull_request), "__call__" ) as call: - call.return_value = developer_connect.FetchAccessTokenResponse() - client.fetch_access_token(request) + call.return_value = developer_connect.PullRequest() + client.fetch_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9097,30 +9128,30 @@ def test_fetch_access_token_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "account_connector=account_connector_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_fetch_access_token_field_headers_async(): +async def test_fetch_git_repository_link_pull_request_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.FetchAccessTokenRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestRequest() - request.account_connector = "account_connector_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_access_token), "__call__" + type(client.transport.fetch_git_repository_link_pull_request), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchAccessTokenResponse() + developer_connect.PullRequest() ) - await client.fetch_access_token(request) + await client.fetch_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9131,37 +9162,41 @@ async def test_fetch_access_token_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "account_connector=account_connector_value", + "name=name_value", ) in kw["metadata"] -def test_fetch_access_token_flattened(): +def test_fetch_git_repository_link_pull_request_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_access_token), "__call__" + type(client.transport.fetch_git_repository_link_pull_request), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchAccessTokenResponse() + call.return_value = developer_connect.PullRequest() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.fetch_access_token( - account_connector="account_connector_value", + client.fetch_git_repository_link_pull_request( + name="name_value", + pull_request_id="pull_request_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].account_connector - mock_val = "account_connector_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].pull_request_id + mock_val = "pull_request_id_value" assert arg == mock_val -def test_fetch_access_token_flattened_error(): +def test_fetch_git_repository_link_pull_request_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9169,45 +9204,50 @@ def test_fetch_access_token_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_access_token( - developer_connect.FetchAccessTokenRequest(), - account_connector="account_connector_value", + client.fetch_git_repository_link_pull_request( + developer_connect.FetchGitRepositoryLinkPullRequestRequest(), + name="name_value", + pull_request_id="pull_request_id_value", ) @pytest.mark.asyncio -async def test_fetch_access_token_flattened_async(): +async def test_fetch_git_repository_link_pull_request_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.fetch_access_token), "__call__" + type(client.transport.fetch_git_repository_link_pull_request), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FetchAccessTokenResponse() + call.return_value = developer_connect.PullRequest() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchAccessTokenResponse() + developer_connect.PullRequest() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.fetch_access_token( - account_connector="account_connector_value", + response = await client.fetch_git_repository_link_pull_request( + name="name_value", + pull_request_id="pull_request_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].account_connector - mock_val = "account_connector_value" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].pull_request_id + mock_val = "pull_request_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_fetch_access_token_flattened_error_async(): +async def test_fetch_git_repository_link_pull_request_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9215,20 +9255,23 @@ async def test_fetch_access_token_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.fetch_access_token( - developer_connect.FetchAccessTokenRequest(), - account_connector="account_connector_value", + await client.fetch_git_repository_link_pull_request( + developer_connect.FetchGitRepositoryLinkPullRequestRequest(), + name="name_value", + pull_request_id="pull_request_id_value", ) @pytest.mark.parametrize( "request_type", [ - developer_connect.ListUsersRequest(), + developer_connect.AddGitRepositoryLinkPullRequestCommentRequest(), {}, ], ) -def test_list_users(request_type, transport: str = "grpc"): +def test_add_git_repository_link_pull_request_comment( + request_type, transport: str = "grpc" +): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9239,27 +9282,31 @@ def test_list_users(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.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.ListUsersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + call.return_value = developer_connect.PullRequestComment( + id="id_value", + body="body_value", + author="author_value", ) - response = client.list_users(request) + response = client.add_git_repository_link_pull_request_comment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.ListUsersRequest() + request = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, developer_connect.PullRequestComment) + assert response.id == "id_value" + assert response.body == "body_value" + assert response.author == "author_value" -def test_list_users_non_empty_request_with_auto_populated_field(): +def test_add_git_repository_link_pull_request_comment_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 = DeveloperConnectClient( @@ -9270,31 +9317,29 @@ def test_list_users_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 = developer_connect.ListUsersRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_users(request=request) + client.add_git_repository_link_pull_request_comment(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListUsersRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request_msg = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", ) assert args[0] == request_msg -def test_list_users_use_cached_wrapped_rpc(): +def test_add_git_repository_link_pull_request_comment_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: @@ -9308,21 +9353,26 @@ def test_list_users_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_users in client._transport._wrapped_methods + assert ( + client._transport.add_git_repository_link_pull_request_comment + 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_users] = mock_rpc + client._transport._wrapped_methods[ + client._transport.add_git_repository_link_pull_request_comment + ] = mock_rpc request = {} - client.list_users(request) + client.add_git_repository_link_pull_request_comment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_users(request) + client.add_git_repository_link_pull_request_comment(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9330,7 +9380,9 @@ def test_list_users_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_add_git_repository_link_pull_request_comment_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: @@ -9345,7 +9397,7 @@ async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_as # Ensure method has been cached assert ( - client._client._transport.list_users + client._client._transport.add_git_repository_link_pull_request_comment in client._client._transport._wrapped_methods ) @@ -9353,16 +9405,16 @@ async def test_list_users_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.list_users + client._client._transport.add_git_repository_link_pull_request_comment ] = mock_rpc request = {} - await client.list_users(request) + await client.add_git_repository_link_pull_request_comment(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_users(request) + await client.add_git_repository_link_pull_request_comment(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9373,11 +9425,13 @@ async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_as @pytest.mark.parametrize( "request_type", [ - developer_connect.ListUsersRequest(), + developer_connect.AddGitRepositoryLinkPullRequestCommentRequest(), {}, ], ) -async def test_list_users_async(request_type, transport: str = "grpc_asyncio"): +async def test_add_git_repository_link_pull_request_comment_async( + request_type, transport: str = "grpc_asyncio" +): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9388,43 +9442,49 @@ async def test_list_users_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.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListUsersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + developer_connect.PullRequestComment( + id="id_value", + body="body_value", + author="author_value", ) ) - response = await client.list_users(request) + response = await client.add_git_repository_link_pull_request_comment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.ListUsersRequest() + request = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, developer_connect.PullRequestComment) + assert response.id == "id_value" + assert response.body == "body_value" + assert response.author == "author_value" -def test_list_users_field_headers(): +def test_add_git_repository_link_pull_request_comment_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.ListUsersRequest() + request = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - call.return_value = developer_connect.ListUsersResponse() - client.list_users(request) + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: + call.return_value = developer_connect.PullRequestComment() + client.add_git_repository_link_pull_request_comment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9435,28 +9495,30 @@ def test_list_users_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_users_field_headers_async(): +async def test_add_git_repository_link_pull_request_comment_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.ListUsersRequest() + request = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListUsersResponse() + developer_connect.PullRequestComment() ) - await client.list_users(request) + await client.add_git_repository_link_pull_request_comment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9467,35 +9529,45 @@ async def test_list_users_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_users_flattened(): +def test_add_git_repository_link_pull_request_comment_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.ListUsersResponse() + call.return_value = developer_connect.PullRequestComment() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_users( - parent="parent_value", + client.add_git_repository_link_pull_request_comment( + name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestComment(id="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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].pull_request_id + mock_val = "pull_request_id_value" + assert arg == mock_val + arg = args[0].comment + mock_val = developer_connect.PullRequestComment(id="id_value") assert arg == mock_val -def test_list_users_flattened_error(): +def test_add_git_repository_link_pull_request_comment_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9503,43 +9575,55 @@ def test_list_users_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_users( - developer_connect.ListUsersRequest(), - parent="parent_value", + client.add_git_repository_link_pull_request_comment( + developer_connect.AddGitRepositoryLinkPullRequestCommentRequest(), + name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestComment(id="id_value"), ) @pytest.mark.asyncio -async def test_list_users_flattened_async(): +async def test_add_git_repository_link_pull_request_comment_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.ListUsersResponse() + call.return_value = developer_connect.PullRequestComment() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListUsersResponse() + developer_connect.PullRequestComment() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_users( - parent="parent_value", + response = await client.add_git_repository_link_pull_request_comment( + name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestComment(id="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" + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].pull_request_id + mock_val = "pull_request_id_value" + assert arg == mock_val + arg = args[0].comment + mock_val = developer_connect.PullRequestComment(id="id_value") assert arg == mock_val @pytest.mark.asyncio -async def test_list_users_flattened_error_async(): +async def test_add_git_repository_link_pull_request_comment_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9547,241 +9631,72 @@ async def test_list_users_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.list_users( - developer_connect.ListUsersRequest(), - parent="parent_value", + await client.add_git_repository_link_pull_request_comment( + developer_connect.AddGitRepositoryLinkPullRequestCommentRequest(), + name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestComment(id="id_value"), ) -def test_list_users_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest(), + {}, + ], +) +def test_add_git_repository_link_pull_request_review_comment( + request_type, transport: str = "grpc" +): client = DeveloperConnectClient( 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_users), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - developer_connect.User(), - ], - next_page_token="abc", - ), - developer_connect.ListUsersResponse( - users=[], - next_page_token="def", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - ], - next_page_token="ghi", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_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, developer_connect.User) for i in results) - - -def test_list_users_pages(transport_name: str = "grpc"): - client = DeveloperConnectClient( - 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_users), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - developer_connect.User(), - ], - next_page_token="abc", - ), - developer_connect.ListUsersResponse( - users=[], - next_page_token="def", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - ], - next_page_token="ghi", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - ], - ), - RuntimeError, - ) - pages = list(client.list_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_users_async_pager(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - developer_connect.User(), - ], - next_page_token="abc", - ), - developer_connect.ListUsersResponse( - users=[], - next_page_token="def", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - ], - next_page_token="ghi", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_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, developer_connect.User) for i in responses) - - -@pytest.mark.asyncio -async def test_list_users_async_pages(): - client = DeveloperConnectAsyncClient( - 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_users), "__call__", new_callable=mock.AsyncMock + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", ) as call: - # Set the response to a series of pages. - call.side_effect = ( - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - developer_connect.User(), - ], - next_page_token="abc", - ), - developer_connect.ListUsersResponse( - users=[], - next_page_token="def", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - ], - next_page_token="ghi", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - ], - ), - RuntimeError, - ) - pages = [] - async for page_ in (await client.list_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", - [ - developer_connect.DeleteUserRequest(), - {}, - ], -) -def test_delete_user(request_type, transport: str = "grpc"): - client = DeveloperConnectClient( - 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_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_user(request) + call.return_value = developer_connect.PullRequestReviewComment( + id="id_value", + body="body_value", + path="path_value", + first_line=1071, + last_line=955, + side=developer_connect.PullRequestReviewComment.DiffSide.BASE, + author="author_value", + commit_id="commit_id_value", + ) + response = client.add_git_repository_link_pull_request_review_comment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.DeleteUserRequest() + request = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest() + ) assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_delete_user_non_empty_request_with_auto_populated_field(): + assert isinstance(response, developer_connect.PullRequestReviewComment) + assert response.id == "id_value" + assert response.body == "body_value" + assert response.path == "path_value" + assert response.first_line == 1071 + assert response.last_line == 955 + assert response.side == developer_connect.PullRequestReviewComment.DiffSide.BASE + assert response.author == "author_value" + assert response.commit_id == "commit_id_value" + + +def test_add_git_repository_link_pull_request_review_comment_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 = DeveloperConnectClient( @@ -9792,27 +9707,34 @@ def test_delete_user_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 = developer_connect.DeleteUserRequest( + request = developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest( name="name_value", - etag="etag_value", + pull_request_id="pull_request_id_value", + commit_id="commit_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_user(request=request) + client.add_git_repository_link_pull_request_review_comment(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteUserRequest( - name="name_value", - etag="etag_value", + request_msg = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest( + name="name_value", + pull_request_id="pull_request_id_value", + commit_id="commit_id_value", + ) ) assert args[0] == request_msg -def test_delete_user_use_cached_wrapped_rpc(): +def test_add_git_repository_link_pull_request_review_comment_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: @@ -9826,26 +9748,26 @@ def test_delete_user_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_user in client._transport._wrapped_methods + assert ( + client._transport.add_git_repository_link_pull_request_review_comment + 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_user] = mock_rpc + client._transport._wrapped_methods[ + client._transport.add_git_repository_link_pull_request_review_comment + ] = mock_rpc request = {} - client.delete_user(request) + client.add_git_repository_link_pull_request_review_comment(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_user(request) + client.add_git_repository_link_pull_request_review_comment(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9853,7 +9775,7 @@ def test_delete_user_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_user_async_use_cached_wrapped_rpc( +async def test_add_git_repository_link_pull_request_review_comment_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9870,7 +9792,7 @@ async def test_delete_user_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_user + client._client._transport.add_git_repository_link_pull_request_review_comment in client._client._transport._wrapped_methods ) @@ -9878,21 +9800,16 @@ async def test_delete_user_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_user + client._client._transport.add_git_repository_link_pull_request_review_comment ] = mock_rpc request = {} - await client.delete_user(request) + await client.add_git_repository_link_pull_request_review_comment(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_user(request) + await client.add_git_repository_link_pull_request_review_comment(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9903,11 +9820,13 @@ async def test_delete_user_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.DeleteUserRequest(), + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest(), {}, ], ) -async def test_delete_user_async(request_type, transport: str = "grpc_asyncio"): +async def test_add_git_repository_link_pull_request_review_comment_async( + request_type, transport: str = "grpc_asyncio" +): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9918,38 +9837,65 @@ async def test_delete_user_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.delete_user), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.PullRequestReviewComment( + id="id_value", + body="body_value", + path="path_value", + first_line=1071, + last_line=955, + side=developer_connect.PullRequestReviewComment.DiffSide.BASE, + author="author_value", + commit_id="commit_id_value", + ) + ) + response = await client.add_git_repository_link_pull_request_review_comment( + request ) - response = await client.delete_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.DeleteUserRequest() + request = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest() + ) assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, developer_connect.PullRequestReviewComment) + assert response.id == "id_value" + assert response.body == "body_value" + assert response.path == "path_value" + assert response.first_line == 1071 + assert response.last_line == 955 + assert response.side == developer_connect.PullRequestReviewComment.DiffSide.BASE + assert response.author == "author_value" + assert response.commit_id == "commit_id_value" -def test_delete_user_field_headers(): +def test_add_git_repository_link_pull_request_review_comment_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.DeleteUserRequest() + request = developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_user(request) + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", + ) as call: + call.return_value = developer_connect.PullRequestReviewComment() + client.add_git_repository_link_pull_request_review_comment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9965,23 +9911,26 @@ def test_delete_user_field_headers(): @pytest.mark.asyncio -async def test_delete_user_field_headers_async(): +async def test_add_git_repository_link_pull_request_review_comment_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.DeleteUserRequest() + request = developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + developer_connect.PullRequestReviewComment() ) - await client.delete_user(request) + await client.add_git_repository_link_pull_request_review_comment(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9996,19 +9945,24 @@ async def test_delete_user_field_headers_async(): ) in kw["metadata"] -def test_delete_user_flattened(): +def test_add_git_repository_link_pull_request_review_comment_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = developer_connect.PullRequestReviewComment() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_user( + client.add_git_repository_link_pull_request_review_comment( name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestReviewComment(id="id_value"), ) # Establish that the underlying call was made with the expected @@ -10018,9 +9972,15 @@ def test_delete_user_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].pull_request_id + mock_val = "pull_request_id_value" + assert arg == mock_val + arg = args[0].comment + mock_val = developer_connect.PullRequestReviewComment(id="id_value") + assert arg == mock_val -def test_delete_user_flattened_error(): +def test_add_git_repository_link_pull_request_review_comment_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10028,30 +9988,37 @@ def test_delete_user_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_user( - developer_connect.DeleteUserRequest(), + client.add_git_repository_link_pull_request_review_comment( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest(), name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestReviewComment(id="id_value"), ) @pytest.mark.asyncio -async def test_delete_user_flattened_async(): +async def test_add_git_repository_link_pull_request_review_comment_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = developer_connect.PullRequestReviewComment() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.PullRequestReviewComment() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_user( + response = await client.add_git_repository_link_pull_request_review_comment( name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestReviewComment(id="id_value"), ) # Establish that the underlying call was made with the expected @@ -10061,10 +10028,16 @@ async def test_delete_user_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].pull_request_id + mock_val = "pull_request_id_value" + assert arg == mock_val + arg = args[0].comment + mock_val = developer_connect.PullRequestReviewComment(id="id_value") + assert arg == mock_val @pytest.mark.asyncio -async def test_delete_user_flattened_error_async(): +async def test_add_git_repository_link_pull_request_review_comment_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10072,20 +10045,22 @@ async def test_delete_user_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.delete_user( - developer_connect.DeleteUserRequest(), + await client.add_git_repository_link_pull_request_review_comment( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest(), name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestReviewComment(id="id_value"), ) @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchSelfRequest(), + developer_connect.ModifyGitRepositoryLinkPullRequestRequest(), {}, ], ) -def test_fetch_self(request_type, transport: str = "grpc"): +def test_modify_git_repository_link_pull_request(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10096,27 +10071,43 @@ def test_fetch_self(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.fetch_self), "__call__") as call: + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.User( - name="name_value", - display_name="display_name_value", - ) - response = client.fetch_self(request) + call.return_value = developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", + ) + response = client.modify_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.FetchSelfRequest() + request = developer_connect.ModifyGitRepositoryLinkPullRequestRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.User) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - - -def test_fetch_self_non_empty_request_with_auto_populated_field(): + assert isinstance(response, developer_connect.PullRequest) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.body == "body_value" + assert response.head_ref == "head_ref_value" + assert response.base_ref == "base_ref_value" + assert response.author == "author_value" + assert response.state == developer_connect.PullRequest.State.OPEN + assert response.mergeability == developer_connect.PullRequest.Mergeability.MERGEABLE + assert response.html_url == "html_url_value" + + +def test_modify_git_repository_link_pull_request_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 = DeveloperConnectClient( @@ -10127,25 +10118,35 @@ def test_fetch_self_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 = developer_connect.FetchSelfRequest( + request = developer_connect.ModifyGitRepositoryLinkPullRequestRequest( name="name_value", + pull_request_id="pull_request_id_value", + title="title_value", + body="body_value", + base_ref="base_ref_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.fetch_self(request=request) + client.modify_git_repository_link_pull_request(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchSelfRequest( + request_msg = developer_connect.ModifyGitRepositoryLinkPullRequestRequest( name="name_value", + pull_request_id="pull_request_id_value", + title="title_value", + body="body_value", + base_ref="base_ref_value", ) assert args[0] == request_msg -def test_fetch_self_use_cached_wrapped_rpc(): +def test_modify_git_repository_link_pull_request_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: @@ -10159,21 +10160,26 @@ def test_fetch_self_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.fetch_self in client._transport._wrapped_methods + assert ( + client._transport.modify_git_repository_link_pull_request + 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.fetch_self] = mock_rpc + client._transport._wrapped_methods[ + client._transport.modify_git_repository_link_pull_request + ] = mock_rpc request = {} - client.fetch_self(request) + client.modify_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_self(request) + client.modify_git_repository_link_pull_request(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10181,7 +10187,9 @@ def test_fetch_self_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_fetch_self_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_modify_git_repository_link_pull_request_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: @@ -10196,7 +10204,7 @@ async def test_fetch_self_async_use_cached_wrapped_rpc(transport: str = "grpc_as # Ensure method has been cached assert ( - client._client._transport.fetch_self + client._client._transport.modify_git_repository_link_pull_request in client._client._transport._wrapped_methods ) @@ -10204,16 +10212,16 @@ async def test_fetch_self_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.fetch_self + client._client._transport.modify_git_repository_link_pull_request ] = mock_rpc request = {} - await client.fetch_self(request) + await client.modify_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.fetch_self(request) + await client.modify_git_repository_link_pull_request(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10224,11 +10232,13 @@ async def test_fetch_self_async_use_cached_wrapped_rpc(transport: str = "grpc_as @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchSelfRequest(), + developer_connect.ModifyGitRepositoryLinkPullRequestRequest(), {}, ], ) -async def test_fetch_self_async(request_type, transport: str = "grpc_asyncio"): +async def test_modify_git_repository_link_pull_request_async( + request_type, transport: str = "grpc_asyncio" +): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -10239,43 +10249,61 @@ async def test_fetch_self_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.fetch_self), "__call__") as call: + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.User( - name="name_value", - display_name="display_name_value", + developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", ) ) - response = await client.fetch_self(request) + response = await client.modify_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.FetchSelfRequest() + request = developer_connect.ModifyGitRepositoryLinkPullRequestRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.User) - assert response.name == "name_value" - assert response.display_name == "display_name_value" + assert isinstance(response, developer_connect.PullRequest) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.body == "body_value" + assert response.head_ref == "head_ref_value" + assert response.base_ref == "base_ref_value" + assert response.author == "author_value" + assert response.state == developer_connect.PullRequest.State.OPEN + assert response.mergeability == developer_connect.PullRequest.Mergeability.MERGEABLE + assert response.html_url == "html_url_value" -def test_fetch_self_field_headers(): +def test_modify_git_repository_link_pull_request_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.FetchSelfRequest() + request = developer_connect.ModifyGitRepositoryLinkPullRequestRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: - call.return_value = developer_connect.User() - client.fetch_self(request) + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: + call.return_value = developer_connect.PullRequest() + client.modify_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10291,23 +10319,25 @@ def test_fetch_self_field_headers(): @pytest.mark.asyncio -async def test_fetch_self_field_headers_async(): +async def test_modify_git_repository_link_pull_request_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.FetchSelfRequest() + request = developer_connect.ModifyGitRepositoryLinkPullRequestRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.User() + developer_connect.PullRequest() ) - await client.fetch_self(request) + await client.modify_git_repository_link_pull_request(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10322,19 +10352,22 @@ async def test_fetch_self_field_headers_async(): ) in kw["metadata"] -def test_fetch_self_flattened(): +def test_modify_git_repository_link_pull_request_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.User() + call.return_value = developer_connect.PullRequest() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.fetch_self( + client.modify_git_repository_link_pull_request( name="name_value", + pull_request_id="pull_request_id_value", ) # Establish that the underlying call was made with the expected @@ -10344,9 +10377,12 @@ def test_fetch_self_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].pull_request_id + mock_val = "pull_request_id_value" + assert arg == mock_val -def test_fetch_self_flattened_error(): +def test_modify_git_repository_link_pull_request_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10354,30 +10390,34 @@ def test_fetch_self_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.fetch_self( - developer_connect.FetchSelfRequest(), + client.modify_git_repository_link_pull_request( + developer_connect.ModifyGitRepositoryLinkPullRequestRequest(), name="name_value", + pull_request_id="pull_request_id_value", ) @pytest.mark.asyncio -async def test_fetch_self_flattened_async(): +async def test_modify_git_repository_link_pull_request_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.User() + call.return_value = developer_connect.PullRequest() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.User() + developer_connect.PullRequest() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.fetch_self( + response = await client.modify_git_repository_link_pull_request( name="name_value", + pull_request_id="pull_request_id_value", ) # Establish that the underlying call was made with the expected @@ -10387,10 +10427,13 @@ async def test_fetch_self_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].pull_request_id + mock_val = "pull_request_id_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_fetch_self_flattened_error_async(): +async def test_modify_git_repository_link_pull_request_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10398,20 +10441,23 @@ async def test_fetch_self_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.fetch_self( - developer_connect.FetchSelfRequest(), + await client.modify_git_repository_link_pull_request( + developer_connect.ModifyGitRepositoryLinkPullRequestRequest(), name="name_value", + pull_request_id="pull_request_id_value", ) @pytest.mark.parametrize( "request_type", [ - developer_connect.DeleteSelfRequest(), + developer_connect.FetchGitRepositoryLinkPullRequestListRequest(), {}, ], ) -def test_delete_self(request_type, transport: str = "grpc"): +def test_fetch_git_repository_link_pull_request_list( + request_type, transport: str = "grpc" +): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10422,22 +10468,29 @@ def test_delete_self(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.delete_self), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_self(request) + call.return_value = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + next_page_token="next_page_token_value", + ) + ) + response = client.fetch_git_repository_link_pull_request_list(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.DeleteSelfRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestListRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.FetchGitRepositoryLinkPullRequestListPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_self_non_empty_request_with_auto_populated_field(): +def test_fetch_git_repository_link_pull_request_list_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 = DeveloperConnectClient( @@ -10448,25 +10501,31 @@ def test_delete_self_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 = developer_connect.DeleteSelfRequest( + request = developer_connect.FetchGitRepositoryLinkPullRequestListRequest( name="name_value", + filter="filter_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_self), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_self(request=request) + client.fetch_git_repository_link_pull_request_list(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteSelfRequest( + request_msg = developer_connect.FetchGitRepositoryLinkPullRequestListRequest( name="name_value", + filter="filter_value", + page_token="page_token_value", ) assert args[0] == request_msg -def test_delete_self_use_cached_wrapped_rpc(): +def test_fetch_git_repository_link_pull_request_list_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: @@ -10480,26 +10539,26 @@ def test_delete_self_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_self in client._transport._wrapped_methods + assert ( + client._transport.fetch_git_repository_link_pull_request_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.delete_self] = mock_rpc + client._transport._wrapped_methods[ + client._transport.fetch_git_repository_link_pull_request_list + ] = mock_rpc request = {} - client.delete_self(request) + client.fetch_git_repository_link_pull_request_list(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_self(request) + client.fetch_git_repository_link_pull_request_list(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10507,7 +10566,7 @@ def test_delete_self_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_self_async_use_cached_wrapped_rpc( +async def test_fetch_git_repository_link_pull_request_list_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10524,7 +10583,7 @@ async def test_delete_self_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_self + client._client._transport.fetch_git_repository_link_pull_request_list in client._client._transport._wrapped_methods ) @@ -10532,21 +10591,16 @@ async def test_delete_self_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_self + client._client._transport.fetch_git_repository_link_pull_request_list ] = mock_rpc request = {} - await client.delete_self(request) + await client.fetch_git_repository_link_pull_request_list(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_self(request) + await client.fetch_git_repository_link_pull_request_list(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10557,11 +10611,13 @@ async def test_delete_self_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.DeleteSelfRequest(), + developer_connect.FetchGitRepositoryLinkPullRequestListRequest(), {}, ], ) -async def test_delete_self_async(request_type, transport: str = "grpc_asyncio"): +async def test_fetch_git_repository_link_pull_request_list_async( + request_type, transport: str = "grpc_asyncio" +): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -10572,38 +10628,47 @@ async def test_delete_self_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.delete_self), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + next_page_token="next_page_token_value", + ) ) - response = await client.delete_self(request) + response = await client.fetch_git_repository_link_pull_request_list(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.DeleteSelfRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestListRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.FetchGitRepositoryLinkPullRequestListAsyncPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_self_field_headers(): +def test_fetch_git_repository_link_pull_request_list_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.DeleteSelfRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestListRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_self), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_self(request) + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: + call.return_value = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse() + ) + client.fetch_git_repository_link_pull_request_list(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10619,23 +10684,25 @@ def test_delete_self_field_headers(): @pytest.mark.asyncio -async def test_delete_self_field_headers_async(): +async def test_fetch_git_repository_link_pull_request_list_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.DeleteSelfRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestListRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_self), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + developer_connect.FetchGitRepositoryLinkPullRequestListResponse() ) - await client.delete_self(request) + await client.fetch_git_repository_link_pull_request_list(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10650,18 +10717,22 @@ async def test_delete_self_field_headers_async(): ) in kw["metadata"] -def test_delete_self_flattened(): +def test_fetch_git_repository_link_pull_request_list_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_self), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_self( + client.fetch_git_repository_link_pull_request_list( name="name_value", ) @@ -10674,7 +10745,7 @@ def test_delete_self_flattened(): assert arg == mock_val -def test_delete_self_flattened_error(): +def test_fetch_git_repository_link_pull_request_list_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10682,29 +10753,33 @@ def test_delete_self_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_self( - developer_connect.DeleteSelfRequest(), + client.fetch_git_repository_link_pull_request_list( + developer_connect.FetchGitRepositoryLinkPullRequestListRequest(), name="name_value", ) @pytest.mark.asyncio -async def test_delete_self_flattened_async(): +async def test_fetch_git_repository_link_pull_request_list_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_self), "__call__") as call: + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse() + ) call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + developer_connect.FetchGitRepositoryLinkPullRequestListResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_self( + response = await client.fetch_git_repository_link_pull_request_list( name="name_value", ) @@ -10718,7 +10793,7 @@ async def test_delete_self_flattened_async(): @pytest.mark.asyncio -async def test_delete_self_flattened_error_async(): +async def test_fetch_git_repository_link_pull_request_list_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10726,60 +10801,266 @@ async def test_delete_self_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.delete_self( - developer_connect.DeleteSelfRequest(), + await client.fetch_git_repository_link_pull_request_list( + developer_connect.FetchGitRepositoryLinkPullRequestListRequest(), name="name_value", ) -@pytest.mark.parametrize( - "request_type", - [ - developer_connect.StartOAuthRequest(), - {}, - ], -) -def test_start_o_auth(request_type, transport: str = "grpc"): +def test_fetch_git_repository_link_pull_request_list_pager( + transport_name: str = "grpc", +): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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_o_auth), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = developer_connect.StartOAuthResponse( - ticket="ticket_value", - code_challenge="code_challenge_value", - code_challenge_method="code_challenge_method_value", - client_id="client_id_value", - scopes=["scopes_value"], - auth_uri="auth_uri_value", - system_provider_id=developer_connect.SystemProvider.GITHUB, + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + ), + RuntimeError, ) - response = client.start_o_auth(request) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), + ) + pager = client.fetch_git_repository_link_pull_request_list( + 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, developer_connect.PullRequest) for i in results) + + +def test_fetch_git_repository_link_pull_request_list_pages( + transport_name: str = "grpc", +): + client = DeveloperConnectClient( + 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.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + ), + RuntimeError, + ) + pages = list( + client.fetch_git_repository_link_pull_request_list(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_fetch_git_repository_link_pull_request_list_async_pager(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + ), + RuntimeError, + ) + async_pager = await client.fetch_git_repository_link_pull_request_list( + 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, developer_connect.PullRequest) for i in responses) + + +@pytest.mark.asyncio +async def test_fetch_git_repository_link_pull_request_list_async_pages(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.fetch_git_repository_link_pull_request_list(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", + [ + developer_connect.ListAccountConnectorsRequest(), + {}, + ], +) +def test_list_account_connectors(request_type, transport: str = "grpc"): + client = DeveloperConnectClient( + 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_account_connectors), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.ListAccountConnectorsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_account_connectors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = developer_connect.StartOAuthRequest() + request = developer_connect.ListAccountConnectorsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.StartOAuthResponse) - assert response.ticket == "ticket_value" - assert response.code_challenge == "code_challenge_value" - assert response.code_challenge_method == "code_challenge_method_value" - assert response.client_id == "client_id_value" - assert response.scopes == ["scopes_value"] - assert response.auth_uri == "auth_uri_value" + assert isinstance(response, pagers.ListAccountConnectorsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_start_o_auth_non_empty_request_with_auto_populated_field(): +def test_list_account_connectors_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 = DeveloperConnectClient( @@ -10790,25 +11071,33 @@ def test_start_o_auth_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 = developer_connect.StartOAuthRequest( - account_connector="account_connector_value", + request = developer_connect.ListAccountConnectorsRequest( + 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.start_o_auth), "__call__") as call: + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.start_o_auth(request=request) + client.list_account_connectors(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = developer_connect.StartOAuthRequest( - account_connector="account_connector_value", + request_msg = developer_connect.ListAccountConnectorsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) assert args[0] == request_msg -def test_start_o_auth_use_cached_wrapped_rpc(): +def test_list_account_connectors_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: @@ -10822,21 +11111,26 @@ def test_start_o_auth_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.start_o_auth in client._transport._wrapped_methods + assert ( + client._transport.list_account_connectors + 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_o_auth] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_account_connectors + ] = mock_rpc request = {} - client.start_o_auth(request) + client.list_account_connectors(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.start_o_auth(request) + client.list_account_connectors(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10844,7 +11138,7 @@ def test_start_o_auth_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_start_o_auth_async_use_cached_wrapped_rpc( +async def test_list_account_connectors_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10861,7 +11155,7 @@ async def test_start_o_auth_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.start_o_auth + client._client._transport.list_account_connectors in client._client._transport._wrapped_methods ) @@ -10869,16 +11163,16 @@ async def test_start_o_auth_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.start_o_auth + client._client._transport.list_account_connectors ] = mock_rpc request = {} - await client.start_o_auth(request) + await client.list_account_connectors(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.start_o_auth(request) + await client.list_account_connectors(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10889,11 +11183,13 @@ async def test_start_o_auth_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.StartOAuthRequest(), + developer_connect.ListAccountConnectorsRequest(), {}, ], ) -async def test_start_o_auth_async(request_type, transport: str = "grpc_asyncio"): +async def test_list_account_connectors_async( + request_type, transport: str = "grpc_asyncio" +): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -10904,51 +11200,47 @@ async def test_start_o_auth_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.start_o_auth), "__call__") as call: + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.StartOAuthResponse( - ticket="ticket_value", - code_challenge="code_challenge_value", - code_challenge_method="code_challenge_method_value", - client_id="client_id_value", - scopes=["scopes_value"], - auth_uri="auth_uri_value", + developer_connect.ListAccountConnectorsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) ) - response = await client.start_o_auth(request) + response = await client.list_account_connectors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.StartOAuthRequest() + request = developer_connect.ListAccountConnectorsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.StartOAuthResponse) - assert response.ticket == "ticket_value" - assert response.code_challenge == "code_challenge_value" - assert response.code_challenge_method == "code_challenge_method_value" - assert response.client_id == "client_id_value" - assert response.scopes == ["scopes_value"] - assert response.auth_uri == "auth_uri_value" + assert isinstance(response, pagers.ListAccountConnectorsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_start_o_auth_field_headers(): +def test_list_account_connectors_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.StartOAuthRequest() + request = developer_connect.ListAccountConnectorsRequest() - request.account_connector = "account_connector_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: - call.return_value = developer_connect.StartOAuthResponse() - client.start_o_auth(request) + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: + call.return_value = developer_connect.ListAccountConnectorsResponse() + client.list_account_connectors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10959,28 +11251,30 @@ def test_start_o_auth_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "account_connector=account_connector_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_start_o_auth_field_headers_async(): +async def test_list_account_connectors_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.StartOAuthRequest() + request = developer_connect.ListAccountConnectorsRequest() - request.account_connector = "account_connector_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.StartOAuthResponse() + developer_connect.ListAccountConnectorsResponse() ) - await client.start_o_auth(request) + await client.list_account_connectors(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10991,35 +11285,37 @@ async def test_start_o_auth_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "account_connector=account_connector_value", + "parent=parent_value", ) in kw["metadata"] -def test_start_o_auth_flattened(): +def test_list_account_connectors_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.StartOAuthResponse() + call.return_value = developer_connect.ListAccountConnectorsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.start_o_auth( - account_connector="account_connector_value", + client.list_account_connectors( + 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].account_connector - mock_val = "account_connector_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_start_o_auth_flattened_error(): +def test_list_account_connectors_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11027,43 +11323,45 @@ def test_start_o_auth_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.start_o_auth( - developer_connect.StartOAuthRequest(), - account_connector="account_connector_value", + client.list_account_connectors( + developer_connect.ListAccountConnectorsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_start_o_auth_flattened_async(): +async def test_list_account_connectors_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.StartOAuthResponse() + call.return_value = developer_connect.ListAccountConnectorsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.StartOAuthResponse() + developer_connect.ListAccountConnectorsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.start_o_auth( - account_connector="account_connector_value", + response = await client.list_account_connectors( + 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].account_connector - mock_val = "account_connector_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_start_o_auth_flattened_error_async(): +async def test_list_account_connectors_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11071,103 +11369,322 @@ async def test_start_o_auth_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.start_o_auth( - developer_connect.StartOAuthRequest(), - account_connector="account_connector_value", + await client.list_account_connectors( + developer_connect.ListAccountConnectorsRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - developer_connect.FinishOAuthRequest(), - {}, - ], -) -def test_finish_o_auth(request_type, transport: str = "grpc"): +def test_list_account_connectors_pager(transport_name: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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_o_auth), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = developer_connect.FinishOAuthResponse() - response = client.finish_o_auth(request) + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + next_page_token="abc", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[], + next_page_token="def", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + ], + next_page_token="ghi", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + ), + RuntimeError, + ) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = developer_connect.FinishOAuthRequest() - assert args[0] == request + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_account_connectors(request={}, retry=retry, timeout=timeout) - # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.FinishOAuthResponse) + 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__}<") -def test_finish_o_auth_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. + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, developer_connect.AccountConnector) for i in results) + + +def test_list_account_connectors_pages(transport_name: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport_name, ) - # 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 = developer_connect.FinishOAuthRequest( - account_connector="account_connector_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + next_page_token="abc", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[], + next_page_token="def", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + ], + next_page_token="ghi", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + ), + RuntimeError, + ) + pages = list(client.list_account_connectors(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_account_connectors_async_pager(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: - call.return_value.name = ( - "foo" # operation_request.operation in compute client(s) expect a string. + with mock.patch.object( + type(client.transport.list_account_connectors), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + next_page_token="abc", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[], + next_page_token="def", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + ], + next_page_token="ghi", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + ), + RuntimeError, ) - client.finish_o_auth(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FinishOAuthRequest( - account_connector="account_connector_value", + async_pager = await client.list_account_connectors( + request={}, ) - assert args[0] == request_msg - + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") -def test_finish_o_auth_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 = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + assert len(responses) == 6 + assert all(isinstance(i, developer_connect.AccountConnector) for i in responses) - # Ensure method has been cached - assert client._transport.finish_o_auth in client._transport._wrapped_methods - # Replace cached wrapped function with mock - mock_rpc = mock.Mock() - mock_rpc.return_value.name = ( +@pytest.mark.asyncio +async def test_list_account_connectors_async_pages(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_account_connectors), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + next_page_token="abc", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[], + next_page_token="def", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + ], + next_page_token="ghi", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_account_connectors(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", + [ + developer_connect.GetAccountConnectorRequest(), + {}, + ], +) +def test_get_account_connector(request_type, transport: str = "grpc"): + client = DeveloperConnectClient( + 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_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.AccountConnector( + name="name_value", + etag="etag_value", + oauth_start_uri="oauth_start_uri_value", + ) + response = client.get_account_connector(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.GetAccountConnectorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, developer_connect.AccountConnector) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.oauth_start_uri == "oauth_start_uri_value" + + +def test_get_account_connector_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 = DeveloperConnectClient( + 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 = developer_connect.GetAccountConnectorRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_account_connector), "__call__" + ) as call: + call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.finish_o_auth] = mock_rpc + client.get_account_connector(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.GetAccountConnectorRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_account_connector_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 = DeveloperConnectClient( + 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_account_connector + 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_account_connector] = ( + mock_rpc + ) request = {} - client.finish_o_auth(request) + client.get_account_connector(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.finish_o_auth(request) + client.get_account_connector(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11175,7 +11692,7 @@ def test_finish_o_auth_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_finish_o_auth_async_use_cached_wrapped_rpc( +async def test_get_account_connector_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11192,7 +11709,7 @@ async def test_finish_o_auth_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.finish_o_auth + client._client._transport.get_account_connector in client._client._transport._wrapped_methods ) @@ -11200,16 +11717,16 @@ async def test_finish_o_auth_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.finish_o_auth + client._client._transport.get_account_connector ] = mock_rpc request = {} - await client.finish_o_auth(request) + await client.get_account_connector(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.finish_o_auth(request) + await client.get_account_connector(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11220,11 +11737,13 @@ async def test_finish_o_auth_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - developer_connect.FinishOAuthRequest(), + developer_connect.GetAccountConnectorRequest(), {}, ], ) -async def test_finish_o_auth_async(request_type, transport: str = "grpc_asyncio"): +async def test_get_account_connector_async( + request_type, transport: str = "grpc_asyncio" +): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -11235,38 +11754,49 @@ async def test_finish_o_auth_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.finish_o_auth), "__call__") as call: + with mock.patch.object( + type(client.transport.get_account_connector), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FinishOAuthResponse() + developer_connect.AccountConnector( + name="name_value", + etag="etag_value", + oauth_start_uri="oauth_start_uri_value", + ) ) - response = await client.finish_o_auth(request) + response = await client.get_account_connector(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = developer_connect.FinishOAuthRequest() + request = developer_connect.GetAccountConnectorRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.FinishOAuthResponse) + assert isinstance(response, developer_connect.AccountConnector) + assert response.name == "name_value" + assert response.etag == "etag_value" + assert response.oauth_start_uri == "oauth_start_uri_value" -def test_finish_o_auth_field_headers(): +def test_get_account_connector_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.FinishOAuthRequest() + request = developer_connect.GetAccountConnectorRequest() - request.account_connector = "account_connector_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: - call.return_value = developer_connect.FinishOAuthResponse() - client.finish_o_auth(request) + with mock.patch.object( + type(client.transport.get_account_connector), "__call__" + ) as call: + call.return_value = developer_connect.AccountConnector() + client.get_account_connector(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11277,28 +11807,30 @@ def test_finish_o_auth_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "account_connector=account_connector_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_finish_o_auth_field_headers_async(): +async def test_get_account_connector_field_headers_async(): client = DeveloperConnectAsyncClient( 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 = developer_connect.FinishOAuthRequest() + request = developer_connect.GetAccountConnectorRequest() - request.account_connector = "account_connector_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + with mock.patch.object( + type(client.transport.get_account_connector), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FinishOAuthResponse() + developer_connect.AccountConnector() ) - await client.finish_o_auth(request) + await client.get_account_connector(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11309,35 +11841,37 @@ async def test_finish_o_auth_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "account_connector=account_connector_value", + "name=name_value", ) in kw["metadata"] -def test_finish_o_auth_flattened(): +def test_get_account_connector_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + with mock.patch.object( + type(client.transport.get_account_connector), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FinishOAuthResponse() + call.return_value = developer_connect.AccountConnector() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.finish_o_auth( - account_connector="account_connector_value", + client.get_account_connector( + 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].account_connector - mock_val = "account_connector_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_finish_o_auth_flattened_error(): +def test_get_account_connector_flattened_error(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11345,43 +11879,45 @@ def test_finish_o_auth_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.finish_o_auth( - developer_connect.FinishOAuthRequest(), - account_connector="account_connector_value", + client.get_account_connector( + developer_connect.GetAccountConnectorRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_finish_o_auth_flattened_async(): +async def test_get_account_connector_flattened_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + with mock.patch.object( + type(client.transport.get_account_connector), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = developer_connect.FinishOAuthResponse() + call.return_value = developer_connect.AccountConnector() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FinishOAuthResponse() + developer_connect.AccountConnector() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.finish_o_auth( - account_connector="account_connector_value", + response = await client.get_account_connector( + 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].account_connector - mock_val = "account_connector_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_finish_o_auth_flattened_error_async(): +async def test_get_account_connector_flattened_error_async(): client = DeveloperConnectAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11389,19 +11925,87 @@ async def test_finish_o_auth_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.finish_o_auth( - developer_connect.FinishOAuthRequest(), - account_connector="account_connector_value", + await client.get_account_connector( + developer_connect.GetAccountConnectorRequest(), + name="name_value", ) -def test_list_connections_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.CreateAccountConnectorRequest(), + {}, + ], +) +def test_create_account_connector(request_type, transport: str = "grpc"): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_account_connector(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.CreateAccountConnectorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_account_connector_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 = DeveloperConnectClient( + 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 = developer_connect.CreateAccountConnectorRequest( + parent="parent_value", + account_connector_id="account_connector_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_account_connector), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_account_connector(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.CreateAccountConnectorRequest( + parent="parent_value", + account_connector_id="account_connector_id_value", + ) + assert args[0] == request_msg + + +def test_create_account_connector_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -11409,417 +12013,388 @@ def test_list_connections_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_connections in client._transport._wrapped_methods + assert ( + client._transport.create_account_connector + 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_connections] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.create_account_connector + ] = mock_rpc request = {} - client.list_connections(request) + client.create_account_connector(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_connections(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.create_account_connector(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_connections_rest_required_fields( - request_type=developer_connect.ListConnectionsRequest, +@pytest.mark.asyncio +async def test_create_account_connector_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.DeveloperConnectRestTransport + # Clients should use _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 = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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.create_account_connector + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseListConnections, - "_BaseListConnections__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.create_account_connector + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.create_account_connector(request) - jsonified_request["parent"] = "parent_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) + # 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() - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + await client.create_account_connector(request) - client = DeveloperConnectClient( - 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 = developer_connect.ListConnectionsResponse() - # 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", + [ + developer_connect.CreateAccountConnectorRequest(), + {}, + ], +) +async def test_create_account_connector_async( + request_type, transport: str = "grpc_asyncio" +): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Convert return value to protobuf type - return_value = developer_connect.ListConnectionsResponse.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.create_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_account_connector(request) - response = client.list_connections(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.CreateAccountConnectorRequest() + 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, future.Future) -def test_list_connections_rest_flattened(): +def test_create_account_connector_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.ListConnectionsResponse() + # 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 = developer_connect.CreateAccountConnectorRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_account_connector), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_account_connector(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_account_connector_field_headers_async(): + client = DeveloperConnectAsyncClient( + 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 = developer_connect.CreateAccountConnectorRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_account_connector), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.create_account_connector(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 = developer_connect.ListConnectionsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.list_connections(**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_create_account_connector_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_account_connector( + parent="parent_value", + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + account_connector_id="account_connector_id_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/v1/{parent=projects/*/locations/*}/connections" - % 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 + arg = args[0].account_connector + mock_val = developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) ) + assert arg == mock_val + arg = args[0].account_connector_id + mock_val = "account_connector_id_value" + assert arg == mock_val -def test_list_connections_rest_flattened_error(transport: str = "rest"): +def test_create_account_connector_flattened_error(): client = DeveloperConnectClient( 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_connections( - developer_connect.ListConnectionsRequest(), + client.create_account_connector( + developer_connect.CreateAccountConnectorRequest(), parent="parent_value", + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + account_connector_id="account_connector_id_value", ) -def test_list_connections_rest_pager(transport: str = "rest"): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_create_account_connector_flattened_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = ( - developer_connect.ListConnectionsResponse( - connections=[ - developer_connect.Connection(), - developer_connect.Connection(), - developer_connect.Connection(), - ], - next_page_token="abc", - ), - developer_connect.ListConnectionsResponse( - connections=[], - next_page_token="def", - ), - developer_connect.ListConnectionsResponse( - connections=[ - developer_connect.Connection(), - ], - next_page_token="ghi", - ), - developer_connect.ListConnectionsResponse( - connections=[ - developer_connect.Connection(), - developer_connect.Connection(), - ], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_account_connector( + parent="parent_value", + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) ), + account_connector_id="account_connector_id_value", ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - developer_connect.ListConnectionsResponse.to_json(x) for x in 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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].account_connector + mock_val = developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) ) - 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_connections(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, developer_connect.Connection) for i in results) + assert arg == mock_val + arg = args[0].account_connector_id + mock_val = "account_connector_id_value" + assert arg == mock_val - pages = list(client.list_connections(request=sample_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_create_account_connector_flattened_error_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_get_connection_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 = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_account_connector( + developer_connect.CreateAccountConnectorRequest(), + parent="parent_value", + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + account_connector_id="account_connector_id_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.get_connection in client._transport._wrapped_methods +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.UpdateAccountConnectorRequest(), + {}, + ], +) +def test_update_account_connector(request_type, transport: str = "grpc"): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # 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_connection] = mock_rpc + # 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 - request = {} - client.get_connection(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_account_connector(request) # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.get_connection(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_connection_rest_required_fields( - request_type=developer_connect.GetConnectionRequest, -): - transport_class = transports.DeveloperConnectRestTransport - - 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 - - default_values = getattr( - transport_class._BaseGetConnection, - "_BaseGetConnection__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" - - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" - - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = developer_connect.Connection() - # 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 = developer_connect.Connection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._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_connection(request) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.UpdateAccountConnectorRequest() + 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, future.Future) -def test_get_connection_rest_flattened(): +def test_update_account_connector_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 = DeveloperConnectClient( 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 = developer_connect.Connection() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/connections/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 = developer_connect.Connection.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_connection(**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/*/connections/*}" - % client.transport._host, - args[1], - ) - - -def test_get_connection_rest_flattened_error(transport: str = "rest"): - client = DeveloperConnectClient( - 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 = developer_connect.UpdateAccountConnectorRequest() - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_connection( - developer_connect.GetConnectionRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_connector), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client.update_account_connector(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.UpdateAccountConnectorRequest() + assert args[0] == request_msg -def test_create_connection_rest_use_cached_wrapped_rpc(): +def test_update_account_connector_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -11827,394 +12402,384 @@ def test_create_connection_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_connection in client._transport._wrapped_methods + assert ( + client._transport.update_account_connector + 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_connection] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.update_account_connector + ] = mock_rpc request = {} - client.create_connection(request) + client.update_account_connector(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 + # 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.create_connection(request) + client.update_account_connector(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_connection_rest_required_fields( - request_type=developer_connect.CreateConnectionRequest, +@pytest.mark.asyncio +async def test_update_account_connector_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.DeveloperConnectRestTransport + # Clients should use _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 = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["parent"] = "" - request_init["connection_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) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped - assert "connectionId" not in jsonified_request + # Ensure method has been cached + assert ( + client._client._transport.update_account_connector + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseCreateConnection, - "_BaseCreateConnection__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.update_account_connector + ] = mock_rpc - # verify required fields with default values are now present - assert "connectionId" in jsonified_request - assert jsonified_request["connectionId"] == request_init["connection_id"] + request = {} + await client.update_account_connector(request) - jsonified_request["parent"] = "parent_value" - jsonified_request["connectionId"] = "connection_id_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "connectionId", - "requestId", - "validateOnly", - ) + # 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.update_account_connector(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", + [ + developer_connect.UpdateAccountConnectorRequest(), + {}, + ], +) +async def test_update_account_connector_async( + request_type, transport: str = "grpc_asyncio" +): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "connectionId" in jsonified_request - assert jsonified_request["connectionId"] == "connection_id_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 + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_connector), "__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.update_account_connector(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.UpdateAccountConnectorRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + +def test_update_account_connector_field_headers(): client = DeveloperConnectClient( 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 + # 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 = developer_connect.UpdateAccountConnectorRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.account_connector.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.update_account_connector), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_account_connector(request) - response = client.create_connection(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 = [ - ( - "connectionId", - "", - ), - ("$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", + "account_connector.name=name_value", + ) in kw["metadata"] -def test_create_connection_rest_flattened(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_update_account_connector_field_headers_async(): + client = DeveloperConnectAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = developer_connect.UpdateAccountConnectorRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.account_connector.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - connection=developer_connect.Connection( - github_config=developer_connect.GitHubConfig( - github_app=developer_connect.GitHubConfig.GitHubApp.DEVELOPER_CONNECT - ) - ), - connection_id="connection_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_connector), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.update_account_connector(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.create_connection(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "account_connector.name=name_value", + ) in kw["metadata"] + + +def test_update_account_connector_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_connector), "__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.update_account_connector( + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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/v1/{parent=projects/*/locations/*}/connections" - % client.transport._host, - args[1], + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].account_connector + mock_val = developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val -def test_create_connection_rest_flattened_error(transport: str = "rest"): +def test_update_account_connector_flattened_error(): client = DeveloperConnectClient( 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_connection( - developer_connect.CreateConnectionRequest(), - parent="parent_value", - connection=developer_connect.Connection( - github_config=developer_connect.GitHubConfig( - github_app=developer_connect.GitHubConfig.GitHubApp.DEVELOPER_CONNECT + client.update_account_connector( + developer_connect.UpdateAccountConnectorRequest(), + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB ) ), - connection_id="connection_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_update_connection_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 = DeveloperConnectClient( - 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_update_account_connector_flattened_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.update_connection in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.update_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # 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( + operations_pb2.Operation(name="operations/spam") ) - client._transport._wrapped_methods[client._transport.update_connection] = ( - mock_rpc + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_account_connector( + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - request = {} - client.update_connection(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_connection(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_connection_rest_required_fields( - request_type=developer_connect.UpdateConnectionRequest, -): - transport_class = transports.DeveloperConnectRestTransport - - 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) - ) + # 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].account_connector + mock_val = developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ) + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseUpdateConnection, - "_BaseUpdateConnection__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_update_account_connector_flattened_error_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allowMissing", - "requestId", - "updateMask", - "validateOnly", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_account_connector( + developer_connect.UpdateAccountConnectorRequest(), + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) - ) - # verify required fields with non-default values are left alone +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.DeleteAccountConnectorRequest(), + {}, + ], +) +def test_delete_account_connector(request_type, transport: str = "grpc"): client = DeveloperConnectClient( 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": "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) + # 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.delete_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_account_connector(request) - response = client.update_connection(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.DeleteAccountConnectorRequest() + 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, future.Future) -def test_update_connection_rest_flattened(): +def test_delete_account_connector_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 = DeveloperConnectClient( 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 = { - "connection": { - "name": "projects/sample1/locations/sample2/connections/sample3" - } - } - - # get truthy value for each flattened field - mock_args = dict( - connection=developer_connect.Connection( - github_config=developer_connect.GitHubConfig( - github_app=developer_connect.GitHubConfig.GitHubApp.DEVELOPER_CONNECT - ) - ), - 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_connection(**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/{connection.name=projects/*/locations/*/connections/*}" - % client.transport._host, - args[1], - ) - - -def test_update_connection_rest_flattened_error(transport: str = "rest"): - client = DeveloperConnectClient( - 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 = developer_connect.DeleteAccountConnectorRequest( + name="name_value", + etag="etag_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_connection( - developer_connect.UpdateConnectionRequest(), - connection=developer_connect.Connection( - github_config=developer_connect.GitHubConfig( - github_app=developer_connect.GitHubConfig.GitHubApp.DEVELOPER_CONNECT - ) - ), - 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.delete_account_connector), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client.delete_account_connector(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteAccountConnectorRequest( + name="name_value", + etag="etag_value", + ) + assert args[0] == request_msg -def test_delete_connection_rest_use_cached_wrapped_rpc(): +def test_delete_account_connector_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -12222,385 +12787,353 @@ def test_delete_connection_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_connection in client._transport._wrapped_methods + assert ( + client._transport.delete_account_connector + 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_connection] = ( - mock_rpc - ) - + client._transport._wrapped_methods[ + client._transport.delete_account_connector + ] = mock_rpc request = {} - client.delete_connection(request) + client.delete_account_connector(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 + # 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_connection(request) + client.delete_account_connector(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_connection_rest_required_fields( - request_type=developer_connect.DeleteConnectionRequest, +@pytest.mark.asyncio +async def test_delete_account_connector_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.DeveloperConnectRestTransport + # Clients should use _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 = DeveloperConnectAsyncClient( + 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.delete_account_connector + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseDeleteConnection, - "_BaseDeleteConnection__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_account_connector + ] = mock_rpc + + request = {} + await client.delete_account_connector(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_account_connector(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", + [ + developer_connect.DeleteAccountConnectorRequest(), {}, + ], +) +async def test_delete_account_connector_async( + request_type, transport: str = "grpc_asyncio" +): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["name"] = "name_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "requestId", - "validateOnly", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account_connector), "__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_account_connector(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.DeleteAccountConnectorRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_account_connector_field_headers(): client = DeveloperConnectClient( 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 + # 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 = developer_connect.DeleteAccountConnectorRequest() - 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.delete_account_connector), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_account_connector(request) - response = client.delete_connection(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_delete_connection_rest_flattened(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_delete_account_connector_field_headers_async(): + client = DeveloperConnectAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = developer_connect.DeleteAccountConnectorRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/connections/sample3" - } + request.name = "name_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.delete_account_connector), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.delete_account_connector(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_connection(**mock_args) + # 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_account_connector_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account_connector), "__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_account_connector( + name="name_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/v1/{name=projects/*/locations/*/connections/*}" - % 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_delete_connection_rest_flattened_error(transport: str = "rest"): +def test_delete_account_connector_flattened_error(): client = DeveloperConnectClient( 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_connection( - developer_connect.DeleteConnectionRequest(), + client.delete_account_connector( + developer_connect.DeleteAccountConnectorRequest(), name="name_value", ) -def test_create_git_repository_link_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 = DeveloperConnectClient( - 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_delete_account_connector_flattened_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert ( - client._transport.create_git_repository_link - in client._transport._wrapped_methods - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # 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( + 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_account_connector( + name="name_value", ) - client._transport._wrapped_methods[ - client._transport.create_git_repository_link - ] = mock_rpc - - request = {} - client.create_git_repository_link(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_git_repository_link(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_git_repository_link_rest_required_fields( - request_type=developer_connect.CreateGitRepositoryLinkRequest, -): - transport_class = transports.DeveloperConnectRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["git_repository_link_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 "gitRepositoryLinkId" not in jsonified_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].name + mock_val = "name_value" + assert arg == mock_val - default_values = getattr( - transport_class._BaseCreateGitRepositoryLink, - "_BaseCreateGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - assert "gitRepositoryLinkId" in jsonified_request - assert ( - jsonified_request["gitRepositoryLinkId"] - == request_init["git_repository_link_id"] +@pytest.mark.asyncio +async def test_delete_account_connector_flattened_error_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), ) - jsonified_request["parent"] = "parent_value" - jsonified_request["gitRepositoryLinkId"] = "git_repository_link_id_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "gitRepositoryLinkId", - "requestId", - "validateOnly", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_account_connector( + developer_connect.DeleteAccountConnectorRequest(), + name="name_value", ) - ) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "gitRepositoryLinkId" in jsonified_request - assert jsonified_request["gitRepositoryLinkId"] == "git_repository_link_id_value" +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.FetchAccessTokenRequest(), + {}, + ], +) +def test_fetch_access_token(request_type, transport: str = "grpc"): client = DeveloperConnectClient( 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": "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) + # 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.fetch_access_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.FetchAccessTokenResponse( + token="token_value", + scopes=["scopes_value"], + ) + response = client.fetch_access_token(request) - response = client.create_git_repository_link(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.FetchAccessTokenRequest() + assert args[0] == request - expected_params = [ - ( - "gitRepositoryLinkId", - "", - ), - ("$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, developer_connect.FetchAccessTokenResponse) + assert response.token == "token_value" + assert response.scopes == ["scopes_value"] -def test_create_git_repository_link_rest_flattened(): +def test_fetch_access_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 = DeveloperConnectClient( 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 = { - "parent": "projects/sample1/locations/sample2/connections/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - git_repository_link=developer_connect.GitRepositoryLink(name="name_value"), - git_repository_link_id="git_repository_link_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_git_repository_link(**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/*/connections/*}/gitRepositoryLinks" - % client.transport._host, - args[1], - ) - - -def test_create_git_repository_link_rest_flattened_error(transport: str = "rest"): - client = DeveloperConnectClient( - 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 = developer_connect.FetchAccessTokenRequest( + account_connector="account_connector_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_git_repository_link( - developer_connect.CreateGitRepositoryLinkRequest(), - parent="parent_value", - git_repository_link=developer_connect.GitRepositoryLink(name="name_value"), - git_repository_link_id="git_repository_link_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_access_token), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_access_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchAccessTokenRequest( + account_connector="account_connector_value", ) + assert args[0] == request_msg -def test_delete_git_repository_link_rest_use_cached_wrapped_rpc(): +def test_fetch_access_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -12609,8 +13142,7 @@ def test_delete_git_repository_link_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_git_repository_link - in client._transport._wrapped_methods + client._transport.fetch_access_token in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -12618,173 +13150,338 @@ def test_delete_git_repository_link_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.delete_git_repository_link - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.fetch_access_token] = ( + mock_rpc + ) request = {} - client.delete_git_repository_link(request) + client.fetch_access_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_git_repository_link(request) + client.fetch_access_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_git_repository_link_rest_required_fields( - request_type=developer_connect.DeleteGitRepositoryLinkRequest, +@pytest.mark.asyncio +async def test_fetch_access_token_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.DeveloperConnectRestTransport + # Clients should use _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 = DeveloperConnectAsyncClient( + 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.fetch_access_token + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseDeleteGitRepositoryLink, - "_BaseDeleteGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.fetch_access_token + ] = mock_rpc + + request = {} + await client.fetch_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.fetch_access_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", + [ + developer_connect.FetchAccessTokenRequest(), {}, + ], +) +async def test_fetch_access_token_async(request_type, transport: str = "grpc_asyncio"): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["name"] = "name_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "requestId", - "validateOnly", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_access_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchAccessTokenResponse( + token="token_value", + scopes=["scopes_value"], + ) ) - ) + response = await client.fetch_access_token(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.FetchAccessTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, developer_connect.FetchAccessTokenResponse) + assert response.token == "token_value" + assert response.scopes == ["scopes_value"] + +def test_fetch_access_token_field_headers(): client = DeveloperConnectClient( 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 + # 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 = developer_connect.FetchAccessTokenRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.account_connector = "account_connector_value" - response_value._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.fetch_access_token), "__call__" + ) as call: + call.return_value = developer_connect.FetchAccessTokenResponse() + client.fetch_access_token(request) - response = client.delete_git_repository_link(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", + "account_connector=account_connector_value", + ) in kw["metadata"] -def test_delete_git_repository_link_rest_flattened(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_fetch_access_token_field_headers_async(): + client = DeveloperConnectAsyncClient( + 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 = operations_pb2.Operation(name="operations/spam") + # 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 = developer_connect.FetchAccessTokenRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" - } + request.account_connector = "account_connector_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.fetch_access_token), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchAccessTokenResponse() ) - mock_args.update(sample_request) + await client.fetch_access_token(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) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.delete_git_repository_link(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "account_connector=account_connector_value", + ) in kw["metadata"] + + +def test_fetch_access_token_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_access_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.FetchAccessTokenResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_access_token( + account_connector="account_connector_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/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].account_connector + mock_val = "account_connector_value" + assert arg == mock_val -def test_delete_git_repository_link_rest_flattened_error(transport: str = "rest"): +def test_fetch_access_token_flattened_error(): client = DeveloperConnectClient( 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_git_repository_link( - developer_connect.DeleteGitRepositoryLinkRequest(), - name="name_value", + client.fetch_access_token( + developer_connect.FetchAccessTokenRequest(), + account_connector="account_connector_value", ) -def test_list_git_repository_links_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_fetch_access_token_flattened_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.fetch_access_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.FetchAccessTokenResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchAccessTokenResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.fetch_access_token( + account_connector="account_connector_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].account_connector + mock_val = "account_connector_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_fetch_access_token_flattened_error_async(): + client = DeveloperConnectAsyncClient( + 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.fetch_access_token( + developer_connect.FetchAccessTokenRequest(), + account_connector="account_connector_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.ListUsersRequest(), + {}, + ], +) +def test_list_users(request_type, transport: str = "grpc"): + client = DeveloperConnectClient( + 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_users), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.ListUsersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_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 = DeveloperConnectClient( + 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 = developer_connect.ListUsersRequest( + 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_users), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_users(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ListUsersRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -12792,432 +13489,517 @@ def test_list_git_repository_links_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_git_repository_links - in client._transport._wrapped_methods - ) + assert client._transport.list_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_git_repository_links - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_users] = mock_rpc request = {} - client.list_git_repository_links(request) + client.list_users(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_git_repository_links(request) + client.list_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_git_repository_links_rest_required_fields( - request_type=developer_connect.ListGitRepositoryLinksRequest, -): - transport_class = transports.DeveloperConnectRestTransport +@pytest.mark.asyncio +async def test_list_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 = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - 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) - ) + # 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_users + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseListGitRepositoryLinks, - "_BaseListGitRepositoryLinks__REQUIRED_FIELDS_DEFAULT_VALUES", + # 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_users + ] = mock_rpc + + request = {} + await client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_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", + [ + developer_connect.ListUsersRequest(), {}, + ], +) +async def test_list_users_async(request_type, transport: str = "grpc_asyncio"): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - ) + response = await client.list_users(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.ListUsersRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListUsersAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_users_field_headers(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = developer_connect.ListGitRepositoryLinksResponse() - # 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 + # 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 = developer_connect.ListUsersRequest() - response_value = Response() - response_value.status_code = 200 + request.parent = "parent_value" - # Convert return value to protobuf type - return_value = developer_connect.ListGitRepositoryLinksResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + call.return_value = developer_connect.ListUsersResponse() + client.list_users(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.list_git_repository_links(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_list_users_field_headers_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_list_git_repository_links_rest_flattened(): + # 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 = developer_connect.ListUsersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.ListUsersResponse() + ) + await client.list_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_users_flattened(): client = DeveloperConnectClient( 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 = developer_connect.ListGitRepositoryLinksResponse() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.ListUsersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_users( + parent="parent_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/connections/sample3" - } + # 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 - # get truthy value for each flattened field - mock_args = dict( + +def test_list_users_flattened_error(): + client = DeveloperConnectClient( + 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_users( + developer_connect.ListUsersRequest(), 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 = developer_connect.ListGitRepositoryLinksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_git_repository_links(**mock_args) +@pytest.mark.asyncio +async def test_list_users_flattened_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.ListUsersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.ListUsersResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_users( + 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/v1/{parent=projects/*/locations/*/connections/*}/gitRepositoryLinks" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_list_git_repository_links_rest_flattened_error(transport: str = "rest"): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_list_users_flattened_error_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_git_repository_links( - developer_connect.ListGitRepositoryLinksRequest(), + await client.list_users( + developer_connect.ListUsersRequest(), parent="parent_value", ) -def test_list_git_repository_links_rest_pager(transport: str = "rest"): +def test_list_users_pager(transport_name: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport=transport_name, ) - # 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 = ( - developer_connect.ListGitRepositoryLinksResponse( - git_repository_links=[ - developer_connect.GitRepositoryLink(), - developer_connect.GitRepositoryLink(), - developer_connect.GitRepositoryLink(), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), + developer_connect.User(), ], next_page_token="abc", ), - developer_connect.ListGitRepositoryLinksResponse( - git_repository_links=[], + developer_connect.ListUsersResponse( + users=[], next_page_token="def", ), - developer_connect.ListGitRepositoryLinksResponse( - git_repository_links=[ - developer_connect.GitRepositoryLink(), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), ], next_page_token="ghi", ), - developer_connect.ListGitRepositoryLinksResponse( - git_repository_links=[ - developer_connect.GitRepositoryLink(), - developer_connect.GitRepositoryLink(), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), ], ), + RuntimeError, ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - developer_connect.ListGitRepositoryLinksResponse.to_json(x) - for x in response + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) - 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/connections/sample3" - } + pager = client.list_users(request={}, retry=retry, timeout=timeout) - pager = client.list_git_repository_links(request=sample_request) + 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, developer_connect.GitRepositoryLink) for i in results) - - pages = list(client.list_git_repository_links(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + assert all(isinstance(i, developer_connect.User) for i in results) -def test_get_git_repository_link_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 = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_list_users_pages(transport_name: str = "grpc"): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) - # 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_git_repository_link - 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. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), + developer_connect.User(), + ], + next_page_token="abc", + ), + developer_connect.ListUsersResponse( + users=[], + next_page_token="def", + ), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + ], + next_page_token="ghi", + ), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), + ], + ), + RuntimeError, ) - client._transport._wrapped_methods[ - client._transport.get_git_repository_link - ] = mock_rpc - - request = {} - client.get_git_repository_link(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + pages = list(client.list_users(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - client.get_git_repository_link(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_users_async_pager(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), + developer_connect.User(), + ], + next_page_token="abc", + ), + developer_connect.ListUsersResponse( + users=[], + next_page_token="def", + ), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + ], + next_page_token="ghi", + ), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_users( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") -def test_get_git_repository_link_rest_required_fields( - request_type=developer_connect.GetGitRepositoryLinkRequest, -): - transport_class = transports.DeveloperConnectRestTransport + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - 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) - ) + assert len(responses) == 6 + assert all(isinstance(i, developer_connect.User) for i in responses) - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseGetGitRepositoryLink, - "_BaseGetGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_list_users_async_pages(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), + developer_connect.User(), + ], + next_page_token="abc", + ), + developer_connect.ListUsersResponse( + users=[], + next_page_token="def", + ), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + ], + next_page_token="ghi", + ), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_users(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - # 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", + [ + developer_connect.DeleteUserRequest(), + {}, + ], +) +def test_delete_user(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = developer_connect.GitRepositoryLink() - # 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 = developer_connect.GitRepositoryLink.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.delete_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_user(request) - response = client.get_git_repository_link(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.DeleteUserRequest() + 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, future.Future) -def test_get_git_repository_link_rest_flattened(): +def test_delete_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 = DeveloperConnectClient( 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 = developer_connect.GitRepositoryLink() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) + # 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 = developer_connect.DeleteUserRequest( + name="name_value", + etag="etag_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 = developer_connect.GitRepositoryLink.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_git_repository_link(**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/*/connections/*/gitRepositoryLinks/*}" - % client.transport._host, - args[1], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - -def test_get_git_repository_link_rest_flattened_error(transport: str = "rest"): - client = DeveloperConnectClient( - 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_git_repository_link( - developer_connect.GetGitRepositoryLinkRequest(), + client.delete_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteUserRequest( name="name_value", + etag="etag_value", ) + assert args[0] == request_msg -def test_fetch_read_write_token_rest_use_cached_wrapped_rpc(): +def test_delete_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -13225,178 +14007,332 @@ def test_fetch_read_write_token_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.fetch_read_write_token - in client._transport._wrapped_methods - ) + assert client._transport.delete_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.fetch_read_write_token] = ( - mock_rpc - ) - + client._transport._wrapped_methods[client._transport.delete_user] = mock_rpc request = {} - client.fetch_read_write_token(request) + client.delete_user(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_read_write_token(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.delete_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_fetch_read_write_token_rest_required_fields( - request_type=developer_connect.FetchReadWriteTokenRequest, +@pytest.mark.asyncio +async def test_delete_user_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.DeveloperConnectRestTransport + # Clients should use _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 = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["git_repository_link"] = "" - 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.delete_user + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseFetchReadWriteToken, - "_BaseFetchReadWriteToken__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.delete_user + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.delete_user(request) - jsonified_request["gitRepositoryLink"] = "git_repository_link_value" + # 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 "gitRepositoryLink" in jsonified_request - assert jsonified_request["gitRepositoryLink"] == "git_repository_link_value" + # 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 = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + await client.delete_user(request) - # Designate an appropriate value for the returned response. - return_value = developer_connect.FetchReadWriteTokenResponse() - # 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 + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = developer_connect.FetchReadWriteTokenResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.DeleteUserRequest(), + {}, + ], +) +async def test_delete_user_async(request_type, transport: str = "grpc_asyncio"): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # 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 = client.fetch_read_write_token(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_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_user(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 underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.DeleteUserRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_fetch_read_write_token_rest_flattened(): + +def test_delete_user_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.FetchReadWriteTokenResponse() + # 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 = developer_connect.DeleteUserRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" - } + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - git_repository_link="git_repository_link_value", - ) - mock_args.update(sample_request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_user(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 = developer_connect.FetchReadWriteTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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] + assert args[0] == request - client.fetch_read_write_token(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] - # 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/{git_repository_link=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchReadWriteToken" - % client.transport._host, - args[1], - ) +@pytest.mark.asyncio +async def test_delete_user_field_headers_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) -def test_fetch_read_write_token_rest_flattened_error(transport: str = "rest"): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # 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 = developer_connect.DeleteUserRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_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_user_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_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_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_user_flattened_error(): + client = DeveloperConnectClient( + 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.fetch_read_write_token( - developer_connect.FetchReadWriteTokenRequest(), - git_repository_link="git_repository_link_value", + client.delete_user( + developer_connect.DeleteUserRequest(), + name="name_value", ) -def test_fetch_read_token_rest_use_cached_wrapped_rpc(): +@pytest.mark.asyncio +async def test_delete_user_flattened_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_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_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_user_flattened_error_async(): + client = DeveloperConnectAsyncClient( + 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_user( + developer_connect.DeleteUserRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.FetchSelfRequest(), + {}, + ], +) +def test_fetch_self(request_type, transport: str = "grpc"): + client = DeveloperConnectClient( + 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.fetch_self), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.User( + name="name_value", + display_name="display_name_value", + ) + response = client.fetch_self(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.FetchSelfRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, developer_connect.User) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + + +def test_fetch_self_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 = DeveloperConnectClient( + 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 = developer_connect.FetchSelfRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.fetch_self(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchSelfRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_fetch_self_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -13404,434 +14340,320 @@ def test_fetch_read_token_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.fetch_read_token in client._transport._wrapped_methods + assert client._transport.fetch_self 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.fetch_read_token] = ( - mock_rpc - ) - + client._transport._wrapped_methods[client._transport.fetch_self] = mock_rpc request = {} - client.fetch_read_token(request) + client.fetch_self(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_read_token(request) + client.fetch_self(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_fetch_read_token_rest_required_fields( - request_type=developer_connect.FetchReadTokenRequest, -): - transport_class = transports.DeveloperConnectRestTransport +@pytest.mark.asyncio +async def test_fetch_self_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 = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["git_repository_link"] = "" - 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.fetch_self + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseFetchReadToken, - "_BaseFetchReadToken__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.fetch_self + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.fetch_self(request) - jsonified_request["gitRepositoryLink"] = "git_repository_link_value" + # 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 "gitRepositoryLink" in jsonified_request - assert jsonified_request["gitRepositoryLink"] == "git_repository_link_value" + await client.fetch_self(request) - client = DeveloperConnectClient( - 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 = developer_connect.FetchReadTokenResponse() - # 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 +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.FetchSelfRequest(), + {}, + ], +) +async def test_fetch_self_async(request_type, transport: str = "grpc_asyncio"): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Convert return value to protobuf type - return_value = developer_connect.FetchReadTokenResponse.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.fetch_self), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.User( + name="name_value", + display_name="display_name_value", + ) + ) + response = await client.fetch_self(request) - response = client.fetch_read_token(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.FetchSelfRequest() + 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, developer_connect.User) + assert response.name == "name_value" + assert response.display_name == "display_name_value" -def test_fetch_read_token_rest_flattened(): +def test_fetch_self_field_headers(): client = DeveloperConnectClient( 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 = developer_connect.FetchReadTokenResponse() + # 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 = developer_connect.FetchSelfRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" - } + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - git_repository_link="git_repository_link_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + call.return_value = developer_connect.User() + client.fetch_self(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_fetch_self_field_headers_async(): + client = DeveloperConnectAsyncClient( + 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 = developer_connect.FetchSelfRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.User() ) - mock_args.update(sample_request) + await client.fetch_self(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 = developer_connect.FetchReadTokenResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.fetch_read_token(**mock_args) + # 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_fetch_self_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.fetch_self( + name="name_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/v1/{git_repository_link=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchReadToken" - % 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_fetch_read_token_rest_flattened_error(transport: str = "rest"): +def test_fetch_self_flattened_error(): client = DeveloperConnectClient( 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.fetch_read_token( - developer_connect.FetchReadTokenRequest(), - git_repository_link="git_repository_link_value", + client.fetch_self( + developer_connect.FetchSelfRequest(), + name="name_value", ) -def test_fetch_linkable_git_repositories_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 = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_fetch_self_flattened_async(): + client = DeveloperConnectAsyncClient( + 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.fetch_self), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.User() - # Ensure method has been cached - assert ( - client._transport.fetch_linkable_git_repositories - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.User() ) - - # 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.fetch_self( + name="name_value", ) - client._transport._wrapped_methods[ - client._transport.fetch_linkable_git_repositories - ] = mock_rpc - - request = {} - client.fetch_linkable_git_repositories(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].name + mock_val = "name_value" + assert arg == mock_val - client.fetch_linkable_git_repositories(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_fetch_self_flattened_error_async(): + client = DeveloperConnectAsyncClient( + 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.fetch_self( + developer_connect.FetchSelfRequest(), + name="name_value", + ) -def test_fetch_linkable_git_repositories_rest_required_fields( - request_type=developer_connect.FetchLinkableGitRepositoriesRequest, -): - transport_class = transports.DeveloperConnectRestTransport - request_init = {} - request_init["connection"] = "" - 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.parametrize( + "request_type", + [ + developer_connect.DeleteSelfRequest(), + {}, + ], +) +def test_delete_self(request_type, transport: str = "grpc"): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # verify fields with default values are dropped - - default_values = getattr( - transport_class._BaseFetchLinkableGitRepositories, - "_BaseFetchLinkableGitRepositories__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["connection"] = "connection_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "pageSize", - "pageToken", - ) - ) - - # verify required fields with non-default values are left alone - assert "connection" in jsonified_request - assert jsonified_request["connection"] == "connection_value" - - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = developer_connect.FetchLinkableGitRepositoriesResponse() - # 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 = developer_connect.FetchLinkableGitRepositoriesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - - response_value._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.fetch_linkable_git_repositories(request) - - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) - - -def test_fetch_linkable_git_repositories_rest_flattened(): - client = DeveloperConnectClient( - 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 = developer_connect.FetchLinkableGitRepositoriesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "connection": "projects/sample1/locations/sample2/connections/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - connection="connection_value", - ) - mock_args.update(sample_request) + # 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 - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = developer_connect.FetchLinkableGitRepositoriesResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.delete_self), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_self(request) - client.fetch_linkable_git_repositories(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.DeleteSelfRequest() + 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/v1/{connection=projects/*/locations/*/connections/*}:fetchLinkableGitRepositories" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_fetch_linkable_git_repositories_rest_flattened_error(transport: str = "rest"): +def test_delete_self_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 = DeveloperConnectClient( 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.fetch_linkable_git_repositories( - developer_connect.FetchLinkableGitRepositoriesRequest(), - connection="connection_value", - ) - - -def test_fetch_linkable_git_repositories_rest_pager(transport: str = "rest"): - client = DeveloperConnectClient( - 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 = developer_connect.DeleteSelfRequest( + name="name_value", ) - # 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 = ( - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - next_page_token="abc", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[], - next_page_token="def", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - ], - next_page_token="ghi", - ), - developer_connect.FetchLinkableGitRepositoriesResponse( - linkable_git_repositories=[ - developer_connect.LinkableGitRepository(), - developer_connect.LinkableGitRepository(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - developer_connect.FetchLinkableGitRepositoriesResponse.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 = { - "connection": "projects/sample1/locations/sample2/connections/sample3" - } - - pager = client.fetch_linkable_git_repositories(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, developer_connect.LinkableGitRepository) for i in results + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_self), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - - pages = list( - client.fetch_linkable_git_repositories(request=sample_request).pages + client.delete_self(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteSelfRequest( + name="name_value", ) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + assert args[0] == request_msg -def test_fetch_git_hub_installations_rest_use_cached_wrapped_rpc(): +def test_delete_self_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -13839,430 +14661,380 @@ def test_fetch_git_hub_installations_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.fetch_git_hub_installations - in client._transport._wrapped_methods - ) + assert client._transport.delete_self 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.fetch_git_hub_installations - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.delete_self] = mock_rpc request = {} - client.fetch_git_hub_installations(request) + client.delete_self(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_git_hub_installations(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.delete_self(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_fetch_git_hub_installations_rest_required_fields( - request_type=developer_connect.FetchGitHubInstallationsRequest, +@pytest.mark.asyncio +async def test_delete_self_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.DeveloperConnectRestTransport - - request_init = {} - request_init["connection"] = "" - 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 = DeveloperConnectAsyncClient( + 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() - default_values = getattr( - transport_class._BaseFetchGitHubInstallations, - "_BaseFetchGitHubInstallations__REQUIRED_FIELDS_DEFAULT_VALUES", + # Ensure method has been cached + assert ( + client._client._transport.delete_self + 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_self + ] = mock_rpc + + request = {} + await client.delete_self(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_self(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", + [ + developer_connect.DeleteSelfRequest(), {}, + ], +) +async def test_delete_self_async(request_type, transport: str = "grpc_asyncio"): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - # verify required fields with default values are now present + # 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 - jsonified_request["connection"] = "connection_value" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_self), "__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_self(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.DeleteSelfRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) - # verify required fields with non-default values are left alone - assert "connection" in jsonified_request - assert jsonified_request["connection"] == "connection_value" +def test_delete_self_field_headers(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = developer_connect.FetchGitHubInstallationsResponse() - # 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 + # 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 = developer_connect.DeleteSelfRequest() - # Convert return value to protobuf type - return_value = developer_connect.FetchGitHubInstallationsResponse.pb( - return_value - ) - 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.delete_self), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_self(request) - response = client.fetch_git_hub_installations(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_fetch_git_hub_installations_rest_flattened(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_delete_self_field_headers_async(): + client = DeveloperConnectAsyncClient( + 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 = developer_connect.FetchGitHubInstallationsResponse() + # 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 = developer_connect.DeleteSelfRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "connection": "projects/sample1/locations/sample2/connections/sample3" - } + request.name = "name_value" - # get truthy value for each flattened field - mock_args = dict( - connection="connection_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_self), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") ) - mock_args.update(sample_request) + await client.delete_self(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 = developer_connect.FetchGitHubInstallationsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.fetch_git_hub_installations(**mock_args) + # 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_self_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_self), "__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_self( + name="name_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/v1/{connection=projects/*/locations/*/connections/*}:fetchGitHubInstallations" - % 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_fetch_git_hub_installations_rest_flattened_error(transport: str = "rest"): +def test_delete_self_flattened_error(): client = DeveloperConnectClient( 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.fetch_git_hub_installations( - developer_connect.FetchGitHubInstallationsRequest(), - connection="connection_value", + client.delete_self( + developer_connect.DeleteSelfRequest(), + name="name_value", ) -def test_fetch_git_refs_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 = DeveloperConnectClient( - 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_delete_self_flattened_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.fetch_git_refs in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_self), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") - # 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( + 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_self( + name="name_value", ) - client._transport._wrapped_methods[client._transport.fetch_git_refs] = mock_rpc - - request = {} - client.fetch_git_refs(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - client.fetch_git_refs(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_fetch_git_refs_rest_required_fields( - request_type=developer_connect.FetchGitRefsRequest, -): - transport_class = transports.DeveloperConnectRestTransport - request_init = {} - request_init["git_repository_link"] = "" - 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) - ) + # 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 - # verify fields with default values are dropped - default_values = getattr( - transport_class._BaseFetchGitRefs, - "_BaseFetchGitRefs__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, +@pytest.mark.asyncio +async def test_delete_self_flattened_error_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["gitRepositoryLink"] = "git_repository_link_value" - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "pageSize", - "pageToken", - "refType", + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_self( + developer_connect.DeleteSelfRequest(), + name="name_value", ) - ) - # verify required fields with non-default values are left alone - assert "gitRepositoryLink" in jsonified_request - assert jsonified_request["gitRepositoryLink"] == "git_repository_link_value" +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.StartOAuthRequest(), + {}, + ], +) +def test_start_o_auth(request_type, transport: str = "grpc"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = developer_connect.FetchGitRefsResponse() - # 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 = developer_connect.FetchGitRefsResponse.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.start_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.StartOAuthResponse( + ticket="ticket_value", + code_challenge="code_challenge_value", + code_challenge_method="code_challenge_method_value", + client_id="client_id_value", + scopes=["scopes_value"], + auth_uri="auth_uri_value", + system_provider_id=developer_connect.SystemProvider.GITHUB, + ) + response = client.start_o_auth(request) - response = client.fetch_git_refs(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.StartOAuthRequest() + 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, developer_connect.StartOAuthResponse) + assert response.ticket == "ticket_value" + assert response.code_challenge == "code_challenge_value" + assert response.code_challenge_method == "code_challenge_method_value" + assert response.client_id == "client_id_value" + assert response.scopes == ["scopes_value"] + assert response.auth_uri == "auth_uri_value" -def test_fetch_git_refs_rest_flattened(): +def test_start_o_auth_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 = DeveloperConnectClient( 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 = developer_connect.FetchGitRefsResponse() + # 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 = developer_connect.StartOAuthRequest( + account_connector="account_connector_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" - } + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.start_o_auth(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.StartOAuthRequest( + account_connector="account_connector_value", + ) + assert args[0] == request_msg - # get truthy value for each flattened field - mock_args = dict( - git_repository_link="git_repository_link_value", - ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, + +def test_start_o_auth_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 = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - 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 = developer_connect.FetchGitRefsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - client.fetch_git_refs(**mock_args) + # Ensure method has been cached + assert client._transport.start_o_auth in client._transport._wrapped_methods - # 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/{git_repository_link=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchGitRefs" - % client.transport._host, - args[1], + # 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_o_auth] = mock_rpc + request = {} + client.start_o_auth(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_fetch_git_refs_rest_flattened_error(transport: str = "rest"): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + client.start_o_auth(request) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.fetch_git_refs( - developer_connect.FetchGitRefsRequest(), - git_repository_link="git_repository_link_value", - ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, - ) + # 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_fetch_git_refs_rest_pager(transport: str = "rest"): - client = DeveloperConnectClient( - 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 = ( - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - str(), - ], - next_page_token="abc", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[], - next_page_token="def", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - ], - next_page_token="ghi", - ), - developer_connect.FetchGitRefsResponse( - ref_names=[ - str(), - str(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - developer_connect.FetchGitRefsResponse.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 = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" - } - - pager = client.fetch_git_refs(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, str) for i in results) - - pages = list(client.fetch_git_refs(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_list_account_connectors_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 = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_start_o_auth_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 = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) # Should wrap all calls on client creation assert wrapper_fn.call_count > 0 @@ -14270,250 +15042,291 @@ def test_list_account_connectors_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_account_connectors - in client._transport._wrapped_methods + client._client._transport.start_o_auth + in client._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_account_connectors + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.start_o_auth ] = mock_rpc request = {} - client.list_account_connectors(request) + await client.start_o_auth(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_account_connectors(request) + await client.start_o_auth(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_account_connectors_rest_required_fields( - request_type=developer_connect.ListAccountConnectorsRequest, -): - transport_class = transports.DeveloperConnectRestTransport - - 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 - - default_values = getattr( - transport_class._BaseListAccountConnectors, - "_BaseListAccountConnectors__REQUIRED_FIELDS_DEFAULT_VALUES", +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.StartOAuthRequest(), {}, + ], +) +async def test_start_o_auth_async(request_type, transport: str = "grpc_asyncio"): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = { - k: v for k, v in default_values.items() if k not in jsonified_request - } - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - jsonified_request["parent"] = "parent_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 - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.StartOAuthResponse( + ticket="ticket_value", + code_challenge="code_challenge_value", + code_challenge_method="code_challenge_method_value", + client_id="client_id_value", + scopes=["scopes_value"], + auth_uri="auth_uri_value", + ) ) - ) + response = await client.start_o_auth(request) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.StartOAuthRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, developer_connect.StartOAuthResponse) + assert response.ticket == "ticket_value" + assert response.code_challenge == "code_challenge_value" + assert response.code_challenge_method == "code_challenge_method_value" + assert response.client_id == "client_id_value" + assert response.scopes == ["scopes_value"] + assert response.auth_uri == "auth_uri_value" + +def test_start_o_auth_field_headers(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = developer_connect.ListAccountConnectorsResponse() - # 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 + # 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 = developer_connect.StartOAuthRequest() - # Convert return value to protobuf type - return_value = developer_connect.ListAccountConnectorsResponse.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) + request.account_connector = "account_connector_value" - response_value._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.start_o_auth), "__call__") as call: + call.return_value = developer_connect.StartOAuthResponse() + client.start_o_auth(request) - response = client.list_account_connectors(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", + "account_connector=account_connector_value", + ) in kw["metadata"] -def test_list_account_connectors_rest_flattened(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", +@pytest.mark.asyncio +async def test_start_o_auth_field_headers_async(): + client = DeveloperConnectAsyncClient( + 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 = developer_connect.ListAccountConnectorsResponse() + # 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 = developer_connect.StartOAuthRequest() - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + request.account_connector = "account_connector_value" - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.StartOAuthResponse() ) - mock_args.update(sample_request) + await client.start_o_auth(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 = developer_connect.ListAccountConnectorsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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.list_account_connectors(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "account_connector=account_connector_value", + ) in kw["metadata"] + + +def test_start_o_auth_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.StartOAuthResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.start_o_auth( + account_connector="account_connector_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/v1/{parent=projects/*/locations/*}/accountConnectors" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].account_connector + mock_val = "account_connector_value" + assert arg == mock_val -def test_list_account_connectors_rest_flattened_error(transport: str = "rest"): +def test_start_o_auth_flattened_error(): client = DeveloperConnectClient( 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_account_connectors( - developer_connect.ListAccountConnectorsRequest(), - parent="parent_value", + client.start_o_auth( + developer_connect.StartOAuthRequest(), + account_connector="account_connector_value", ) -def test_list_account_connectors_rest_pager(transport: str = "rest"): +@pytest.mark.asyncio +async def test_start_o_auth_flattened_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.StartOAuthResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.StartOAuthResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.start_o_auth( + account_connector="account_connector_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].account_connector + mock_val = "account_connector_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_start_o_auth_flattened_error_async(): + client = DeveloperConnectAsyncClient( + 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.start_o_auth( + developer_connect.StartOAuthRequest(), + account_connector="account_connector_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.FinishOAuthRequest(), + {}, + ], +) +def test_finish_o_auth(request_type, transport: str = "grpc"): client = DeveloperConnectClient( 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 = ( - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), - ], - next_page_token="abc", - ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[], - next_page_token="def", - ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - ], - next_page_token="ghi", - ), - developer_connect.ListAccountConnectorsResponse( - account_connectors=[ - developer_connect.AccountConnector(), - developer_connect.AccountConnector(), - ], - ), - ) - # Two responses for two calls - response = response + response + # 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 - # Wrap the values into proper Response objs - response = tuple( - developer_connect.ListAccountConnectorsResponse.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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.FinishOAuthResponse() + response = client.finish_o_auth(request) - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = developer_connect.FinishOAuthRequest() + assert args[0] == request - pager = client.list_account_connectors(request=sample_request) + # Establish that the response is the type that we expect. + assert isinstance(response, developer_connect.FinishOAuthResponse) - 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, developer_connect.AccountConnector) for i in results) +def test_finish_o_auth_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 = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - pages = list(client.list_account_connectors(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # 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 = developer_connect.FinishOAuthRequest( + account_connector="account_connector_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.finish_o_auth(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FinishOAuthRequest( + account_connector="account_connector_value", + ) + assert args[0] == request_msg -def test_get_account_connector_rest_use_cached_wrapped_rpc(): +def test_finish_o_auth_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -14521,169 +15334,249 @@ def test_get_account_connector_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_account_connector - in client._transport._wrapped_methods - ) + assert client._transport.finish_o_auth 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_account_connector] = ( - mock_rpc - ) - + client._transport._wrapped_methods[client._transport.finish_o_auth] = mock_rpc request = {} - client.get_account_connector(request) + client.finish_o_auth(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_account_connector(request) + client.finish_o_auth(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_account_connector_rest_required_fields( - request_type=developer_connect.GetAccountConnectorRequest, +@pytest.mark.asyncio +async def test_finish_o_auth_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.DeveloperConnectRestTransport + # Clients should use _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 = DeveloperConnectAsyncClient( + 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.finish_o_auth + in client._client._transport._wrapped_methods + ) - default_values = getattr( - transport_class._BaseGetAccountConnector, - "_BaseGetAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", - {}, - ) - unset_fields = { - k: v for k, v in default_values.items() if k not in 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.finish_o_auth + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.finish_o_auth(request) - jsonified_request["name"] = "name_value" + # 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.finish_o_auth(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", + [ + developer_connect.FinishOAuthRequest(), + {}, + ], +) +async def test_finish_o_auth_async(request_type, transport: str = "grpc_asyncio"): + client = DeveloperConnectAsyncClient( + 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_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FinishOAuthResponse() + ) + response = await client.finish_o_auth(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = developer_connect.FinishOAuthRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, developer_connect.FinishOAuthResponse) + +def test_finish_o_auth_field_headers(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = developer_connect.AccountConnector() - # 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 + # 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 = developer_connect.FinishOAuthRequest() - response_value = Response() - response_value.status_code = 200 + request.account_connector = "account_connector_value" - # Convert return value to protobuf type - return_value = developer_connect.AccountConnector.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + call.return_value = developer_connect.FinishOAuthResponse() + client.finish_o_auth(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 underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - response = client.get_account_connector(request) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "account_connector=account_connector_value", + ) in kw["metadata"] - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +@pytest.mark.asyncio +async def test_finish_o_auth_field_headers_async(): + client = DeveloperConnectAsyncClient( + 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 = developer_connect.FinishOAuthRequest() -def test_get_account_connector_rest_flattened(): + request.account_connector = "account_connector_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FinishOAuthResponse() + ) + await client.finish_o_auth(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", + "account_connector=account_connector_value", + ) in kw["metadata"] + + +def test_finish_o_auth_flattened(): client = DeveloperConnectClient( 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 = developer_connect.AccountConnector() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.FinishOAuthResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.finish_o_auth( + account_connector="account_connector_value", + ) - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/accountConnectors/sample3" - } + # 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].account_connector + mock_val = "account_connector_value" + assert arg == mock_val - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + +def test_finish_o_auth_flattened_error(): + client = DeveloperConnectClient( + 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_o_auth( + developer_connect.FinishOAuthRequest(), + account_connector="account_connector_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 = developer_connect.AccountConnector.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._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_account_connector(**mock_args) +@pytest.mark.asyncio +async def test_finish_o_auth_flattened_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = developer_connect.FinishOAuthResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FinishOAuthResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.finish_o_auth( + account_connector="account_connector_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/v1/{name=projects/*/locations/*/accountConnectors/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].account_connector + mock_val = "account_connector_value" + assert arg == mock_val -def test_get_account_connector_rest_flattened_error(transport: str = "rest"): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +@pytest.mark.asyncio +async def test_finish_o_auth_flattened_error_async(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_account_connector( - developer_connect.GetAccountConnectorRequest(), - name="name_value", + await client.finish_o_auth( + developer_connect.FinishOAuthRequest(), + account_connector="account_connector_value", ) -def test_create_account_connector_rest_use_cached_wrapped_rpc(): +def test_list_connections_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: @@ -14697,45 +15590,37 @@ def test_create_account_connector_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_account_connector - in client._transport._wrapped_methods - ) + assert client._transport.list_connections 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_account_connector - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_connections] = ( + mock_rpc + ) request = {} - client.create_account_connector(request) + client.list_connections(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_account_connector(request) + client.list_connections(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_account_connector_rest_required_fields( - request_type=developer_connect.CreateAccountConnectorRequest, +def test_list_connections_rest_required_fields( + request_type=developer_connect.ListConnectionsRequest, ): transport_class = transports.DeveloperConnectRestTransport request_init = {} request_init["parent"] = "" - request_init["account_connector_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14743,11 +15628,10 @@ def test_create_account_connector_rest_required_fields( ) # verify fields with default values are dropped - assert "accountConnectorId" not in jsonified_request default_values = getattr( - transport_class._BaseCreateAccountConnector, - "_BaseCreateAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListConnections, + "_BaseListConnections__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -14756,28 +15640,22 @@ def test_create_account_connector_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "accountConnectorId" in jsonified_request - assert ( - jsonified_request["accountConnectorId"] == request_init["account_connector_id"] - ) jsonified_request["parent"] = "parent_value" - jsonified_request["accountConnectorId"] = "account_connector_id_value" # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "accountConnectorId", - "requestId", - "validateOnly", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" - assert "accountConnectorId" in jsonified_request - assert jsonified_request["accountConnectorId"] == "account_connector_id_value" client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14786,7 +15664,7 @@ def test_create_account_connector_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 = developer_connect.ListConnectionsResponse() # 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 @@ -14798,34 +15676,30 @@ def test_create_account_connector_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 = developer_connect.ListConnectionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_account_connector(request) + response = client.list_connections(request) - expected_params = [ - ( - "accountConnectorId", - "", - ), - ("$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_account_connector_rest_flattened(): +def test_list_connections_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14834,7 +15708,7 @@ def test_create_account_connector_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 = operations_pb2.Operation(name="operations/spam") + return_value = developer_connect.ListConnectionsResponse() # get arguments that satisfy an http rule for this method sample_request = {"parent": "projects/sample1/locations/sample2"} @@ -14842,37 +15716,33 @@ def test_create_account_connector_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - account_connector_id="account_connector_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 = developer_connect.ListConnectionsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_account_connector(**mock_args) + client.list_connections(**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/*}/accountConnectors" + "%s/v1/{parent=projects/*/locations/*}/connections" % client.transport._host, args[1], ) -def test_create_account_connector_rest_flattened_error(transport: str = "rest"): +def test_list_connections_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14881,19 +15751,79 @@ def test_create_account_connector_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_account_connector( - developer_connect.CreateAccountConnectorRequest(), + client.list_connections( + developer_connect.ListConnectionsRequest(), parent="parent_value", - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) + ) + + +def test_list_connections_rest_pager(transport: str = "rest"): + client = DeveloperConnectClient( + 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 = ( + developer_connect.ListConnectionsResponse( + connections=[ + developer_connect.Connection(), + developer_connect.Connection(), + developer_connect.Connection(), + ], + next_page_token="abc", ), - account_connector_id="account_connector_id_value", + developer_connect.ListConnectionsResponse( + connections=[], + next_page_token="def", + ), + developer_connect.ListConnectionsResponse( + connections=[ + developer_connect.Connection(), + ], + next_page_token="ghi", + ), + developer_connect.ListConnectionsResponse( + connections=[ + developer_connect.Connection(), + developer_connect.Connection(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + developer_connect.ListConnectionsResponse.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"} -def test_update_account_connector_rest_use_cached_wrapped_rpc(): + pager = client.list_connections(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, developer_connect.Connection) for i in results) + + pages = list(client.list_connections(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_connection_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: @@ -14907,43 +15837,35 @@ def test_update_account_connector_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_account_connector - in client._transport._wrapped_methods - ) + assert client._transport.get_connection 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_account_connector - ] = mock_rpc + client._transport._wrapped_methods[client._transport.get_connection] = mock_rpc request = {} - client.update_account_connector(request) + client.get_connection(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_account_connector(request) + client.get_connection(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_account_connector_rest_required_fields( - request_type=developer_connect.UpdateAccountConnectorRequest, +def test_get_connection_rest_required_fields( + request_type=developer_connect.GetConnectionRequest, ): transport_class = transports.DeveloperConnectRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14953,8 +15875,8 @@ def test_update_account_connector_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseUpdateAccountConnector, - "_BaseUpdateAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetConnection, + "_BaseGetConnection__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -14964,17 +15886,11 @@ def test_update_account_connector_rest_required_fields( # verify required fields with default values are now present - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allowMissing", - "requestId", - "updateMask", - "validateOnly", - ) - ) + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14983,7 +15899,7 @@ def test_update_account_connector_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 = developer_connect.Connection() # 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 @@ -14995,28 +15911,30 @@ def test_update_account_connector_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = developer_connect.Connection.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_account_connector(request) + response = client.get_connection(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_account_connector_rest_flattened(): +def test_get_connection_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15025,48 +15943,43 @@ def test_update_account_connector_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 = operations_pb2.Operation(name="operations/spam") + return_value = developer_connect.Connection() # get arguments that satisfy an http rule for this method sample_request = { - "account_connector": { - "name": "projects/sample1/locations/sample2/accountConnectors/sample3" - } + "name": "projects/sample1/locations/sample2/connections/sample3" } # get truthy value for each flattened field mock_args = dict( - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = developer_connect.Connection.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_account_connector(**mock_args) + client.get_connection(**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/{account_connector.name=projects/*/locations/*/accountConnectors/*}" + "%s/v1/{name=projects/*/locations/*/connections/*}" % client.transport._host, args[1], ) -def test_update_account_connector_rest_flattened_error(transport: str = "rest"): +def test_get_connection_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15075,18 +15988,13 @@ def test_update_account_connector_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_account_connector( - developer_connect.UpdateAccountConnectorRequest(), - account_connector=developer_connect.AccountConnector( - provider_oauth_config=developer_connect.ProviderOAuthConfig( - system_provider_id=developer_connect.SystemProvider.GITHUB - ) - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_connection( + developer_connect.GetConnectionRequest(), + name="name_value", ) -def test_delete_account_connector_rest_use_cached_wrapped_rpc(): +def test_create_connection_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: @@ -15100,22 +16008,19 @@ def test_delete_account_connector_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_account_connector - in client._transport._wrapped_methods - ) + assert client._transport.create_connection 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_account_connector - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_connection] = ( + mock_rpc + ) request = {} - client.delete_account_connector(request) + client.create_connection(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -15124,20 +16029,21 @@ def test_delete_account_connector_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_account_connector(request) + client.create_connection(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_account_connector_rest_required_fields( - request_type=developer_connect.DeleteAccountConnectorRequest, +def test_create_connection_rest_required_fields( + request_type=developer_connect.CreateConnectionRequest, ): transport_class = transports.DeveloperConnectRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["connection_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15145,10 +16051,11 @@ def test_delete_account_connector_rest_required_fields( ) # verify fields with default values are dropped + assert "connectionId" not in jsonified_request default_values = getattr( - transport_class._BaseDeleteAccountConnector, - "_BaseDeleteAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateConnection, + "_BaseCreateConnection__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -15157,22 +16064,26 @@ def test_delete_account_connector_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "connectionId" in jsonified_request + assert jsonified_request["connectionId"] == request_init["connection_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["connectionId"] = "connection_id_value" # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "etag", - "force", + "connectionId", "requestId", "validateOnly", ) ) # 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 "connectionId" in jsonified_request + assert jsonified_request["connectionId"] == "connection_id_value" client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15193,9 +16104,10 @@ def test_delete_account_connector_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() @@ -15206,14 +16118,20 @@ def test_delete_account_connector_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_account_connector(request) + response = client.create_connection(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "connectionId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_account_connector_rest_flattened(): +def test_create_connection_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15225,13 +16143,17 @@ def test_delete_account_connector_rest_flattened(): 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/accountConnectors/sample3" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + connection=developer_connect.Connection( + github_config=developer_connect.GitHubConfig( + github_app=developer_connect.GitHubConfig.GitHubApp.DEVELOPER_CONNECT + ) + ), + connection_id="connection_id_value", ) mock_args.update(sample_request) @@ -15243,20 +16165,20 @@ def test_delete_account_connector_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_account_connector(**mock_args) + client.create_connection(**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/*/accountConnectors/*}" + "%s/v1/{parent=projects/*/locations/*}/connections" % client.transport._host, args[1], ) -def test_delete_account_connector_rest_flattened_error(transport: str = "rest"): +def test_create_connection_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15265,13 +16187,19 @@ def test_delete_account_connector_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_account_connector( - developer_connect.DeleteAccountConnectorRequest(), - name="name_value", + client.create_connection( + developer_connect.CreateConnectionRequest(), + parent="parent_value", + connection=developer_connect.Connection( + github_config=developer_connect.GitHubConfig( + github_app=developer_connect.GitHubConfig.GitHubApp.DEVELOPER_CONNECT + ) + ), + connection_id="connection_id_value", ) -def test_fetch_access_token_rest_use_cached_wrapped_rpc(): +def test_update_connection_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: @@ -15285,39 +16213,40 @@ def test_fetch_access_token_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.fetch_access_token in client._transport._wrapped_methods - ) + assert client._transport.update_connection 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.fetch_access_token] = ( + client._transport._wrapped_methods[client._transport.update_connection] = ( mock_rpc ) request = {} - client.fetch_access_token(request) + client.update_connection(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_access_token(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_connection(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_fetch_access_token_rest_required_fields( - request_type=developer_connect.FetchAccessTokenRequest, +def test_update_connection_rest_required_fields( + request_type=developer_connect.UpdateConnectionRequest, ): transport_class = transports.DeveloperConnectRestTransport request_init = {} - request_init["account_connector"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15327,8 +16256,8 @@ def test_fetch_access_token_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseFetchAccessToken, - "_BaseFetchAccessToken__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseUpdateConnection, + "_BaseUpdateConnection__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -15338,11 +16267,17 @@ def test_fetch_access_token_rest_required_fields( # verify required fields with default values are now present - jsonified_request["accountConnector"] = "account_connector_value" + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allowMissing", + "requestId", + "updateMask", + "validateOnly", + ) + ) # verify required fields with non-default values are left alone - assert "accountConnector" in jsonified_request - assert jsonified_request["accountConnector"] == "account_connector_value" client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15351,7 +16286,7 @@ def test_fetch_access_token_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = developer_connect.FetchAccessTokenResponse() + 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 @@ -15363,7 +16298,7 @@ def test_fetch_access_token_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -15371,23 +16306,20 @@ def test_fetch_access_token_rest_required_fields( response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = developer_connect.FetchAccessTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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.fetch_access_token(request) + response = client.update_connection(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_fetch_access_token_rest_flattened(): +def test_update_connection_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15396,43 +16328,48 @@ def test_fetch_access_token_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 = developer_connect.FetchAccessTokenResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "account_connector": "projects/sample1/locations/sample2/accountConnectors/sample3" + "connection": { + "name": "projects/sample1/locations/sample2/connections/sample3" + } } # get truthy value for each flattened field mock_args = dict( - account_connector="account_connector_value", + connection=developer_connect.Connection( + github_config=developer_connect.GitHubConfig( + github_app=developer_connect.GitHubConfig.GitHubApp.DEVELOPER_CONNECT + ) + ), + 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 - # Convert return value to protobuf type - return_value = developer_connect.FetchAccessTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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.fetch_access_token(**mock_args) + client.update_connection(**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/{account_connector=projects/*/locations/*/accountConnectors/*}/users:fetchAccessToken" + "%s/v1/{connection.name=projects/*/locations/*/connections/*}" % client.transport._host, args[1], ) -def test_fetch_access_token_rest_flattened_error(transport: str = "rest"): +def test_update_connection_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15441,13 +16378,18 @@ def test_fetch_access_token_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.fetch_access_token( - developer_connect.FetchAccessTokenRequest(), - account_connector="account_connector_value", + client.update_connection( + developer_connect.UpdateConnectionRequest(), + connection=developer_connect.Connection( + github_config=developer_connect.GitHubConfig( + github_app=developer_connect.GitHubConfig.GitHubApp.DEVELOPER_CONNECT + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_list_users_rest_use_cached_wrapped_rpc(): +def test_delete_connection_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: @@ -15461,35 +16403,41 @@ def test_list_users_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_users in client._transport._wrapped_methods + assert client._transport.delete_connection 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_users] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_connection] = ( + mock_rpc + ) request = {} - client.list_users(request) + client.delete_connection(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_users(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_connection(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_users_rest_required_fields( - request_type=developer_connect.ListUsersRequest, +def test_delete_connection_rest_required_fields( + request_type=developer_connect.DeleteConnectionRequest, ): transport_class = transports.DeveloperConnectRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15499,8 +16447,8 @@ def test_list_users_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseListUsers, - "_BaseListUsers__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteConnection, + "_BaseDeleteConnection__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -15510,21 +16458,20 @@ def test_list_users_rest_required_fields( # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "etag", + "requestId", + "validateOnly", ) ) # 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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15533,7 +16480,7 @@ def test_list_users_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = developer_connect.ListUsersResponse() + 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 @@ -15545,30 +16492,27 @@ def test_list_users_rest_required_fields( 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 response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = developer_connect.ListUsersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_users(request) + response = client.delete_connection(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_users_rest_flattened(): +def test_delete_connection_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15577,43 +16521,41 @@ def test_list_users_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 = developer_connect.ListUsersResponse() + 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/accountConnectors/sample3" + "name": "projects/sample1/locations/sample2/connections/sample3" } # get truthy value for each flattened field mock_args = dict( - parent="parent_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 = developer_connect.ListUsersResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_users(**mock_args) + client.delete_connection(**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/*/accountConnectors/*}/users" + "%s/v1/{name=projects/*/locations/*/connections/*}" % client.transport._host, args[1], ) -def test_list_users_rest_flattened_error(transport: str = "rest"): +def test_delete_connection_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15622,105 +16564,42 @@ def test_list_users_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_users( - developer_connect.ListUsersRequest(), - parent="parent_value", + client.delete_connection( + developer_connect.DeleteConnectionRequest(), + name="name_value", ) -def test_list_users_rest_pager(transport: str = "rest"): - client = DeveloperConnectClient( - 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 = ( - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - developer_connect.User(), - ], - next_page_token="abc", - ), - developer_connect.ListUsersResponse( - users=[], - next_page_token="def", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - ], - next_page_token="ghi", - ), - developer_connect.ListUsersResponse( - users=[ - developer_connect.User(), - developer_connect.User(), - ], - ), +def test_create_git_repository_link_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 = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Two responses for two calls - response = response + response - # Wrap the values into proper Response objs - response = tuple( - developer_connect.ListUsersResponse.to_json(x) for x in response + # 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_git_repository_link + in client._transport._wrapped_methods ) - 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/accountConnectors/sample3" - } - - pager = client.list_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, developer_connect.User) for i in results) - - pages = list(client.list_users(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_delete_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 = DeveloperConnectClient( - 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_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_user] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_git_repository_link + ] = mock_rpc request = {} - client.delete_user(request) + client.create_git_repository_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -15729,20 +16608,21 @@ def test_delete_user_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_user(request) + client.create_git_repository_link(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_user_rest_required_fields( - request_type=developer_connect.DeleteUserRequest, +def test_create_git_repository_link_rest_required_fields( + request_type=developer_connect.CreateGitRepositoryLinkRequest, ): transport_class = transports.DeveloperConnectRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["git_repository_link_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15750,10 +16630,11 @@ def test_delete_user_rest_required_fields( ) # verify fields with default values are dropped + assert "gitRepositoryLinkId" not in jsonified_request default_values = getattr( - transport_class._BaseDeleteUser, - "_BaseDeleteUser__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseCreateGitRepositoryLink, + "_BaseCreateGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -15762,21 +16643,29 @@ def test_delete_user_rest_required_fields( jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "gitRepositoryLinkId" in jsonified_request + assert ( + jsonified_request["gitRepositoryLinkId"] + == request_init["git_repository_link_id"] + ) - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["gitRepositoryLinkId"] = "git_repository_link_id_value" # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "etag", + "gitRepositoryLinkId", "requestId", "validateOnly", ) ) # 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 "gitRepositoryLinkId" in jsonified_request + assert jsonified_request["gitRepositoryLinkId"] == "git_repository_link_id_value" client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15797,9 +16686,10 @@ def test_delete_user_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() @@ -15810,14 +16700,20 @@ def test_delete_user_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_user(request) + response = client.create_git_repository_link(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "gitRepositoryLinkId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_user_rest_flattened(): +def test_create_git_repository_link_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15830,12 +16726,14 @@ def test_delete_user_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/accountConnectors/sample3/users/sample4" + "parent": "projects/sample1/locations/sample2/connections/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + git_repository_link=developer_connect.GitRepositoryLink(name="name_value"), + git_repository_link_id="git_repository_link_id_value", ) mock_args.update(sample_request) @@ -15847,20 +16745,20 @@ def test_delete_user_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_user(**mock_args) + client.create_git_repository_link(**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/*/accountConnectors/*/users/*}" + "%s/v1/{parent=projects/*/locations/*/connections/*}/gitRepositoryLinks" % client.transport._host, args[1], ) -def test_delete_user_rest_flattened_error(transport: str = "rest"): +def test_create_git_repository_link_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15869,13 +16767,15 @@ def test_delete_user_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_user( - developer_connect.DeleteUserRequest(), - name="name_value", + client.create_git_repository_link( + developer_connect.CreateGitRepositoryLinkRequest(), + parent="parent_value", + git_repository_link=developer_connect.GitRepositoryLink(name="name_value"), + git_repository_link_id="git_repository_link_id_value", ) -def test_fetch_self_rest_use_cached_wrapped_rpc(): +def test_delete_git_repository_link_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: @@ -15889,30 +16789,39 @@ def test_fetch_self_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.fetch_self in client._transport._wrapped_methods + assert ( + client._transport.delete_git_repository_link + 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.fetch_self] = mock_rpc + client._transport._wrapped_methods[ + client._transport.delete_git_repository_link + ] = mock_rpc request = {} - client.fetch_self(request) + client.delete_git_repository_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.fetch_self(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_git_repository_link(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_fetch_self_rest_required_fields( - request_type=developer_connect.FetchSelfRequest, +def test_delete_git_repository_link_rest_required_fields( + request_type=developer_connect.DeleteGitRepositoryLinkRequest, ): transport_class = transports.DeveloperConnectRestTransport @@ -15927,8 +16836,8 @@ def test_fetch_self_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseFetchSelf, - "_BaseFetchSelf__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseDeleteGitRepositoryLink, + "_BaseDeleteGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -15940,6 +16849,15 @@ def test_fetch_self_rest_required_fields( jsonified_request["name"] = "name_value" + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "requestId", + "validateOnly", + ) + ) + # verify required fields with non-default values are left alone assert "name" in jsonified_request assert jsonified_request["name"] == "name_value" @@ -15951,7 +16869,7 @@ def test_fetch_self_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = developer_connect.User() + 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 @@ -15963,30 +16881,27 @@ def test_fetch_self_rest_required_fields( 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 response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = developer_connect.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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.fetch_self(request) + response = client.delete_git_repository_link(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_fetch_self_rest_flattened(): +def test_delete_git_repository_link_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15995,11 +16910,11 @@ def test_fetch_self_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 = developer_connect.User() + 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/accountConnectors/sample3" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" } # get truthy value for each flattened field @@ -16011,27 +16926,25 @@ def test_fetch_self_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = developer_connect.User.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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.fetch_self(**mock_args) + client.delete_git_repository_link(**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/*/accountConnectors/*}/users:fetchSelf" + "%s/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}" % client.transport._host, args[1], ) -def test_fetch_self_rest_flattened_error(transport: str = "rest"): +def test_delete_git_repository_link_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16040,13 +16953,13 @@ def test_fetch_self_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.fetch_self( - developer_connect.FetchSelfRequest(), + client.delete_git_repository_link( + developer_connect.DeleteGitRepositoryLinkRequest(), name="name_value", ) -def test_delete_self_rest_use_cached_wrapped_rpc(): +def test_list_git_repository_links_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: @@ -16060,39 +16973,40 @@ def test_delete_self_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_self in client._transport._wrapped_methods + assert ( + client._transport.list_git_repository_links + 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_self] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_git_repository_links + ] = mock_rpc request = {} - client.delete_self(request) + client.list_git_repository_links(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_self(request) + client.list_git_repository_links(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_self_rest_required_fields( - request_type=developer_connect.DeleteSelfRequest, +def test_list_git_repository_links_rest_required_fields( + request_type=developer_connect.ListGitRepositoryLinksRequest, ): transport_class = transports.DeveloperConnectRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16102,8 +17016,8 @@ def test_delete_self_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseDeleteSelf, - "_BaseDeleteSelf__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseListGitRepositoryLinks, + "_BaseListGitRepositoryLinks__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -16113,11 +17027,21 @@ def test_delete_self_rest_required_fields( # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) # 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" client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16126,7 +17050,7 @@ def test_delete_self_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 = developer_connect.ListGitRepositoryLinksResponse() # 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 @@ -16138,27 +17062,32 @@ def test_delete_self_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "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 = developer_connect.ListGitRepositoryLinksResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._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_self(request) + response = client.list_git_repository_links(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_self_rest_flattened(): +def test_list_git_repository_links_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16167,41 +17096,43 @@ def test_delete_self_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 = operations_pb2.Operation(name="operations/spam") + return_value = developer_connect.ListGitRepositoryLinksResponse() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/accountConnectors/sample3" + "parent": "projects/sample1/locations/sample2/connections/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + 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 = developer_connect.ListGitRepositoryLinksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_self(**mock_args) + client.list_git_repository_links(**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/*/accountConnectors/*}/users:deleteSelf" + "%s/v1/{parent=projects/*/locations/*/connections/*}/gitRepositoryLinks" % client.transport._host, args[1], ) -def test_delete_self_rest_flattened_error(transport: str = "rest"): +def test_list_git_repository_links_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16210,55 +17141,129 @@ def test_delete_self_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_self( - developer_connect.DeleteSelfRequest(), - name="name_value", + client.list_git_repository_links( + developer_connect.ListGitRepositoryLinksRequest(), + parent="parent_value", ) -def test_start_o_auth_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 = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation +def test_list_git_repository_links_rest_pager(transport: str = "rest"): + client = DeveloperConnectClient( + 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 = ( + developer_connect.ListGitRepositoryLinksResponse( + git_repository_links=[ + developer_connect.GitRepositoryLink(), + developer_connect.GitRepositoryLink(), + developer_connect.GitRepositoryLink(), + ], + next_page_token="abc", + ), + developer_connect.ListGitRepositoryLinksResponse( + git_repository_links=[], + next_page_token="def", + ), + developer_connect.ListGitRepositoryLinksResponse( + git_repository_links=[ + developer_connect.GitRepositoryLink(), + ], + next_page_token="ghi", + ), + developer_connect.ListGitRepositoryLinksResponse( + git_repository_links=[ + developer_connect.GitRepositoryLink(), + developer_connect.GitRepositoryLink(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + developer_connect.ListGitRepositoryLinksResponse.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/connections/sample3" + } + + pager = client.list_git_repository_links(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, developer_connect.GitRepositoryLink) for i in results) + + pages = list(client.list_git_repository_links(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_git_repository_link_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 = DeveloperConnectClient( + 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_o_auth in client._transport._wrapped_methods + assert ( + client._transport.get_git_repository_link + 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_o_auth] = mock_rpc + client._transport._wrapped_methods[ + client._transport.get_git_repository_link + ] = mock_rpc request = {} - client.start_o_auth(request) + client.get_git_repository_link(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.start_o_auth(request) + client.get_git_repository_link(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_o_auth_rest_required_fields( - request_type=developer_connect.StartOAuthRequest, +def test_get_git_repository_link_rest_required_fields( + request_type=developer_connect.GetGitRepositoryLinkRequest, ): transport_class = transports.DeveloperConnectRestTransport request_init = {} - request_init["account_connector"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16268,8 +17273,8 @@ def test_start_o_auth_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseStartOAuth, - "_BaseStartOAuth__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseGetGitRepositoryLink, + "_BaseGetGitRepositoryLink__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -16279,11 +17284,11 @@ def test_start_o_auth_rest_required_fields( # verify required fields with default values are now present - jsonified_request["accountConnector"] = "account_connector_value" + jsonified_request["name"] = "name_value" # verify required fields with non-default values are left alone - assert "accountConnector" in jsonified_request - assert jsonified_request["accountConnector"] == "account_connector_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16292,7 +17297,7 @@ def test_start_o_auth_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = developer_connect.StartOAuthResponse() + return_value = developer_connect.GitRepositoryLink() # 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 @@ -16313,21 +17318,21 @@ def test_start_o_auth_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.StartOAuthResponse.pb(return_value) + return_value = developer_connect.GitRepositoryLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_o_auth(request) + response = client.get_git_repository_link(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_o_auth_rest_flattened(): +def test_get_git_repository_link_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16336,16 +17341,16 @@ def test_start_o_auth_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 = developer_connect.StartOAuthResponse() + return_value = developer_connect.GitRepositoryLink() # get arguments that satisfy an http rule for this method sample_request = { - "account_connector": "projects/sample1/locations/sample2/accountConnectors/sample3" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" } # get truthy value for each flattened field mock_args = dict( - account_connector="account_connector_value", + name="name_value", ) mock_args.update(sample_request) @@ -16353,26 +17358,26 @@ def test_start_o_auth_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.StartOAuthResponse.pb(return_value) + return_value = developer_connect.GitRepositoryLink.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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.start_o_auth(**mock_args) + client.get_git_repository_link(**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/{account_connector=projects/*/locations/*/accountConnectors/*}/users:startOAuthFlow" + "%s/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}" % client.transport._host, args[1], ) -def test_start_o_auth_rest_flattened_error(transport: str = "rest"): +def test_get_git_repository_link_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16381,13 +17386,13 @@ def test_start_o_auth_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.start_o_auth( - developer_connect.StartOAuthRequest(), - account_connector="account_connector_value", + client.get_git_repository_link( + developer_connect.GetGitRepositoryLinkRequest(), + name="name_value", ) -def test_finish_o_auth_rest_use_cached_wrapped_rpc(): +def test_fetch_read_write_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: @@ -16401,35 +17406,40 @@ def test_finish_o_auth_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.finish_o_auth in client._transport._wrapped_methods + assert ( + client._transport.fetch_read_write_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.finish_o_auth] = mock_rpc + client._transport._wrapped_methods[client._transport.fetch_read_write_token] = ( + mock_rpc + ) request = {} - client.finish_o_auth(request) + client.fetch_read_write_token(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.finish_o_auth(request) + client.fetch_read_write_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_finish_o_auth_rest_required_fields( - request_type=developer_connect.FinishOAuthRequest, +def test_fetch_read_write_token_rest_required_fields( + request_type=developer_connect.FetchReadWriteTokenRequest, ): transport_class = transports.DeveloperConnectRestTransport request_init = {} - request_init["account_connector"] = "" + request_init["git_repository_link"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16439,8 +17449,8 @@ def test_finish_o_auth_rest_required_fields( # verify fields with default values are dropped default_values = getattr( - transport_class._BaseFinishOAuth, - "_BaseFinishOAuth__REQUIRED_FIELDS_DEFAULT_VALUES", + transport_class._BaseFetchReadWriteToken, + "_BaseFetchReadWriteToken__REQUIRED_FIELDS_DEFAULT_VALUES", {}, ) unset_fields = { @@ -16450,19 +17460,11 @@ def test_finish_o_auth_rest_required_fields( # verify required fields with default values are now present - jsonified_request["accountConnector"] = "account_connector_value" - - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "googleOauthParams", - "oauthParams", - ) - ) + jsonified_request["gitRepositoryLink"] = "git_repository_link_value" # verify required fields with non-default values are left alone - assert "accountConnector" in jsonified_request - assert jsonified_request["accountConnector"] == "account_connector_value" + assert "gitRepositoryLink" in jsonified_request + assert jsonified_request["gitRepositoryLink"] == "git_repository_link_value" client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16471,7 +17473,7 @@ def test_finish_o_auth_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = developer_connect.FinishOAuthResponse() + return_value = developer_connect.FetchReadWriteTokenResponse() # 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 @@ -16483,30 +17485,33 @@ def test_finish_o_auth_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 = developer_connect.FinishOAuthResponse.pb(return_value) + return_value = developer_connect.FetchReadWriteTokenResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value._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_o_auth(request) + response = client.fetch_read_write_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_finish_o_auth_rest_flattened(): +def test_fetch_read_write_token_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16515,16 +17520,16 @@ def test_finish_o_auth_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 = developer_connect.FinishOAuthResponse() + return_value = developer_connect.FetchReadWriteTokenResponse() # get arguments that satisfy an http rule for this method sample_request = { - "account_connector": "projects/sample1/locations/sample2/accountConnectors/sample3" + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" } # get truthy value for each flattened field mock_args = dict( - account_connector="account_connector_value", + git_repository_link="git_repository_link_value", ) mock_args.update(sample_request) @@ -16532,26 +17537,26 @@ def test_finish_o_auth_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.FinishOAuthResponse.pb(return_value) + return_value = developer_connect.FetchReadWriteTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._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_o_auth(**mock_args) + client.fetch_read_write_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/v1/{account_connector=projects/*/locations/*/accountConnectors/*}/users:finishOAuthFlow" + "%s/v1/{git_repository_link=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchReadWriteToken" % client.transport._host, args[1], ) -def test_finish_o_auth_rest_flattened_error(transport: str = "rest"): +def test_fetch_read_write_token_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16560,1409 +17565,8844 @@ def test_finish_o_auth_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.finish_o_auth( - developer_connect.FinishOAuthRequest(), - account_connector="account_connector_value", + client.fetch_read_write_token( + developer_connect.FetchReadWriteTokenRequest(), + git_repository_link="git_repository_link_value", ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DeveloperConnectGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): +def test_fetch_read_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 = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.DeveloperConnectGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeveloperConnectClient( - 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.DeveloperConnectGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DeveloperConnectClient( - client_options=options, - transport=transport, - ) + # Ensure method has been cached + assert client._transport.fetch_read_token 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 = DeveloperConnectClient( - 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.DeveloperConnectGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = DeveloperConnectClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client._transport._wrapped_methods[client._transport.fetch_read_token] = ( + mock_rpc ) + request = {} + client.fetch_read_token(request) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DeveloperConnectGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = DeveloperConnectClient(transport=transport) - assert client.transport is transport + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.fetch_read_token(request) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DeveloperConnectGrpcTransport( - 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 - transport = transports.DeveloperConnectGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel +def test_fetch_read_token_rest_required_fields( + request_type=developer_connect.FetchReadTokenRequest, +): + transport_class = transports.DeveloperConnectRestTransport -@pytest.mark.parametrize( - "transport_class", - [ - transports.DeveloperConnectGrpcTransport, - transports.DeveloperConnectGrpcAsyncIOTransport, - transports.DeveloperConnectRestTransport, - ], -) -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_init = {} + request_init["git_repository_link"] = "" + 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 -def test_transport_kind_grpc(): - transport = DeveloperConnectClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() + default_values = getattr( + transport_class._BaseFetchReadToken, + "_BaseFetchReadToken__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) - assert transport.kind == "grpc" + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -def test_initialize_client_w_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + jsonified_request["gitRepositoryLink"] = "git_repository_link_value" + # verify required fields with non-default values are left alone + assert "gitRepositoryLink" in jsonified_request + assert jsonified_request["gitRepositoryLink"] == "git_repository_link_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_connections_empty_call_grpc(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_connections), "__call__") as call: - call.return_value = developer_connect.ListConnectionsResponse() - client.list_connections(request=None) + # Designate an appropriate value for the returned response. + return_value = developer_connect.FetchReadTokenResponse() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListConnectionsRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.FetchReadTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_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_get_connection_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._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, and fake the request. - with mock.patch.object(type(client.transport.get_connection), "__call__") as call: - call.return_value = developer_connect.Connection() - client.get_connection(request=None) + response = client.fetch_read_token(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.GetConnectionRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_connection_empty_call_grpc(): +def test_fetch_read_token_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_connection), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_connection(request=None) + # 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 = developer_connect.FetchReadTokenResponse() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.CreateConnectionRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + # get truthy value for each flattened field + mock_args = dict( + git_repository_link="git_repository_link_value", + ) + mock_args.update(sample_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_update_connection_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.FetchReadTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.update_connection), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_connection(request=None) + client.fetch_read_token(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.UpdateConnectionRequest() - assert args[0] == request_msg + # 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/{git_repository_link=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchReadToken" + % client.transport._host, + args[1], + ) -# 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_connection_empty_call_grpc(): +def test_fetch_read_token_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_connection), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_connection(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_read_token( + developer_connect.FetchReadTokenRequest(), + git_repository_link="git_repository_link_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteConnectionRequest() - assert args[0] == request_msg +def test_open_git_repository_link_pull_request_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 = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="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_create_git_repository_link_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_git_repository_link), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_git_repository_link(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.CreateGitRepositoryLinkRequest() - assert args[0] == request_msg + # Ensure method has been cached + assert ( + client._transport.open_git_repository_link_pull_request + 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.open_git_repository_link_pull_request + ] = mock_rpc -# 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_git_repository_link_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request = {} + client.open_git_repository_link_pull_request(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_git_repository_link), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_git_repository_link(request=None) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteGitRepositoryLinkRequest() - assert args[0] == request_msg + client.open_git_repository_link_pull_request(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. -def test_list_git_repository_links_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_git_repository_links), "__call__" - ) as call: - call.return_value = developer_connect.ListGitRepositoryLinksResponse() - client.list_git_repository_links(request=None) +def test_open_git_repository_link_pull_request_rest_required_fields( + request_type=developer_connect.OpenGitRepositoryLinkPullRequestRequest, +): + transport_class = transports.DeveloperConnectRestTransport - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListGitRepositoryLinksRequest() - assert args[0] == request_msg + 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 -# 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_git_repository_link_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + default_values = getattr( + transport_class._BaseOpenGitRepositoryLinkPullRequest, + "_BaseOpenGitRepositoryLinkPullRequest__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_git_repository_link), "__call__" - ) as call: - call.return_value = developer_connect.GitRepositoryLink() - client.get_git_repository_link(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.GetGitRepositoryLinkRequest() - assert args[0] == request_msg + jsonified_request["name"] = "name_value" + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["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. -def test_fetch_read_write_token_empty_call_grpc(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_read_write_token), "__call__" - ) as call: - call.return_value = developer_connect.FetchReadWriteTokenResponse() - client.fetch_read_write_token(request=None) + # Designate an appropriate value for the returned response. + return_value = developer_connect.PullRequest() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchReadWriteTokenRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.PullRequest.pb(return_value) + json_return_value = json_format.MessageToJson(return_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_fetch_read_token_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._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, and fake the request. - with mock.patch.object(type(client.transport.fetch_read_token), "__call__") as call: - call.return_value = developer_connect.FetchReadTokenResponse() - client.fetch_read_token(request=None) + response = client.open_git_repository_link_pull_request(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchReadTokenRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_fetch_linkable_git_repositories_empty_call_grpc(): +def test_open_git_repository_link_pull_request_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), "__call__" - ) as call: - call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() - client.fetch_linkable_git_repositories(request=None) + # 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 = developer_connect.PullRequest() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchLinkableGitRepositoriesRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + pull_request=developer_connect.PullRequest(id="id_value"), + ) + mock_args.update(sample_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_fetch_git_hub_installations_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.PullRequest.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.fetch_git_hub_installations), "__call__" - ) as call: - call.return_value = developer_connect.FetchGitHubInstallationsResponse() - client.fetch_git_hub_installations(request=None) + client.open_git_repository_link_pull_request(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchGitHubInstallationsRequest() - assert args[0] == request_msg + # 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/*/connections/*/gitRepositoryLinks/*}:openPullRequest" + % client.transport._host, + args[1], + ) -# 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_fetch_git_refs_empty_call_grpc(): +def test_open_git_repository_link_pull_request_rest_flattened_error( + transport: str = "rest", +): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: - call.return_value = developer_connect.FetchGitRefsResponse() - client.fetch_git_refs(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.open_git_repository_link_pull_request( + developer_connect.OpenGitRepositoryLinkPullRequestRequest(), + name="name_value", + pull_request=developer_connect.PullRequest(id="id_value"), + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchGitRefsRequest() - assert args[0] == request_msg +def test_fetch_linkable_git_repositories_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 = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="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_list_account_connectors_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_account_connectors), "__call__" - ) as call: - call.return_value = developer_connect.ListAccountConnectorsResponse() - client.list_account_connectors(request=None) + # Ensure method has been cached + assert ( + client._transport.fetch_linkable_git_repositories + in client._transport._wrapped_methods + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListAccountConnectorsRequest() - assert args[0] == request_msg + # 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.fetch_linkable_git_repositories + ] = mock_rpc + request = {} + client.fetch_linkable_git_repositories(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_get_account_connector_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account_connector), "__call__" - ) as call: - call.return_value = developer_connect.AccountConnector() - client.get_account_connector(request=None) + client.fetch_linkable_git_repositories(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.GetAccountConnectorRequest() - assert args[0] == request_msg + # 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. -def test_create_account_connector_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +def test_fetch_linkable_git_repositories_rest_required_fields( + request_type=developer_connect.FetchLinkableGitRepositoriesRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["connection"] = "" + 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 actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_account_connector), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_account_connector(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.CreateAccountConnectorRequest() - assert args[0] == request_msg + default_values = getattr( + transport_class._BaseFetchLinkableGitRepositories, + "_BaseFetchLinkableGitRepositories__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present + + jsonified_request["connection"] = "connection_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "connection" in jsonified_request + assert jsonified_request["connection"] == "connection_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_update_account_connector_empty_call_grpc(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account_connector), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_account_connector(request=None) + # Designate an appropriate value for the returned response. + return_value = developer_connect.FetchLinkableGitRepositoriesResponse() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.UpdateAccountConnectorRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.FetchLinkableGitRepositoriesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_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_delete_account_connector_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.delete_account_connector), "__call__" - ) as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_account_connector(request=None) + response = client.fetch_linkable_git_repositories(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteAccountConnectorRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_fetch_access_token_empty_call_grpc(): +def test_fetch_linkable_git_repositories_rest_flattened(): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_access_token), "__call__" - ) as call: - call.return_value = developer_connect.FetchAccessTokenResponse() - client.fetch_access_token(request=None) + # 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 = developer_connect.FetchLinkableGitRepositoriesResponse() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchAccessTokenRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "connection": "projects/sample1/locations/sample2/connections/sample3" + } + # get truthy value for each flattened field + mock_args = dict( + connection="connection_value", + ) + mock_args.update(sample_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_list_users_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.FetchLinkableGitRepositoriesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - call.return_value = developer_connect.ListUsersResponse() - client.list_users(request=None) + client.fetch_linkable_git_repositories(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListUsersRequest() - assert args[0] == request_msg + # 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/{connection=projects/*/locations/*/connections/*}:fetchLinkableGitRepositories" + % client.transport._host, + args[1], + ) -# 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_user_empty_call_grpc(): +def test_fetch_linkable_git_repositories_rest_flattened_error(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_user(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteUserRequest() - assert args[0] == request_msg + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_linkable_git_repositories( + developer_connect.FetchLinkableGitRepositoriesRequest(), + connection="connection_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_fetch_self_empty_call_grpc(): +def test_fetch_linkable_git_repositories_rest_pager(transport: str = "rest"): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: - call.return_value = developer_connect.User() - client.fetch_self(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchSelfRequest() - assert args[0] == request_msg + # 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 = ( + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + next_page_token="abc", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[], + next_page_token="def", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + ], + next_page_token="ghi", + ), + developer_connect.FetchLinkableGitRepositoriesResponse( + linkable_git_repositories=[ + developer_connect.LinkableGitRepository(), + developer_connect.LinkableGitRepository(), + ], + ), + ) + # Two responses for two calls + response = response + response + # Wrap the values into proper Response objs + response = tuple( + developer_connect.FetchLinkableGitRepositoriesResponse.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 -# 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_self_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + sample_request = { + "connection": "projects/sample1/locations/sample2/connections/sample3" + } - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_self), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_self(request=None) + pager = client.fetch_linkable_git_repositories(request=sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteSelfRequest() - assert args[0] == request_msg + 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, developer_connect.LinkableGitRepository) for i in results + ) -# 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_o_auth_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + pages = list( + client.fetch_linkable_git_repositories(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, and fake the request. - with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: - call.return_value = developer_connect.StartOAuthResponse() - client.start_o_auth(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.StartOAuthRequest() - assert args[0] == request_msg +def test_fetch_git_hub_installations_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 = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# 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_o_auth_empty_call_grpc(): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + # Ensure method has been cached + assert ( + client._transport.fetch_git_hub_installations + in client._transport._wrapped_methods + ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: - call.return_value = developer_connect.FinishOAuthResponse() - client.finish_o_auth(request=None) + # 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.fetch_git_hub_installations + ] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FinishOAuthRequest() - assert args[0] == request_msg + request = {} + client.fetch_git_hub_installations(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_transport_kind_grpc_asyncio(): - transport = DeveloperConnectAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" + client.fetch_git_hub_installations(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_initialize_client_w_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None +def test_fetch_git_hub_installations_rest_required_fields( + request_type=developer_connect.FetchGitHubInstallationsRequest, +): + transport_class = transports.DeveloperConnectRestTransport -# 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_connections_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["connection"] = "" + 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 actual call, and fake the request. - with mock.patch.object(type(client.transport.list_connections), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListConnectionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_connections(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListConnectionsRequest() - assert args[0] == request_msg - + # verify fields with default values are dropped -# 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_connection_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + default_values = getattr( + transport_class._BaseFetchGitHubInstallations, + "_BaseFetchGitHubInstallations__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_connection), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.Connection( - name="name_value", - disabled=True, - reconciling=True, - etag="etag_value", - uid="uid_value", - ) - ) - await client.get_connection(request=None) + # verify required fields with default values are now present - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.GetConnectionRequest() - assert args[0] == request_msg + jsonified_request["connection"] = "connection_value" + # verify required fields with non-default values are left alone + assert "connection" in jsonified_request + assert jsonified_request["connection"] == "connection_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_create_connection_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_connection), "__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_connection(request=None) + # Designate an appropriate value for the returned response. + return_value = developer_connect.FetchGitHubInstallationsResponse() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.CreateConnectionRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.FetchGitHubInstallationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_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_update_connection_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.update_connection), "__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_connection(request=None) + response = client.fetch_git_hub_installations(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.UpdateConnectionRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_connection_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_fetch_git_hub_installations_rest_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_connection), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # 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 = developer_connect.FetchGitHubInstallationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "connection": "projects/sample1/locations/sample2/connections/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + connection="connection_value", ) - await client.delete_connection(request=None) + mock_args.update(sample_request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteConnectionRequest() - assert args[0] == request_msg + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.FetchGitHubInstallationsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_git_hub_installations(**mock_args) -# 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_git_repository_link_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # 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/{connection=projects/*/locations/*/connections/*}:fetchGitHubInstallations" + % client.transport._host, + args[1], + ) + + +def test_fetch_git_hub_installations_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_git_repository_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_git_hub_installations( + developer_connect.FetchGitHubInstallationsRequest(), + connection="connection_value", ) - await client.create_git_repository_link(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.CreateGitRepositoryLinkRequest() - assert args[0] == request_msg +def test_fetch_git_refs_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 = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# 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_git_repository_link_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert client._transport.fetch_git_refs in client._transport._wrapped_methods - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_git_repository_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # 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. ) - await client.delete_git_repository_link(request=None) + client._transport._wrapped_methods[client._transport.fetch_git_refs] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteGitRepositoryLinkRequest() - assert args[0] == request_msg + request = {} + client.fetch_git_refs(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# 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_git_repository_links_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.fetch_git_refs(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_git_repository_links), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListGitRepositoryLinksResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_git_repository_links(request=None) + # 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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListGitRepositoryLinksRequest() - assert args[0] == request_msg +def test_fetch_git_refs_rest_required_fields( + request_type=developer_connect.FetchGitRefsRequest, +): + transport_class = transports.DeveloperConnectRestTransport -# 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_git_repository_link_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["git_repository_link"] = "" + 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 actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_git_repository_link), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.GitRepositoryLink( - name="name_value", - clone_uri="clone_uri_value", - etag="etag_value", - reconciling=True, - uid="uid_value", - webhook_id="webhook_id_value", - git_proxy_uri="git_proxy_uri_value", - ) - ) - await client.get_git_repository_link(request=None) + # verify fields with default values are dropped - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.GetGitRepositoryLinkRequest() - assert args[0] == request_msg + default_values = getattr( + transport_class._BaseFetchGitRefs, + "_BaseFetchGitRefs__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present -# 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_fetch_read_write_token_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + jsonified_request["gitRepositoryLink"] = "git_repository_link_value" - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_read_write_token), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchReadWriteTokenResponse( - token="token_value", - git_username="git_username_value", - ) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + "refType", ) - await client.fetch_read_write_token(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchReadWriteTokenRequest() - assert args[0] == request_msg + ) + # verify required fields with non-default values are left alone + assert "gitRepositoryLink" in jsonified_request + assert jsonified_request["gitRepositoryLink"] == "git_repository_link_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_fetch_read_token_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) + request = request_type(**request_init) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.fetch_read_token), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchReadTokenResponse( - token="token_value", - git_username="git_username_value", - ) - ) - await client.fetch_read_token(request=None) + # Designate an appropriate value for the returned response. + return_value = developer_connect.FetchGitRefsResponse() + # 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 - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchReadTokenRequest() - assert args[0] == request_msg + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.FetchGitRefsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_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_fetch_linkable_git_repositories_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + response_value._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, and fake the request. - with mock.patch.object( - type(client.transport.fetch_linkable_git_repositories), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchLinkableGitRepositoriesResponse( - next_page_token="next_page_token_value", - ) - ) - await client.fetch_linkable_git_repositories(request=None) + response = client.fetch_git_refs(request) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchLinkableGitRepositoriesRequest() - assert args[0] == request_msg + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) -# 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_fetch_git_hub_installations_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_fetch_git_refs_rest_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_git_hub_installations), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchGitHubInstallationsResponse() - ) - await client.fetch_git_hub_installations(request=None) + # 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 = developer_connect.FetchGitRefsResponse() - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchGitHubInstallationsRequest() - assert args[0] == request_msg + # get arguments that satisfy an http rule for this method + sample_request = { + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + # get truthy value for each flattened field + mock_args = dict( + git_repository_link="git_repository_link_value", + ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, + ) + mock_args.update(sample_request) -# 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_fetch_git_refs_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = developer_connect.FetchGitRefsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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, and fake the request. - with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchGitRefsResponse( - ref_names=["ref_names_value"], - next_page_token="next_page_token_value", - ) - ) - await client.fetch_git_refs(request=None) + client.fetch_git_refs(**mock_args) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchGitRefsRequest() - assert args[0] == request_msg + # 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/{git_repository_link=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchGitRefs" + % client.transport._host, + args[1], + ) -# 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_account_connectors_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_fetch_git_refs_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.list_account_connectors), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListAccountConnectorsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.fetch_git_refs( + developer_connect.FetchGitRefsRequest(), + git_repository_link="git_repository_link_value", + ref_type=developer_connect.FetchGitRefsRequest.RefType.TAG, ) - await client.list_account_connectors(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListAccountConnectorsRequest() - 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_account_connector_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_fetch_git_refs_rest_pager(transport: str = "rest"): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_account_connector), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.AccountConnector( - name="name_value", - etag="etag_value", - oauth_start_uri="oauth_start_uri_value", - ) + # 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 = ( + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), + str(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRefsResponse( + ref_names=[], + next_page_token="def", + ), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRefsResponse( + ref_names=[ + str(), + str(), + ], + ), ) - await client.get_account_connector(request=None) + # Two responses for two calls + response = response + response - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.GetAccountConnectorRequest() - assert args[0] == request_msg + # Wrap the values into proper Response objs + response = tuple( + developer_connect.FetchGitRefsResponse.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 = { + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } -# 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_account_connector_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + pager = client.fetch_git_refs(request=sample_request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.create_account_connector), "__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_account_connector(request=None) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.CreateAccountConnectorRequest() - assert args[0] == request_msg + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, str) for i in results) + pages = list(client.fetch_git_refs(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -# 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_account_connector_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.update_account_connector), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") +def test_diff_git_repository_link_commit_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 = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - await client.update_account_connector(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.UpdateAccountConnectorRequest() - assert args[0] == request_msg + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -# 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_account_connector_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + # Ensure method has been cached + assert ( + client._transport.diff_git_repository_link_commit + in client._transport._wrapped_methods + ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.delete_account_connector), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + # 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. ) - await client.delete_account_connector(request=None) + client._transport._wrapped_methods[ + client._transport.diff_git_repository_link_commit + ] = mock_rpc - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteAccountConnectorRequest() - assert args[0] == request_msg + request = {} + client.diff_git_repository_link_commit(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -# 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_fetch_access_token_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + client.diff_git_repository_link_commit(request) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.fetch_access_token), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FetchAccessTokenResponse( - token="token_value", - scopes=["scopes_value"], - ) - ) - await client.fetch_access_token(request=None) + # 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 stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchAccessTokenRequest() - assert args[0] == request_msg +def test_diff_git_repository_link_commit_rest_required_fields( + request_type=developer_connect.DiffGitRepositoryLinkCommitRequest, +): + transport_class = transports.DeveloperConnectRestTransport -# 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_users_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + request_init = {} + request_init["name"] = "" + request_init["base_sha"] = "" + request_init["head_sha"] = "" + 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 actual call, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.ListUsersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - ) - await client.list_users(request=None) + # verify fields with default values are dropped + assert "baseSha" not in jsonified_request + assert "headSha" not in jsonified_request - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.ListUsersRequest() - assert args[0] == request_msg + default_values = getattr( + transport_class._BaseDiffGitRepositoryLinkCommit, + "_BaseDiffGitRepositoryLinkCommit__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + # verify required fields with default values are now present + assert "baseSha" in jsonified_request + assert jsonified_request["baseSha"] == request_init["base_sha"] + assert "headSha" in jsonified_request + assert jsonified_request["headSha"] == request_init["head_sha"] -# 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_user_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) + jsonified_request["name"] = "name_value" + jsonified_request["baseSha"] = "base_sha_value" + jsonified_request["headSha"] = "head_sha_value" - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_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") + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "baseSha", + "headSha", + "pathFilters", ) - await client.delete_user(request=None) + ) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteUserRequest() - assert args[0] == request_msg + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "baseSha" in jsonified_request + assert jsonified_request["baseSha"] == "base_sha_value" + assert "headSha" in jsonified_request + assert jsonified_request["headSha"] == "head_sha_value" + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) -# 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_fetch_self_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # Designate an appropriate value for the returned response. + return_value = developer_connect.DiffGitRepositoryLinkCommitResponse() + # 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 = developer_connect.DiffGitRepositoryLinkCommitResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.diff_git_repository_link_commit(request) + + expected_params = [ + ( + "baseSha", + "", + ), + ( + "headSha", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_diff_git_repository_link_commit_rest_flattened(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.User( - name="name_value", - display_name="display_name_value", + # 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 = developer_connect.DiffGitRepositoryLinkCommitResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_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 = developer_connect.DiffGitRepositoryLinkCommitResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.diff_git_repository_link_commit(**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/*/connections/*/gitRepositoryLinks/*}:diffCommit" + % client.transport._host, + args[1], + ) + + +def test_diff_git_repository_link_commit_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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.diff_git_repository_link_commit( + developer_connect.DiffGitRepositoryLinkCommitRequest(), + name="name_value", + base_sha="base_sha_value", + head_sha="head_sha_value", + ) + + +def test_fetch_git_repository_link_commit_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 = DeveloperConnectClient( + 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.fetch_git_repository_link_commit + 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.fetch_git_repository_link_commit + ] = mock_rpc + + request = {} + client.fetch_git_repository_link_commit(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_git_repository_link_commit(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_fetch_git_repository_link_commit_rest_required_fields( + request_type=developer_connect.FetchGitRepositoryLinkCommitRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["name"] = "" + request_init["commit_sha"] = "" + 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 "commitSha" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchGitRepositoryLinkCommit, + "_BaseFetchGitRepositoryLinkCommit__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "commitSha" in jsonified_request + assert jsonified_request["commitSha"] == request_init["commit_sha"] + + jsonified_request["name"] = "name_value" + jsonified_request["commitSha"] = "commit_sha_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "commitSha", + "pathFilters", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "commitSha" in jsonified_request + assert jsonified_request["commitSha"] == "commit_sha_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.FetchGitRepositoryLinkCommitResponse() + # 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 = developer_connect.FetchGitRepositoryLinkCommitResponse.pb( + return_value ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_git_repository_link_commit(request) + + expected_params = [ + ( + "commitSha", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_git_repository_link_commit_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.FetchGitRepositoryLinkCommitResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + commit_sha="commit_sha_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 = developer_connect.FetchGitRepositoryLinkCommitResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_git_repository_link_commit(**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/*/connections/*/gitRepositoryLinks/*}:fetchCommit" + % client.transport._host, + args[1], + ) + + +def test_fetch_git_repository_link_commit_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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.fetch_git_repository_link_commit( + developer_connect.FetchGitRepositoryLinkCommitRequest(), + name="name_value", + commit_sha="commit_sha_value", + ) + + +def test_fetch_git_repository_link_commit_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 = DeveloperConnectClient( + 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.fetch_git_repository_link_commit_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.fetch_git_repository_link_commit_list + ] = mock_rpc + + request = {} + client.fetch_git_repository_link_commit_list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_git_repository_link_commit_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_fetch_git_repository_link_commit_list_rest_required_fields( + request_type=developer_connect.FetchGitRepositoryLinkCommitListRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseFetchGitRepositoryLinkCommitList, + "_BaseFetchGitRepositoryLinkCommitList__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "pageSize", + "pageToken", + "ref", + "view", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.FetchGitRepositoryLinkCommitListResponse() + # 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 = ( + developer_connect.FetchGitRepositoryLinkCommitListResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_git_repository_link_commit_list(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_git_repository_link_commit_list_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.FetchGitRepositoryLinkCommitListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ref="ref_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 = developer_connect.FetchGitRepositoryLinkCommitListResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_git_repository_link_commit_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/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchCommitList" + % client.transport._host, + args[1], + ) + + +def test_fetch_git_repository_link_commit_list_rest_flattened_error( + transport: str = "rest", +): + client = DeveloperConnectClient( + 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.fetch_git_repository_link_commit_list( + developer_connect.FetchGitRepositoryLinkCommitListRequest(), + name="name_value", + ref="ref_value", + ) + + +def test_fetch_git_repository_link_commit_list_rest_pager(transport: str = "rest"): + client = DeveloperConnectClient( + 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 = ( + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkCommitListResponse( + commits=[ + developer_connect.SCMCommit(), + developer_connect.SCMCommit(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + developer_connect.FetchGitRepositoryLinkCommitListResponse.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 = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + pager = client.fetch_git_repository_link_commit_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, developer_connect.SCMCommit) for i in results) + + pages = list( + client.fetch_git_repository_link_commit_list(request=sample_request).pages + ) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_fetch_git_repository_link_file_blame_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 = DeveloperConnectClient( + 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.fetch_git_repository_link_file_blame + 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.fetch_git_repository_link_file_blame + ] = mock_rpc + + request = {} + client.fetch_git_repository_link_file_blame(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_git_repository_link_file_blame(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_fetch_git_repository_link_file_blame_rest_required_fields( + request_type=developer_connect.FetchGitRepositoryLinkFileBlameRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["name"] = "" + request_init["ref"] = "" + request_init["path"] = "" + 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 "ref" not in jsonified_request + assert "path" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchGitRepositoryLinkFileBlame, + "_BaseFetchGitRepositoryLinkFileBlame__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "ref" in jsonified_request + assert jsonified_request["ref"] == request_init["ref"] + assert "path" in jsonified_request + assert jsonified_request["path"] == request_init["path"] + + jsonified_request["name"] = "name_value" + jsonified_request["ref"] = "ref_value" + jsonified_request["path"] = "path_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "firstLine", + "lastLine", + "path", + "ref", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "ref" in jsonified_request + assert jsonified_request["ref"] == "ref_value" + assert "path" in jsonified_request + assert jsonified_request["path"] == "path_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.FetchGitRepositoryLinkFileBlameResponse() + # 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 = developer_connect.FetchGitRepositoryLinkFileBlameResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_git_repository_link_file_blame(request) + + expected_params = [ + ( + "ref", + "", + ), + ( + "path", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_git_repository_link_file_blame_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.FetchGitRepositoryLinkFileBlameResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ref="ref_value", + path="path_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 = developer_connect.FetchGitRepositoryLinkFileBlameResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_git_repository_link_file_blame(**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/*/connections/*/gitRepositoryLinks/*}:fetchFileBlame" + % client.transport._host, + args[1], + ) + + +def test_fetch_git_repository_link_file_blame_rest_flattened_error( + transport: str = "rest", +): + client = DeveloperConnectClient( + 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.fetch_git_repository_link_file_blame( + developer_connect.FetchGitRepositoryLinkFileBlameRequest(), + name="name_value", + ref="ref_value", + path="path_value", + ) + + +def test_fetch_git_repository_link_pull_request_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 = DeveloperConnectClient( + 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.fetch_git_repository_link_pull_request + 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.fetch_git_repository_link_pull_request + ] = mock_rpc + + request = {} + client.fetch_git_repository_link_pull_request(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_git_repository_link_pull_request(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_fetch_git_repository_link_pull_request_rest_required_fields( + request_type=developer_connect.FetchGitRepositoryLinkPullRequestRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["name"] = "" + request_init["pull_request_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 "pullRequestId" not in jsonified_request + + default_values = getattr( + transport_class._BaseFetchGitRepositoryLinkPullRequest, + "_BaseFetchGitRepositoryLinkPullRequest__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "pullRequestId" in jsonified_request + assert jsonified_request["pullRequestId"] == request_init["pull_request_id"] + + jsonified_request["name"] = "name_value" + jsonified_request["pullRequestId"] = "pull_request_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("pullRequestId",)) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "pullRequestId" in jsonified_request + assert jsonified_request["pullRequestId"] == "pull_request_id_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.PullRequest() + # 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 = developer_connect.PullRequest.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_git_repository_link_pull_request(request) + + expected_params = [ + ( + "pullRequestId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_git_repository_link_pull_request_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.PullRequest() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + pull_request_id="pull_request_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 = developer_connect.PullRequest.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_git_repository_link_pull_request(**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/*/connections/*/gitRepositoryLinks/*}:fetchPullRequest" + % client.transport._host, + args[1], + ) + + +def test_fetch_git_repository_link_pull_request_rest_flattened_error( + transport: str = "rest", +): + client = DeveloperConnectClient( + 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.fetch_git_repository_link_pull_request( + developer_connect.FetchGitRepositoryLinkPullRequestRequest(), + name="name_value", + pull_request_id="pull_request_id_value", + ) + + +def test_add_git_repository_link_pull_request_comment_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 = DeveloperConnectClient( + 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_git_repository_link_pull_request_comment + 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_git_repository_link_pull_request_comment + ] = mock_rpc + + request = {} + client.add_git_repository_link_pull_request_comment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.add_git_repository_link_pull_request_comment(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_git_repository_link_pull_request_comment_rest_required_fields( + request_type=developer_connect.AddGitRepositoryLinkPullRequestCommentRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["name"] = "" + request_init["pull_request_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 + + default_values = getattr( + transport_class._BaseAddGitRepositoryLinkPullRequestComment, + "_BaseAddGitRepositoryLinkPullRequestComment__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["pullRequestId"] = "pull_request_id_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "pullRequestId" in jsonified_request + assert jsonified_request["pullRequestId"] == "pull_request_id_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.PullRequestComment() + # 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 = developer_connect.PullRequestComment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_git_repository_link_pull_request_comment(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_git_repository_link_pull_request_comment_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.PullRequestComment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestComment(id="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 = developer_connect.PullRequestComment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_git_repository_link_pull_request_comment(**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/*/connections/*/gitRepositoryLinks/*}:addPullRequestComment" + % client.transport._host, + args[1], + ) + + +def test_add_git_repository_link_pull_request_comment_rest_flattened_error( + transport: str = "rest", +): + client = DeveloperConnectClient( + 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_git_repository_link_pull_request_comment( + developer_connect.AddGitRepositoryLinkPullRequestCommentRequest(), + name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestComment(id="id_value"), + ) + + +def test_add_git_repository_link_pull_request_review_comment_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 = DeveloperConnectClient( + 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_git_repository_link_pull_request_review_comment + 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_git_repository_link_pull_request_review_comment + ] = mock_rpc + + request = {} + client.add_git_repository_link_pull_request_review_comment(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.add_git_repository_link_pull_request_review_comment(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_git_repository_link_pull_request_review_comment_rest_required_fields( + request_type=developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["name"] = "" + request_init["pull_request_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 + + default_values = getattr( + transport_class._BaseAddGitRepositoryLinkPullRequestReviewComment, + "_BaseAddGitRepositoryLinkPullRequestReviewComment__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["pullRequestId"] = "pull_request_id_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "pullRequestId" in jsonified_request + assert jsonified_request["pullRequestId"] == "pull_request_id_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.PullRequestReviewComment() + # 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 = developer_connect.PullRequestReviewComment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_git_repository_link_pull_request_review_comment( + 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_git_repository_link_pull_request_review_comment_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.PullRequestReviewComment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestReviewComment(id="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 = developer_connect.PullRequestReviewComment.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_git_repository_link_pull_request_review_comment(**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/*/connections/*/gitRepositoryLinks/*}:addPullRequestReviewComment" + % client.transport._host, + args[1], + ) + + +def test_add_git_repository_link_pull_request_review_comment_rest_flattened_error( + transport: str = "rest", +): + client = DeveloperConnectClient( + 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_git_repository_link_pull_request_review_comment( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest(), + name="name_value", + pull_request_id="pull_request_id_value", + comment=developer_connect.PullRequestReviewComment(id="id_value"), + ) + + +def test_modify_git_repository_link_pull_request_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 = DeveloperConnectClient( + 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.modify_git_repository_link_pull_request + 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.modify_git_repository_link_pull_request + ] = mock_rpc + + request = {} + client.modify_git_repository_link_pull_request(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.modify_git_repository_link_pull_request(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_modify_git_repository_link_pull_request_rest_required_fields( + request_type=developer_connect.ModifyGitRepositoryLinkPullRequestRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["name"] = "" + request_init["pull_request_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 + + default_values = getattr( + transport_class._BaseModifyGitRepositoryLinkPullRequest, + "_BaseModifyGitRepositoryLinkPullRequest__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + jsonified_request["pullRequestId"] = "pull_request_id_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "pullRequestId" in jsonified_request + assert jsonified_request["pullRequestId"] == "pull_request_id_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.PullRequest() + # 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 = developer_connect.PullRequest.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.modify_git_repository_link_pull_request(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_modify_git_repository_link_pull_request_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.PullRequest() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + pull_request_id="pull_request_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 = developer_connect.PullRequest.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.modify_git_repository_link_pull_request(**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/*/connections/*/gitRepositoryLinks/*}:modifyPullRequest" + % client.transport._host, + args[1], + ) + + +def test_modify_git_repository_link_pull_request_rest_flattened_error( + transport: str = "rest", +): + client = DeveloperConnectClient( + 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.modify_git_repository_link_pull_request( + developer_connect.ModifyGitRepositoryLinkPullRequestRequest(), + name="name_value", + pull_request_id="pull_request_id_value", + ) + + +def test_fetch_git_repository_link_pull_request_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 = DeveloperConnectClient( + 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.fetch_git_repository_link_pull_request_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.fetch_git_repository_link_pull_request_list + ] = mock_rpc + + request = {} + client.fetch_git_repository_link_pull_request_list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_git_repository_link_pull_request_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_fetch_git_repository_link_pull_request_list_rest_required_fields( + request_type=developer_connect.FetchGitRepositoryLinkPullRequestListRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseFetchGitRepositoryLinkPullRequestList, + "_BaseFetchGitRepositoryLinkPullRequestList__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.FetchGitRepositoryLinkPullRequestListResponse() + # 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 = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_git_repository_link_pull_request_list(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_git_repository_link_pull_request_list_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.FetchGitRepositoryLinkPullRequestListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse.pb( + return_value + ) + ) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_git_repository_link_pull_request_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/v1/{name=projects/*/locations/*/connections/*/gitRepositoryLinks/*}:fetchPullRequestList" + % client.transport._host, + args[1], + ) + + +def test_fetch_git_repository_link_pull_request_list_rest_flattened_error( + transport: str = "rest", +): + client = DeveloperConnectClient( + 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.fetch_git_repository_link_pull_request_list( + developer_connect.FetchGitRepositoryLinkPullRequestListRequest(), + name="name_value", + ) + + +def test_fetch_git_repository_link_pull_request_list_rest_pager( + transport: str = "rest", +): + client = DeveloperConnectClient( + 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 = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + next_page_token="abc", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[], + next_page_token="def", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + ], + next_page_token="ghi", + ), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + pull_requests=[ + developer_connect.PullRequest(), + developer_connect.PullRequest(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse.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 = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + + pager = client.fetch_git_repository_link_pull_request_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, developer_connect.PullRequest) for i in results) + + pages = list( + client.fetch_git_repository_link_pull_request_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_account_connectors_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 = DeveloperConnectClient( + 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_account_connectors + 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_account_connectors + ] = mock_rpc + + request = {} + client.list_account_connectors(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_account_connectors(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_account_connectors_rest_required_fields( + request_type=developer_connect.ListAccountConnectorsRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListAccountConnectors, + "_BaseListAccountConnectors__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.ListAccountConnectorsResponse() + # 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 = developer_connect.ListAccountConnectorsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_account_connectors(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_account_connectors_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.ListAccountConnectorsResponse() + + # 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 = developer_connect.ListAccountConnectorsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_account_connectors(**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/*}/accountConnectors" + % client.transport._host, + args[1], + ) + + +def test_list_account_connectors_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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_account_connectors( + developer_connect.ListAccountConnectorsRequest(), + parent="parent_value", + ) + + +def test_list_account_connectors_rest_pager(transport: str = "rest"): + client = DeveloperConnectClient( + 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 = ( + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + next_page_token="abc", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[], + next_page_token="def", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + ], + next_page_token="ghi", + ), + developer_connect.ListAccountConnectorsResponse( + account_connectors=[ + developer_connect.AccountConnector(), + developer_connect.AccountConnector(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + developer_connect.ListAccountConnectorsResponse.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_account_connectors(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, developer_connect.AccountConnector) for i in results) + + pages = list(client.list_account_connectors(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_account_connector_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 = DeveloperConnectClient( + 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_account_connector + 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_account_connector] = ( + mock_rpc + ) + + request = {} + client.get_account_connector(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_account_connector(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_account_connector_rest_required_fields( + request_type=developer_connect.GetAccountConnectorRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseGetAccountConnector, + "_BaseGetAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.AccountConnector() + # 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 = developer_connect.AccountConnector.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_account_connector(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_account_connector_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.AccountConnector() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/accountConnectors/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 = developer_connect.AccountConnector.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_account_connector(**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/*/accountConnectors/*}" + % client.transport._host, + args[1], + ) + + +def test_get_account_connector_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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_account_connector( + developer_connect.GetAccountConnectorRequest(), + name="name_value", + ) + + +def test_create_account_connector_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 = DeveloperConnectClient( + 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_account_connector + 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_account_connector + ] = mock_rpc + + request = {} + client.create_account_connector(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_account_connector(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_account_connector_rest_required_fields( + request_type=developer_connect.CreateAccountConnectorRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["account_connector_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 "accountConnectorId" not in jsonified_request + + default_values = getattr( + transport_class._BaseCreateAccountConnector, + "_BaseCreateAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "accountConnectorId" in jsonified_request + assert ( + jsonified_request["accountConnectorId"] == request_init["account_connector_id"] + ) + + jsonified_request["parent"] = "parent_value" + jsonified_request["accountConnectorId"] = "account_connector_id_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "accountConnectorId", + "requestId", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "accountConnectorId" in jsonified_request + assert jsonified_request["accountConnectorId"] == "account_connector_id_value" + + client = DeveloperConnectClient( + 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_account_connector(request) + + expected_params = [ + ( + "accountConnectorId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_account_connector_rest_flattened(): + client = DeveloperConnectClient( + 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", + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + account_connector_id="account_connector_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_account_connector(**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/*}/accountConnectors" + % client.transport._host, + args[1], + ) + + +def test_create_account_connector_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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_account_connector( + developer_connect.CreateAccountConnectorRequest(), + parent="parent_value", + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + account_connector_id="account_connector_id_value", + ) + + +def test_update_account_connector_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 = DeveloperConnectClient( + 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_account_connector + 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_account_connector + ] = mock_rpc + + request = {} + client.update_account_connector(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_account_connector(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_account_connector_rest_required_fields( + request_type=developer_connect.UpdateAccountConnectorRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseUpdateAccountConnector, + "_BaseUpdateAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allowMissing", + "requestId", + "updateMask", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + + client = DeveloperConnectClient( + 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_account_connector(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_account_connector_rest_flattened(): + client = DeveloperConnectClient( + 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 = { + "account_connector": { + "name": "projects/sample1/locations/sample2/accountConnectors/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + 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_account_connector(**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/{account_connector.name=projects/*/locations/*/accountConnectors/*}" + % client.transport._host, + args[1], + ) + + +def test_update_account_connector_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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_account_connector( + developer_connect.UpdateAccountConnectorRequest(), + account_connector=developer_connect.AccountConnector( + provider_oauth_config=developer_connect.ProviderOAuthConfig( + system_provider_id=developer_connect.SystemProvider.GITHUB + ) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_account_connector_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 = DeveloperConnectClient( + 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_account_connector + 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_account_connector + ] = mock_rpc + + request = {} + client.delete_account_connector(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_account_connector(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_account_connector_rest_required_fields( + request_type=developer_connect.DeleteAccountConnectorRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteAccountConnector, + "_BaseDeleteAccountConnector__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "force", + "requestId", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DeveloperConnectClient( + 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_account_connector(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_account_connector_rest_flattened(): + client = DeveloperConnectClient( + 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/accountConnectors/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_account_connector(**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/*/accountConnectors/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_account_connector_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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_account_connector( + developer_connect.DeleteAccountConnectorRequest(), + name="name_value", + ) + + +def test_fetch_access_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 = DeveloperConnectClient( + 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.fetch_access_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.fetch_access_token] = ( + mock_rpc + ) + + request = {} + client.fetch_access_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_access_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_fetch_access_token_rest_required_fields( + request_type=developer_connect.FetchAccessTokenRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["account_connector"] = "" + 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 + + default_values = getattr( + transport_class._BaseFetchAccessToken, + "_BaseFetchAccessToken__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["accountConnector"] = "account_connector_value" + + # verify required fields with non-default values are left alone + assert "accountConnector" in jsonified_request + assert jsonified_request["accountConnector"] == "account_connector_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.FetchAccessTokenResponse() + # 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 = developer_connect.FetchAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_access_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_fetch_access_token_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.FetchAccessTokenResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "account_connector": "projects/sample1/locations/sample2/accountConnectors/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + account_connector="account_connector_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 = developer_connect.FetchAccessTokenResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_access_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/v1/{account_connector=projects/*/locations/*/accountConnectors/*}/users:fetchAccessToken" + % client.transport._host, + args[1], + ) + + +def test_fetch_access_token_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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.fetch_access_token( + developer_connect.FetchAccessTokenRequest(), + account_connector="account_connector_value", + ) + + +def test_list_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 = DeveloperConnectClient( + 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_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_users] = mock_rpc + + request = {} + client.list_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_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_users_rest_required_fields( + request_type=developer_connect.ListUsersRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseListUsers, + "_BaseListUsers__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.ListUsersResponse() + # 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 = developer_connect.ListUsersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_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_users_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.ListUsersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/accountConnectors/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 = developer_connect.ListUsersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_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/v1/{parent=projects/*/locations/*/accountConnectors/*}/users" + % client.transport._host, + args[1], + ) + + +def test_list_users_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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_users( + developer_connect.ListUsersRequest(), + parent="parent_value", + ) + + +def test_list_users_rest_pager(transport: str = "rest"): + client = DeveloperConnectClient( + 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 = ( + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), + developer_connect.User(), + ], + next_page_token="abc", + ), + developer_connect.ListUsersResponse( + users=[], + next_page_token="def", + ), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + ], + next_page_token="ghi", + ), + developer_connect.ListUsersResponse( + users=[ + developer_connect.User(), + developer_connect.User(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + developer_connect.ListUsersResponse.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/accountConnectors/sample3" + } + + pager = client.list_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, developer_connect.User) for i in results) + + pages = list(client.list_users(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_delete_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 = DeveloperConnectClient( + 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_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_user] = mock_rpc + + request = {} + client.delete_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_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_user_rest_required_fields( + request_type=developer_connect.DeleteUserRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteUser, + "_BaseDeleteUser__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "requestId", + "validateOnly", + ) + ) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DeveloperConnectClient( + 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_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_user_rest_flattened(): + client = DeveloperConnectClient( + 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/accountConnectors/sample3/users/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_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/v1/{name=projects/*/locations/*/accountConnectors/*/users/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_user_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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_user( + developer_connect.DeleteUserRequest(), + name="name_value", + ) + + +def test_fetch_self_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 = DeveloperConnectClient( + 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.fetch_self 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.fetch_self] = mock_rpc + + request = {} + client.fetch_self(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.fetch_self(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_fetch_self_rest_required_fields( + request_type=developer_connect.FetchSelfRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseFetchSelf, + "_BaseFetchSelf__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.User() + # 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 = developer_connect.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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.fetch_self(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_fetch_self_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.User() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/accountConnectors/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 = developer_connect.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.fetch_self(**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/*/accountConnectors/*}/users:fetchSelf" + % client.transport._host, + args[1], + ) + + +def test_fetch_self_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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.fetch_self( + developer_connect.FetchSelfRequest(), + name="name_value", + ) + + +def test_delete_self_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 = DeveloperConnectClient( + 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_self 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_self] = mock_rpc + + request = {} + client.delete_self(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_self(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_self_rest_required_fields( + request_type=developer_connect.DeleteSelfRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + 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 + + default_values = getattr( + transport_class._BaseDeleteSelf, + "_BaseDeleteSelf__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = DeveloperConnectClient( + 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_self(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_self_rest_flattened(): + client = DeveloperConnectClient( + 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/accountConnectors/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_self(**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/*/accountConnectors/*}/users:deleteSelf" + % client.transport._host, + args[1], + ) + + +def test_delete_self_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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_self( + developer_connect.DeleteSelfRequest(), + name="name_value", + ) + + +def test_start_o_auth_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 = DeveloperConnectClient( + 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_o_auth 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_o_auth] = mock_rpc + + request = {} + client.start_o_auth(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.start_o_auth(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_o_auth_rest_required_fields( + request_type=developer_connect.StartOAuthRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["account_connector"] = "" + 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 + + default_values = getattr( + transport_class._BaseStartOAuth, + "_BaseStartOAuth__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["accountConnector"] = "account_connector_value" + + # verify required fields with non-default values are left alone + assert "accountConnector" in jsonified_request + assert jsonified_request["accountConnector"] == "account_connector_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.StartOAuthResponse() + # 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 = developer_connect.StartOAuthResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_o_auth(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_o_auth_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.StartOAuthResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "account_connector": "projects/sample1/locations/sample2/accountConnectors/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + account_connector="account_connector_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 = developer_connect.StartOAuthResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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.start_o_auth(**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/{account_connector=projects/*/locations/*/accountConnectors/*}/users:startOAuthFlow" + % client.transport._host, + args[1], + ) + + +def test_start_o_auth_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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.start_o_auth( + developer_connect.StartOAuthRequest(), + account_connector="account_connector_value", + ) + + +def test_finish_o_auth_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 = DeveloperConnectClient( + 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_o_auth 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_o_auth] = mock_rpc + + request = {} + client.finish_o_auth(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.finish_o_auth(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_o_auth_rest_required_fields( + request_type=developer_connect.FinishOAuthRequest, +): + transport_class = transports.DeveloperConnectRestTransport + + request_init = {} + request_init["account_connector"] = "" + 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 + + default_values = getattr( + transport_class._BaseFinishOAuth, + "_BaseFinishOAuth__REQUIRED_FIELDS_DEFAULT_VALUES", + {}, + ) + unset_fields = { + k: v for k, v in default_values.items() if k not in jsonified_request + } + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["accountConnector"] = "account_connector_value" + + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "googleOauthParams", + "oauthParams", + ) + ) + + # verify required fields with non-default values are left alone + assert "accountConnector" in jsonified_request + assert jsonified_request["accountConnector"] == "account_connector_value" + + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = developer_connect.FinishOAuthResponse() + # 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 = developer_connect.FinishOAuthResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._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_o_auth(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_o_auth_rest_flattened(): + client = DeveloperConnectClient( + 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 = developer_connect.FinishOAuthResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "account_connector": "projects/sample1/locations/sample2/accountConnectors/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + account_connector="account_connector_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 = developer_connect.FinishOAuthResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._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_o_auth(**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/{account_connector=projects/*/locations/*/accountConnectors/*}/users:finishOAuthFlow" + % client.transport._host, + args[1], + ) + + +def test_finish_o_auth_rest_flattened_error(transport: str = "rest"): + client = DeveloperConnectClient( + 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_o_auth( + developer_connect.FinishOAuthRequest(), + account_connector="account_connector_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DeveloperConnectGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DeveloperConnectGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeveloperConnectClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DeveloperConnectGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DeveloperConnectClient( + 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 = DeveloperConnectClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DeveloperConnectGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DeveloperConnectClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeveloperConnectGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DeveloperConnectClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DeveloperConnectGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DeveloperConnectGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DeveloperConnectGrpcTransport, + transports.DeveloperConnectGrpcAsyncIOTransport, + transports.DeveloperConnectRestTransport, + ], +) +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 = DeveloperConnectClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = DeveloperConnectClient( + 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_connections_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_connections), "__call__") as call: + call.return_value = developer_connect.ListConnectionsResponse() + client.list_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ListConnectionsRequest() + 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_connection_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_connection), "__call__") as call: + call.return_value = developer_connect.Connection() + client.get_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.GetConnectionRequest() + 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_connection_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_connection), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.CreateConnectionRequest() + 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_connection_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_connection), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.UpdateConnectionRequest() + 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_connection_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_connection), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteConnectionRequest() + 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_git_repository_link_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_git_repository_link), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_git_repository_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.CreateGitRepositoryLinkRequest() + 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_git_repository_link_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_git_repository_link), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_git_repository_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteGitRepositoryLinkRequest() + 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_git_repository_links_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_git_repository_links), "__call__" + ) as call: + call.return_value = developer_connect.ListGitRepositoryLinksResponse() + client.list_git_repository_links(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ListGitRepositoryLinksRequest() + 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_git_repository_link_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_git_repository_link), "__call__" + ) as call: + call.return_value = developer_connect.GitRepositoryLink() + client.get_git_repository_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.GetGitRepositoryLinkRequest() + 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_fetch_read_write_token_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_read_write_token), "__call__" + ) as call: + call.return_value = developer_connect.FetchReadWriteTokenResponse() + client.fetch_read_write_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchReadWriteTokenRequest() + 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_fetch_read_token_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_read_token), "__call__") as call: + call.return_value = developer_connect.FetchReadTokenResponse() + client.fetch_read_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchReadTokenRequest() + 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_open_git_repository_link_pull_request_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.open_git_repository_link_pull_request), "__call__" + ) as call: + call.return_value = developer_connect.PullRequest() + client.open_git_repository_link_pull_request(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.OpenGitRepositoryLinkPullRequestRequest() + 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_fetch_linkable_git_repositories_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_linkable_git_repositories), "__call__" + ) as call: + call.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() + client.fetch_linkable_git_repositories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchLinkableGitRepositoriesRequest() + 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_fetch_git_hub_installations_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_hub_installations), "__call__" + ) as call: + call.return_value = developer_connect.FetchGitHubInstallationsResponse() + client.fetch_git_hub_installations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitHubInstallationsRequest() + 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_fetch_git_refs_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: + call.return_value = developer_connect.FetchGitRefsResponse() + client.fetch_git_refs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRefsRequest() + 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_diff_git_repository_link_commit_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.diff_git_repository_link_commit), "__call__" + ) as call: + call.return_value = developer_connect.DiffGitRepositoryLinkCommitResponse() + client.diff_git_repository_link_commit(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DiffGitRepositoryLinkCommitRequest() + 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_fetch_git_repository_link_commit_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_commit), "__call__" + ) as call: + call.return_value = developer_connect.FetchGitRepositoryLinkCommitResponse() + client.fetch_git_repository_link_commit(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkCommitRequest() + 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_fetch_git_repository_link_commit_list_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_commit_list), "__call__" + ) as call: + call.return_value = developer_connect.FetchGitRepositoryLinkCommitListResponse() + client.fetch_git_repository_link_commit_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkCommitListRequest() + 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_fetch_git_repository_link_file_blame_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_file_blame), "__call__" + ) as call: + call.return_value = developer_connect.FetchGitRepositoryLinkFileBlameResponse() + client.fetch_git_repository_link_file_blame(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkFileBlameRequest() + 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_fetch_git_repository_link_pull_request_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request), "__call__" + ) as call: + call.return_value = developer_connect.PullRequest() + client.fetch_git_repository_link_pull_request(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkPullRequestRequest() + 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_git_repository_link_pull_request_comment_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: + call.return_value = developer_connect.PullRequestComment() + client.add_git_repository_link_pull_request_comment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest() + 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_git_repository_link_pull_request_review_comment_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", + ) as call: + call.return_value = developer_connect.PullRequestReviewComment() + client.add_git_repository_link_pull_request_review_comment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest() + ) + 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_modify_git_repository_link_pull_request_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: + call.return_value = developer_connect.PullRequest() + client.modify_git_repository_link_pull_request(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ModifyGitRepositoryLinkPullRequestRequest() + 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_fetch_git_repository_link_pull_request_list_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: + call.return_value = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse() + ) + client.fetch_git_repository_link_pull_request_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkPullRequestListRequest() + 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_account_connectors_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: + call.return_value = developer_connect.ListAccountConnectorsResponse() + client.list_account_connectors(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ListAccountConnectorsRequest() + 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_account_connector_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_connector), "__call__" + ) as call: + call.return_value = developer_connect.AccountConnector() + client.get_account_connector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.GetAccountConnectorRequest() + 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_account_connector_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_account_connector), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_account_connector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.CreateAccountConnectorRequest() + 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_account_connector_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account_connector), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_account_connector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.UpdateAccountConnectorRequest() + 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_account_connector_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_account_connector), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_account_connector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteAccountConnectorRequest() + 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_fetch_access_token_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_access_token), "__call__" + ) as call: + call.return_value = developer_connect.FetchAccessTokenResponse() + client.fetch_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchAccessTokenRequest() + 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_users_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + call.return_value = developer_connect.ListUsersResponse() + client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ListUsersRequest() + 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_user_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteUserRequest() + 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_fetch_self_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + call.return_value = developer_connect.User() + client.fetch_self(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchSelfRequest() + 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_self_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_self), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_self(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteSelfRequest() + 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_o_auth_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + call.return_value = developer_connect.StartOAuthResponse() + client.start_o_auth(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.StartOAuthRequest() + 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_o_auth_empty_call_grpc(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + call.return_value = developer_connect.FinishOAuthResponse() + client.finish_o_auth(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FinishOAuthRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = DeveloperConnectAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + 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_connections_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_connections), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.ListConnectionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_connections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ListConnectionsRequest() + 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_connection_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_connection), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.Connection( + name="name_value", + disabled=True, + reconciling=True, + etag="etag_value", + uid="uid_value", + ) + ) + await client.get_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.GetConnectionRequest() + 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_connection_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_connection), "__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_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.CreateConnectionRequest() + 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_connection_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_connection), "__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_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.UpdateConnectionRequest() + 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_connection_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_connection), "__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_connection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteConnectionRequest() + 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_git_repository_link_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_git_repository_link), "__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_git_repository_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.CreateGitRepositoryLinkRequest() + 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_git_repository_link_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_git_repository_link), "__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_git_repository_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteGitRepositoryLinkRequest() + 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_git_repository_links_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_git_repository_links), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.ListGitRepositoryLinksResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_git_repository_links(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ListGitRepositoryLinksRequest() + 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_git_repository_link_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_git_repository_link), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.GitRepositoryLink( + name="name_value", + clone_uri="clone_uri_value", + etag="etag_value", + reconciling=True, + uid="uid_value", + webhook_id="webhook_id_value", + git_proxy_uri="git_proxy_uri_value", + ) + ) + await client.get_git_repository_link(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.GetGitRepositoryLinkRequest() + 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_fetch_read_write_token_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_read_write_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchReadWriteTokenResponse( + token="token_value", + git_username="git_username_value", + ) + ) + await client.fetch_read_write_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchReadWriteTokenRequest() + 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_fetch_read_token_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_read_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchReadTokenResponse( + token="token_value", + git_username="git_username_value", + ) + ) + await client.fetch_read_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchReadTokenRequest() + 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_open_git_repository_link_pull_request_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.open_git_repository_link_pull_request), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", + ) + ) + await client.open_git_repository_link_pull_request(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.OpenGitRepositoryLinkPullRequestRequest() + 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_fetch_linkable_git_repositories_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_linkable_git_repositories), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchLinkableGitRepositoriesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_linkable_git_repositories(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchLinkableGitRepositoriesRequest() + 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_fetch_git_hub_installations_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_hub_installations), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchGitHubInstallationsResponse() + ) + await client.fetch_git_hub_installations(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitHubInstallationsRequest() + 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_fetch_git_refs_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_git_refs), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchGitRefsResponse( + ref_names=["ref_names_value"], + next_page_token="next_page_token_value", + ) + ) + await client.fetch_git_refs(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRefsRequest() + 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_diff_git_repository_link_commit_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.diff_git_repository_link_commit), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.DiffGitRepositoryLinkCommitResponse() + ) + await client.diff_git_repository_link_commit(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DiffGitRepositoryLinkCommitRequest() + 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_fetch_git_repository_link_commit_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_commit), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchGitRepositoryLinkCommitResponse() + ) + await client.fetch_git_repository_link_commit(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkCommitRequest() + 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_fetch_git_repository_link_commit_list_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_commit_list), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchGitRepositoryLinkCommitListResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_git_repository_link_commit_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkCommitListRequest() + 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_fetch_git_repository_link_file_blame_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_file_blame), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchGitRepositoryLinkFileBlameResponse() + ) + await client.fetch_git_repository_link_file_blame(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkFileBlameRequest() + 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_fetch_git_repository_link_pull_request_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", + ) + ) + await client.fetch_git_repository_link_pull_request(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkPullRequestRequest() + 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_git_repository_link_pull_request_comment_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.PullRequestComment( + id="id_value", + body="body_value", + author="author_value", + ) + ) + await client.add_git_repository_link_pull_request_comment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest() + 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_git_repository_link_pull_request_review_comment_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.PullRequestReviewComment( + id="id_value", + body="body_value", + path="path_value", + first_line=1071, + last_line=955, + side=developer_connect.PullRequestReviewComment.DiffSide.BASE, + author="author_value", + commit_id="commit_id_value", + ) + ) + await client.add_git_repository_link_pull_request_review_comment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest() + ) + 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_modify_git_repository_link_pull_request_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", + ) + ) + await client.modify_git_repository_link_pull_request(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ModifyGitRepositoryLinkPullRequestRequest() + 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_fetch_git_repository_link_pull_request_list_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse( + next_page_token="next_page_token_value", + ) + ) + await client.fetch_git_repository_link_pull_request_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkPullRequestListRequest() + 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_account_connectors_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_account_connectors), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.ListAccountConnectorsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_account_connectors(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ListAccountConnectorsRequest() + 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_account_connector_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_account_connector), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.AccountConnector( + name="name_value", + etag="etag_value", + oauth_start_uri="oauth_start_uri_value", + ) + ) + await client.get_account_connector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.GetAccountConnectorRequest() + 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_account_connector_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.create_account_connector), "__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_account_connector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.CreateAccountConnectorRequest() + 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_account_connector_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.update_account_connector), "__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_account_connector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.UpdateAccountConnectorRequest() + 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_account_connector_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_account_connector), "__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_account_connector(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteAccountConnectorRequest() + 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_fetch_access_token_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_access_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FetchAccessTokenResponse( + token="token_value", + scopes=["scopes_value"], + ) + ) + await client.fetch_access_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchAccessTokenRequest() + 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_users_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ListUsersRequest() + 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_user_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_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_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteUserRequest() + 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_fetch_self_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.fetch_self), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.User( + name="name_value", + display_name="display_name_value", + ) + ) + await client.fetch_self(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchSelfRequest() + 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_self_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_self), "__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_self(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DeleteSelfRequest() + 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_o_auth_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.StartOAuthResponse( + ticket="ticket_value", + code_challenge="code_challenge_value", + code_challenge_method="code_challenge_method_value", + client_id="client_id_value", + scopes=["scopes_value"], + auth_uri="auth_uri_value", + ) + ) + await client.start_o_auth(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.StartOAuthRequest() + 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_o_auth_empty_call_grpc_asyncio(): + client = DeveloperConnectAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + developer_connect.FinishOAuthResponse() + ) + await client.finish_o_auth(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FinishOAuthRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = DeveloperConnectClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_connections_rest_bad_request( + request_type=developer_connect.ListConnectionsRequest, +): + client = DeveloperConnectClient( + 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_connections(request) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.ListConnectionsRequest, + dict, + ], +) +def test_list_connections_rest_call_success(request_type): + client = DeveloperConnectClient( + 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 = developer_connect.ListConnectionsResponse( + 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 = developer_connect.ListConnectionsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_connections(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListConnectionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_connections_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), + ) + client = DeveloperConnectClient(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.DeveloperConnectRestInterceptor, "post_list_connections" + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_list_connections_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "pre_list_connections" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.ListConnectionsRequest.pb( + developer_connect.ListConnectionsRequest() + ) + 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 = developer_connect.ListConnectionsResponse.to_json( + developer_connect.ListConnectionsResponse() + ) + req.return_value.content = return_value + + request = developer_connect.ListConnectionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = developer_connect.ListConnectionsResponse() + post_with_metadata.return_value = ( + developer_connect.ListConnectionsResponse(), + metadata, + ) + + client.list_connections( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_connection_rest_bad_request( + request_type=developer_connect.GetConnectionRequest, +): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/connections/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_connection(request) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.GetConnectionRequest, + dict, + ], +) +def test_get_connection_rest_call_success(request_type): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/connections/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 = developer_connect.Connection( + name="name_value", + disabled=True, + reconciling=True, + etag="etag_value", + 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 = developer_connect.Connection.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_connection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, developer_connect.Connection) + assert response.name == "name_value" + assert response.disabled is True + assert response.reconciling is True + assert response.etag == "etag_value" + assert response.uid == "uid_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_connection_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), + ) + client = DeveloperConnectClient(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.DeveloperConnectRestInterceptor, "post_get_connection" + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_get_connection_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "pre_get_connection" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.GetConnectionRequest.pb( + developer_connect.GetConnectionRequest() + ) + 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 = developer_connect.Connection.to_json( + developer_connect.Connection() + ) + req.return_value.content = return_value + + request = developer_connect.GetConnectionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = developer_connect.Connection() + post_with_metadata.return_value = developer_connect.Connection(), metadata + + client.get_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_connection_rest_bad_request( + request_type=developer_connect.CreateConnectionRequest, +): + client = DeveloperConnectClient( + 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_connection(request) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.CreateConnectionRequest, + dict, + ], +) +def test_create_connection_rest_call_success(request_type): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["connection"] = { + "github_config": { + "github_app": 1, + "authorizer_credential": { + "oauth_token_secret_version": "oauth_token_secret_version_value", + "username": "username_value", + }, + "app_installation_id": 2014, + "installation_uri": "installation_uri_value", + }, + "github_enterprise_config": { + "host_uri": "host_uri_value", + "app_id": 621, + "app_slug": "app_slug_value", + "private_key_secret_version": "private_key_secret_version_value", + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "app_installation_id": 2014, + "installation_uri": "installation_uri_value", + "service_directory_config": {"service": "service_value"}, + "server_version": "server_version_value", + "ssl_ca_certificate": "ssl_ca_certificate_value", + "organization": "organization_value", + }, + "gitlab_config": { + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "read_authorizer_credential": { + "user_token_secret_version": "user_token_secret_version_value", + "username": "username_value", + }, + "authorizer_credential": {}, + }, + "gitlab_enterprise_config": { + "host_uri": "host_uri_value", + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "read_authorizer_credential": {}, + "authorizer_credential": {}, + "service_directory_config": {}, + "ssl_ca_certificate": "ssl_ca_certificate_value", + "server_version": "server_version_value", + }, + "bitbucket_data_center_config": { + "host_uri": "host_uri_value", + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "read_authorizer_credential": {}, + "authorizer_credential": {}, + "service_directory_config": {}, + "ssl_ca_certificate": "ssl_ca_certificate_value", + "server_version": "server_version_value", + }, + "bitbucket_cloud_config": { + "workspace": "workspace_value", + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "read_authorizer_credential": {}, + "authorizer_credential": {}, + }, + "secure_source_manager_instance_config": {"instance": "instance_value"}, + "http_config": { + "basic_authentication": { + "password_secret_version": "password_secret_version_value", + "username": "username_value", + }, + "bearer_token_authentication": { + "token_secret_version": "token_secret_version_value" + }, + "host_uri": "host_uri_value", + "service_directory_config": {}, + "ssl_ca_certificate": "ssl_ca_certificate_value", + }, + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "installation_state": { + "stage": 1, + "message": "message_value", + "action_uri": "action_uri_value", + }, + "disabled": True, + "reconciling": True, + "annotations": {}, + "etag": "etag_value", + "uid": "uid_value", + "crypto_key_config": {"key_reference": "key_reference_value"}, + "git_proxy_config": { + "enabled": True, + "http_proxy_base_uri": "http_proxy_base_uri_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 = developer_connect.CreateConnectionRequest.meta.fields["connection"] + + 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["connection"].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["connection"][field])): + del request_init["connection"][field][i][subfield] + else: + del request_init["connection"][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_connection(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_connection_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), + ) + client = DeveloperConnectClient(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.DeveloperConnectRestInterceptor, "post_create_connection" + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_create_connection_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "pre_create_connection" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.CreateConnectionRequest.pb( + developer_connect.CreateConnectionRequest() + ) + 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 = developer_connect.CreateConnectionRequest() + 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_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_connection_rest_bad_request( + request_type=developer_connect.UpdateConnectionRequest, +): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "connection": {"name": "projects/sample1/locations/sample2/connections/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_connection(request) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.UpdateConnectionRequest, + dict, + ], +) +def test_update_connection_rest_call_success(request_type): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "connection": {"name": "projects/sample1/locations/sample2/connections/sample3"} + } + request_init["connection"] = { + "github_config": { + "github_app": 1, + "authorizer_credential": { + "oauth_token_secret_version": "oauth_token_secret_version_value", + "username": "username_value", + }, + "app_installation_id": 2014, + "installation_uri": "installation_uri_value", + }, + "github_enterprise_config": { + "host_uri": "host_uri_value", + "app_id": 621, + "app_slug": "app_slug_value", + "private_key_secret_version": "private_key_secret_version_value", + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "app_installation_id": 2014, + "installation_uri": "installation_uri_value", + "service_directory_config": {"service": "service_value"}, + "server_version": "server_version_value", + "ssl_ca_certificate": "ssl_ca_certificate_value", + "organization": "organization_value", + }, + "gitlab_config": { + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "read_authorizer_credential": { + "user_token_secret_version": "user_token_secret_version_value", + "username": "username_value", + }, + "authorizer_credential": {}, + }, + "gitlab_enterprise_config": { + "host_uri": "host_uri_value", + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "read_authorizer_credential": {}, + "authorizer_credential": {}, + "service_directory_config": {}, + "ssl_ca_certificate": "ssl_ca_certificate_value", + "server_version": "server_version_value", + }, + "bitbucket_data_center_config": { + "host_uri": "host_uri_value", + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "read_authorizer_credential": {}, + "authorizer_credential": {}, + "service_directory_config": {}, + "ssl_ca_certificate": "ssl_ca_certificate_value", + "server_version": "server_version_value", + }, + "bitbucket_cloud_config": { + "workspace": "workspace_value", + "webhook_secret_secret_version": "webhook_secret_secret_version_value", + "read_authorizer_credential": {}, + "authorizer_credential": {}, + }, + "secure_source_manager_instance_config": {"instance": "instance_value"}, + "http_config": { + "basic_authentication": { + "password_secret_version": "password_secret_version_value", + "username": "username_value", + }, + "bearer_token_authentication": { + "token_secret_version": "token_secret_version_value" + }, + "host_uri": "host_uri_value", + "service_directory_config": {}, + "ssl_ca_certificate": "ssl_ca_certificate_value", + }, + "name": "projects/sample1/locations/sample2/connections/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "installation_state": { + "stage": 1, + "message": "message_value", + "action_uri": "action_uri_value", + }, + "disabled": True, + "reconciling": True, + "annotations": {}, + "etag": "etag_value", + "uid": "uid_value", + "crypto_key_config": {"key_reference": "key_reference_value"}, + "git_proxy_config": { + "enabled": True, + "http_proxy_base_uri": "http_proxy_base_uri_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 = developer_connect.UpdateConnectionRequest.meta.fields["connection"] + + 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["connection"].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["connection"][field])): + del request_init["connection"][field][i][subfield] + else: + del request_init["connection"][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_connection(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_connection_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), + ) + client = DeveloperConnectClient(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.DeveloperConnectRestInterceptor, "post_update_connection" + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_update_connection_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "pre_update_connection" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.UpdateConnectionRequest.pb( + developer_connect.UpdateConnectionRequest() + ) + 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 = developer_connect.UpdateConnectionRequest() + 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_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_connection_rest_bad_request( + request_type=developer_connect.DeleteConnectionRequest, +): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/connections/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_connection(request) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.DeleteConnectionRequest, + dict, + ], +) +def test_delete_connection_rest_call_success(request_type): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/connections/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_connection(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_connection_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), + ) + client = DeveloperConnectClient(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.DeveloperConnectRestInterceptor, "post_delete_connection" + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_delete_connection_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "pre_delete_connection" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.DeleteConnectionRequest.pb( + developer_connect.DeleteConnectionRequest() + ) + 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 = developer_connect.DeleteConnectionRequest() + 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_connection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_git_repository_link_rest_bad_request( + request_type=developer_connect.CreateGitRepositoryLinkRequest, +): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/connections/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.create_git_repository_link(request) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.CreateGitRepositoryLinkRequest, + dict, + ], +) +def test_create_git_repository_link_rest_call_success(request_type): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/connections/sample3"} + request_init["git_repository_link"] = { + "name": "name_value", + "clone_uri": "clone_uri_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "etag": "etag_value", + "reconciling": True, + "annotations": {}, + "uid": "uid_value", + "webhook_id": "webhook_id_value", + "git_proxy_uri": "git_proxy_uri_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 = developer_connect.CreateGitRepositoryLinkRequest.meta.fields[ + "git_repository_link" + ] + + 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["git_repository_link"].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["git_repository_link"][field])): + del request_init["git_repository_link"][field][i][subfield] + else: + del request_init["git_repository_link"][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_git_repository_link(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_git_repository_link_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), + ) + client = DeveloperConnectClient(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.DeveloperConnectRestInterceptor, + "post_create_git_repository_link", + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_create_git_repository_link_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "pre_create_git_repository_link" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.CreateGitRepositoryLinkRequest.pb( + developer_connect.CreateGitRepositoryLinkRequest() + ) + 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 = developer_connect.CreateGitRepositoryLinkRequest() + 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_git_repository_link( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_git_repository_link_rest_bad_request( + request_type=developer_connect.DeleteGitRepositoryLinkRequest, +): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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_git_repository_link(request) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.DeleteGitRepositoryLinkRequest, + dict, + ], +) +def test_delete_git_repository_link_rest_call_success(request_type): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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_git_repository_link(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_git_repository_link_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), + ) + client = DeveloperConnectClient(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.DeveloperConnectRestInterceptor, + "post_delete_git_repository_link", + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_delete_git_repository_link_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "pre_delete_git_repository_link" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.DeleteGitRepositoryLinkRequest.pb( + developer_connect.DeleteGitRepositoryLinkRequest() + ) + 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 = developer_connect.DeleteGitRepositoryLinkRequest() + 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_git_repository_link( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_git_repository_links_rest_bad_request( + request_type=developer_connect.ListGitRepositoryLinksRequest, +): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/connections/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_git_repository_links(request) + + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.ListGitRepositoryLinksRequest, + dict, + ], +) +def test_list_git_repository_links_rest_call_success(request_type): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/connections/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 = developer_connect.ListGitRepositoryLinksResponse( + 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 = developer_connect.ListGitRepositoryLinksResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_git_repository_links(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListGitRepositoryLinksPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_git_repository_links_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), + ) + client = DeveloperConnectClient(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.DeveloperConnectRestInterceptor, "post_list_git_repository_links" + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_list_git_repository_links_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "pre_list_git_repository_links" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.ListGitRepositoryLinksRequest.pb( + developer_connect.ListGitRepositoryLinksRequest() + ) + 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 = developer_connect.ListGitRepositoryLinksResponse.to_json( + developer_connect.ListGitRepositoryLinksResponse() + ) + req.return_value.content = return_value + + request = developer_connect.ListGitRepositoryLinksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = developer_connect.ListGitRepositoryLinksResponse() + post_with_metadata.return_value = ( + developer_connect.ListGitRepositoryLinksResponse(), + metadata, ) - await client.fetch_self(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FetchSelfRequest() - assert args[0] == request_msg + client.list_git_repository_links( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -# 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_self_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", - ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_self), "__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_self(request=None) +def test_get_git_repository_link_rest_bad_request( + request_type=developer_connect.GetGitRepositoryLinkRequest, +): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } + request = request_type(**request_init) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.DeleteSelfRequest() - assert args[0] == request_msg + # 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_git_repository_link(request) -# 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_o_auth_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.GetGitRepositoryLinkRequest, + dict, + ], +) +def test_get_git_repository_link_rest_call_success(request_type): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.start_o_auth), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.StartOAuthResponse( - ticket="ticket_value", - code_challenge="code_challenge_value", - code_challenge_method="code_challenge_method_value", - client_id="client_id_value", - scopes=["scopes_value"], - auth_uri="auth_uri_value", - ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.GitRepositoryLink( + name="name_value", + clone_uri="clone_uri_value", + etag="etag_value", + reconciling=True, + uid="uid_value", + webhook_id="webhook_id_value", + git_proxy_uri="git_proxy_uri_value", ) - await client.start_o_auth(request=None) - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.StartOAuthRequest() - assert args[0] == request_msg + # 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 = developer_connect.GitRepositoryLink.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.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_git_repository_link(request) -# 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_o_auth_empty_call_grpc_asyncio(): - client = DeveloperConnectAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + # Establish that the response is the type that we expect. + assert isinstance(response, developer_connect.GitRepositoryLink) + assert response.name == "name_value" + assert response.clone_uri == "clone_uri_value" + assert response.etag == "etag_value" + assert response.reconciling is True + assert response.uid == "uid_value" + assert response.webhook_id == "webhook_id_value" + assert response.git_proxy_uri == "git_proxy_uri_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_git_repository_link_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), ) + client = DeveloperConnectClient(transport=transport) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.finish_o_auth), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - developer_connect.FinishOAuthResponse() + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "post_get_git_repository_link" + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_get_git_repository_link_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, "pre_get_git_repository_link" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.GetGitRepositoryLinkRequest.pb( + developer_connect.GetGitRepositoryLinkRequest() ) - await client.finish_o_auth(request=None) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = developer_connect.FinishOAuthRequest() - assert args[0] == request_msg + 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 = developer_connect.GitRepositoryLink.to_json( + developer_connect.GitRepositoryLink() + ) + req.return_value.content = return_value + request = developer_connect.GetGitRepositoryLinkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = developer_connect.GitRepositoryLink() + post_with_metadata.return_value = ( + developer_connect.GitRepositoryLink(), + metadata, + ) -def test_transport_kind_rest(): - transport = DeveloperConnectClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + client.get_git_repository_link( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_connections_rest_bad_request( - request_type=developer_connect.ListConnectionsRequest, +def test_fetch_read_write_token_rest_bad_request( + request_type=developer_connect.FetchReadWriteTokenRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -17978,31 +26418,33 @@ def test_list_connections_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_connections(request) + client.fetch_read_write_token(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.ListConnectionsRequest, + developer_connect.FetchReadWriteTokenRequest, dict, ], ) -def test_list_connections_rest_call_success(request_type): +def test_fetch_read_write_token_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.ListConnectionsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = developer_connect.FetchReadWriteTokenResponse( + token="token_value", + git_username="git_username_value", ) # Wrap the value into a proper Response obj @@ -18010,21 +26452,21 @@ def test_list_connections_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.ListConnectionsResponse.pb(return_value) + return_value = developer_connect.FetchReadWriteTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_connections(request) + response = client.fetch_read_write_token(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListConnectionsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, developer_connect.FetchReadWriteTokenResponse) + assert response.token == "token_value" + assert response.git_username == "git_username_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_connections_rest_interceptors(null_interceptor): +def test_fetch_read_write_token_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18037,21 +26479,21 @@ def test_list_connections_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.DeveloperConnectRestInterceptor, "post_list_connections" + transports.DeveloperConnectRestInterceptor, "post_fetch_read_write_token" ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_list_connections_with_metadata", + "post_fetch_read_write_token_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_list_connections" + transports.DeveloperConnectRestInterceptor, "pre_fetch_read_write_token" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.ListConnectionsRequest.pb( - developer_connect.ListConnectionsRequest() + pb_message = developer_connect.FetchReadWriteTokenRequest.pb( + developer_connect.FetchReadWriteTokenRequest() ) transcode.return_value = { "method": "post", @@ -18063,24 +26505,24 @@ def test_list_connections_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 = developer_connect.ListConnectionsResponse.to_json( - developer_connect.ListConnectionsResponse() + return_value = developer_connect.FetchReadWriteTokenResponse.to_json( + developer_connect.FetchReadWriteTokenResponse() ) req.return_value.content = return_value - request = developer_connect.ListConnectionsRequest() + request = developer_connect.FetchReadWriteTokenRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = developer_connect.ListConnectionsResponse() + post.return_value = developer_connect.FetchReadWriteTokenResponse() post_with_metadata.return_value = ( - developer_connect.ListConnectionsResponse(), + developer_connect.FetchReadWriteTokenResponse(), metadata, ) - client.list_connections( + client.fetch_read_write_token( request, metadata=[ ("key", "val"), @@ -18093,14 +26535,16 @@ def test_list_connections_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_connection_rest_bad_request( - request_type=developer_connect.GetConnectionRequest, +def test_fetch_read_token_rest_bad_request( + request_type=developer_connect.FetchReadTokenRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/connections/sample3"} + request_init = { + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18116,34 +26560,33 @@ def test_get_connection_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_connection(request) + client.fetch_read_token(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.GetConnectionRequest, + developer_connect.FetchReadTokenRequest, dict, ], ) -def test_get_connection_rest_call_success(request_type): +def test_fetch_read_token_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/connections/sample3"} + request_init = { + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.Connection( - name="name_value", - disabled=True, - reconciling=True, - etag="etag_value", - uid="uid_value", + return_value = developer_connect.FetchReadTokenResponse( + token="token_value", + git_username="git_username_value", ) # Wrap the value into a proper Response obj @@ -18151,24 +26594,21 @@ def test_get_connection_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.Connection.pb(return_value) + return_value = developer_connect.FetchReadTokenResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_connection(request) + response = client.fetch_read_token(request) # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.Connection) - assert response.name == "name_value" - assert response.disabled is True - assert response.reconciling is True - assert response.etag == "etag_value" - assert response.uid == "uid_value" + assert isinstance(response, developer_connect.FetchReadTokenResponse) + assert response.token == "token_value" + assert response.git_username == "git_username_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_connection_rest_interceptors(null_interceptor): +def test_fetch_read_token_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18181,21 +26621,21 @@ def test_get_connection_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.DeveloperConnectRestInterceptor, "post_get_connection" + transports.DeveloperConnectRestInterceptor, "post_fetch_read_token" ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_get_connection_with_metadata", + "post_fetch_read_token_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_get_connection" + transports.DeveloperConnectRestInterceptor, "pre_fetch_read_token" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.GetConnectionRequest.pb( - developer_connect.GetConnectionRequest() + pb_message = developer_connect.FetchReadTokenRequest.pb( + developer_connect.FetchReadTokenRequest() ) transcode.return_value = { "method": "post", @@ -18207,21 +26647,24 @@ def test_get_connection_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 = developer_connect.Connection.to_json( - developer_connect.Connection() + return_value = developer_connect.FetchReadTokenResponse.to_json( + developer_connect.FetchReadTokenResponse() ) req.return_value.content = return_value - request = developer_connect.GetConnectionRequest() + request = developer_connect.FetchReadTokenRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = developer_connect.Connection() - post_with_metadata.return_value = developer_connect.Connection(), metadata + post.return_value = developer_connect.FetchReadTokenResponse() + post_with_metadata.return_value = ( + developer_connect.FetchReadTokenResponse(), + metadata, + ) - client.get_connection( + client.fetch_read_token( request, metadata=[ ("key", "val"), @@ -18234,14 +26677,16 @@ def test_get_connection_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_connection_rest_bad_request( - request_type=developer_connect.CreateConnectionRequest, +def test_open_git_repository_link_pull_request_rest_bad_request( + request_type=developer_connect.OpenGitRepositoryLinkPullRequestRequest, ): client = DeveloperConnectClient( 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/connections/sample3/gitRepositoryLinks/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18257,201 +26702,69 @@ def test_create_connection_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_connection(request) + client.open_git_repository_link_pull_request(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.CreateConnectionRequest, + developer_connect.OpenGitRepositoryLinkPullRequestRequest, dict, ], ) -def test_create_connection_rest_call_success(request_type): +def test_open_git_repository_link_pull_request_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["connection"] = { - "github_config": { - "github_app": 1, - "authorizer_credential": { - "oauth_token_secret_version": "oauth_token_secret_version_value", - "username": "username_value", - }, - "app_installation_id": 2014, - "installation_uri": "installation_uri_value", - }, - "github_enterprise_config": { - "host_uri": "host_uri_value", - "app_id": 621, - "app_slug": "app_slug_value", - "private_key_secret_version": "private_key_secret_version_value", - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "app_installation_id": 2014, - "installation_uri": "installation_uri_value", - "service_directory_config": {"service": "service_value"}, - "server_version": "server_version_value", - "ssl_ca_certificate": "ssl_ca_certificate_value", - "organization": "organization_value", - }, - "gitlab_config": { - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "read_authorizer_credential": { - "user_token_secret_version": "user_token_secret_version_value", - "username": "username_value", - }, - "authorizer_credential": {}, - }, - "gitlab_enterprise_config": { - "host_uri": "host_uri_value", - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "read_authorizer_credential": {}, - "authorizer_credential": {}, - "service_directory_config": {}, - "ssl_ca_certificate": "ssl_ca_certificate_value", - "server_version": "server_version_value", - }, - "bitbucket_data_center_config": { - "host_uri": "host_uri_value", - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "read_authorizer_credential": {}, - "authorizer_credential": {}, - "service_directory_config": {}, - "ssl_ca_certificate": "ssl_ca_certificate_value", - "server_version": "server_version_value", - }, - "bitbucket_cloud_config": { - "workspace": "workspace_value", - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "read_authorizer_credential": {}, - "authorizer_credential": {}, - }, - "secure_source_manager_instance_config": {"instance": "instance_value"}, - "http_config": { - "basic_authentication": { - "password_secret_version": "password_secret_version_value", - "username": "username_value", - }, - "bearer_token_authentication": { - "token_secret_version": "token_secret_version_value" - }, - "host_uri": "host_uri_value", - "service_directory_config": {}, - "ssl_ca_certificate": "ssl_ca_certificate_value", - }, - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "installation_state": { - "stage": 1, - "message": "message_value", - "action_uri": "action_uri_value", - }, - "disabled": True, - "reconciling": True, - "annotations": {}, - "etag": "etag_value", - "uid": "uid_value", - "crypto_key_config": {"key_reference": "key_reference_value"}, - "git_proxy_config": { - "enabled": True, - "http_proxy_base_uri": "http_proxy_base_uri_value", - }, + request_init = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.CreateConnectionRequest.meta.fields["connection"] - - 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["connection"].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["connection"][field])): - del request_init["connection"][field][i][subfield] - else: - del request_init["connection"][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") + return_value = developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_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 = developer_connect.PullRequest.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_connection(request) + response = client.open_git_repository_link_pull_request(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, developer_connect.PullRequest) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.body == "body_value" + assert response.head_ref == "head_ref_value" + assert response.base_ref == "base_ref_value" + assert response.author == "author_value" + assert response.state == developer_connect.PullRequest.State.OPEN + assert response.mergeability == developer_connect.PullRequest.Mergeability.MERGEABLE + assert response.html_url == "html_url_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_connection_rest_interceptors(null_interceptor): +def test_open_git_repository_link_pull_request_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18463,23 +26776,24 @@ def test_create_connection_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.DeveloperConnectRestInterceptor, "post_create_connection" + transports.DeveloperConnectRestInterceptor, + "post_open_git_repository_link_pull_request", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_create_connection_with_metadata", + "post_open_git_repository_link_pull_request_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_create_connection" + transports.DeveloperConnectRestInterceptor, + "pre_open_git_repository_link_pull_request", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.CreateConnectionRequest.pb( - developer_connect.CreateConnectionRequest() + pb_message = developer_connect.OpenGitRepositoryLinkPullRequestRequest.pb( + developer_connect.OpenGitRepositoryLinkPullRequestRequest() ) transcode.return_value = { "method": "post", @@ -18491,19 +26805,21 @@ def test_create_connection_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 = developer_connect.PullRequest.to_json( + developer_connect.PullRequest() + ) req.return_value.content = return_value - request = developer_connect.CreateConnectionRequest() + request = developer_connect.OpenGitRepositoryLinkPullRequestRequest() 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 = developer_connect.PullRequest() + post_with_metadata.return_value = developer_connect.PullRequest(), metadata - client.create_connection( + client.open_git_repository_link_pull_request( request, metadata=[ ("key", "val"), @@ -18516,15 +26832,15 @@ def test_create_connection_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_connection_rest_bad_request( - request_type=developer_connect.UpdateConnectionRequest, +def test_fetch_linkable_git_repositories_rest_bad_request( + request_type=developer_connect.FetchLinkableGitRepositoriesRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "connection": {"name": "projects/sample1/locations/sample2/connections/sample3"} + "connection": "projects/sample1/locations/sample2/connections/sample3" } request = request_type(**request_init) @@ -18541,203 +26857,196 @@ def test_update_connection_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_connection(request) + client.fetch_linkable_git_repositories(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.UpdateConnectionRequest, + developer_connect.FetchLinkableGitRepositoriesRequest, dict, ], ) -def test_update_connection_rest_call_success(request_type): +def test_fetch_linkable_git_repositories_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "connection": {"name": "projects/sample1/locations/sample2/connections/sample3"} - } - request_init["connection"] = { - "github_config": { - "github_app": 1, - "authorizer_credential": { - "oauth_token_secret_version": "oauth_token_secret_version_value", - "username": "username_value", - }, - "app_installation_id": 2014, - "installation_uri": "installation_uri_value", - }, - "github_enterprise_config": { - "host_uri": "host_uri_value", - "app_id": 621, - "app_slug": "app_slug_value", - "private_key_secret_version": "private_key_secret_version_value", - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "app_installation_id": 2014, - "installation_uri": "installation_uri_value", - "service_directory_config": {"service": "service_value"}, - "server_version": "server_version_value", - "ssl_ca_certificate": "ssl_ca_certificate_value", - "organization": "organization_value", - }, - "gitlab_config": { - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "read_authorizer_credential": { - "user_token_secret_version": "user_token_secret_version_value", - "username": "username_value", - }, - "authorizer_credential": {}, - }, - "gitlab_enterprise_config": { - "host_uri": "host_uri_value", - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "read_authorizer_credential": {}, - "authorizer_credential": {}, - "service_directory_config": {}, - "ssl_ca_certificate": "ssl_ca_certificate_value", - "server_version": "server_version_value", - }, - "bitbucket_data_center_config": { - "host_uri": "host_uri_value", - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "read_authorizer_credential": {}, - "authorizer_credential": {}, - "service_directory_config": {}, - "ssl_ca_certificate": "ssl_ca_certificate_value", - "server_version": "server_version_value", - }, - "bitbucket_cloud_config": { - "workspace": "workspace_value", - "webhook_secret_secret_version": "webhook_secret_secret_version_value", - "read_authorizer_credential": {}, - "authorizer_credential": {}, - }, - "secure_source_manager_instance_config": {"instance": "instance_value"}, - "http_config": { - "basic_authentication": { - "password_secret_version": "password_secret_version_value", - "username": "username_value", - }, - "bearer_token_authentication": { - "token_secret_version": "token_secret_version_value" - }, - "host_uri": "host_uri_value", - "service_directory_config": {}, - "ssl_ca_certificate": "ssl_ca_certificate_value", - }, - "name": "projects/sample1/locations/sample2/connections/sample3", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "installation_state": { - "stage": 1, - "message": "message_value", - "action_uri": "action_uri_value", - }, - "disabled": True, - "reconciling": True, - "annotations": {}, - "etag": "etag_value", - "uid": "uid_value", - "crypto_key_config": {"key_reference": "key_reference_value"}, - "git_proxy_config": { - "enabled": True, - "http_proxy_base_uri": "http_proxy_base_uri_value", - }, + "connection": "projects/sample1/locations/sample2/connections/sample3" } - # 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 = developer_connect.UpdateConnectionRequest.meta.fields["connection"] + # 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 = developer_connect.FetchLinkableGitRepositoriesResponse( + next_page_token="next_page_token_value", + ) - 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 - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Convert return value to protobuf type + return_value = developer_connect.FetchLinkableGitRepositoriesResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + response_value.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.fetch_linkable_git_repositories(request) - 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 + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.FetchLinkableGitRepositoriesPager) + assert response.next_page_token == "next_page_token_value" - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_fetch_linkable_git_repositories_rest_interceptors(null_interceptor): + transport = transports.DeveloperConnectRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DeveloperConnectRestInterceptor(), + ) + client = DeveloperConnectClient(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.DeveloperConnectRestInterceptor, + "post_fetch_linkable_git_repositories", + ) as post, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "post_fetch_linkable_git_repositories_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.DeveloperConnectRestInterceptor, + "pre_fetch_linkable_git_repositories", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = developer_connect.FetchLinkableGitRepositoriesRequest.pb( + developer_connect.FetchLinkableGitRepositoriesRequest() + ) + 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 = developer_connect.FetchLinkableGitRepositoriesResponse.to_json( + developer_connect.FetchLinkableGitRepositoriesResponse() + ) + req.return_value.content = return_value + + request = developer_connect.FetchLinkableGitRepositoriesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() + post_with_metadata.return_value = ( + developer_connect.FetchLinkableGitRepositoriesResponse(), + metadata, + ) + + client.fetch_linkable_git_repositories( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_fetch_git_hub_installations_rest_bad_request( + request_type=developer_connect.FetchGitHubInstallationsRequest, +): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "connection": "projects/sample1/locations/sample2/connections/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.fetch_git_hub_installations(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["connection"].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", + [ + developer_connect.FetchGitHubInstallationsRequest, + dict, + ], +) +def test_fetch_git_hub_installations_rest_call_success(request_type): + client = DeveloperConnectClient( + 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["connection"][field])): - del request_init["connection"][field][i][subfield] - else: - del request_init["connection"][field][subfield] + # send a request that will satisfy transcoding + request_init = { + "connection": "projects/sample1/locations/sample2/connections/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") + return_value = developer_connect.FetchGitHubInstallationsResponse() # 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 = developer_connect.FetchGitHubInstallationsResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_connection(request) + response = client.fetch_git_hub_installations(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, developer_connect.FetchGitHubInstallationsResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_connection_rest_interceptors(null_interceptor): +def test_fetch_git_hub_installations_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18749,23 +27058,24 @@ def test_update_connection_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.DeveloperConnectRestInterceptor, "post_update_connection" + transports.DeveloperConnectRestInterceptor, + "post_fetch_git_hub_installations", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_update_connection_with_metadata", + "post_fetch_git_hub_installations_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_update_connection" + transports.DeveloperConnectRestInterceptor, + "pre_fetch_git_hub_installations", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.UpdateConnectionRequest.pb( - developer_connect.UpdateConnectionRequest() + pb_message = developer_connect.FetchGitHubInstallationsRequest.pb( + developer_connect.FetchGitHubInstallationsRequest() ) transcode.return_value = { "method": "post", @@ -18777,19 +27087,24 @@ def test_update_connection_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 = developer_connect.FetchGitHubInstallationsResponse.to_json( + developer_connect.FetchGitHubInstallationsResponse() + ) req.return_value.content = return_value - request = developer_connect.UpdateConnectionRequest() + request = developer_connect.FetchGitHubInstallationsRequest() 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 = developer_connect.FetchGitHubInstallationsResponse() + post_with_metadata.return_value = ( + developer_connect.FetchGitHubInstallationsResponse(), + metadata, + ) - client.update_connection( + client.fetch_git_hub_installations( request, metadata=[ ("key", "val"), @@ -18802,14 +27117,16 @@ def test_update_connection_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_connection_rest_bad_request( - request_type=developer_connect.DeleteConnectionRequest, +def test_fetch_git_refs_rest_bad_request( + request_type=developer_connect.FetchGitRefsRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/connections/sample3"} + request_init = { + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18825,45 +27142,55 @@ def test_delete_connection_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_connection(request) + client.fetch_git_refs(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.DeleteConnectionRequest, + developer_connect.FetchGitRefsRequest, dict, ], ) -def test_delete_connection_rest_call_success(request_type): +def test_fetch_git_refs_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/connections/sample3"} + request_init = { + "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.FetchGitRefsResponse( + ref_names=["ref_names_value"], + next_page_token="next_page_token_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 = developer_connect.FetchGitRefsResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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_connection(request) + response = client.fetch_git_refs(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, pagers.FetchGitRefsPager) + assert response.ref_names == ["ref_names_value"] + assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_connection_rest_interceptors(null_interceptor): +def test_fetch_git_refs_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -18875,23 +27202,22 @@ def test_delete_connection_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.DeveloperConnectRestInterceptor, "post_delete_connection" + transports.DeveloperConnectRestInterceptor, "post_fetch_git_refs" ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_delete_connection_with_metadata", + "post_fetch_git_refs_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_delete_connection" + transports.DeveloperConnectRestInterceptor, "pre_fetch_git_refs" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.DeleteConnectionRequest.pb( - developer_connect.DeleteConnectionRequest() + pb_message = developer_connect.FetchGitRefsRequest.pb( + developer_connect.FetchGitRefsRequest() ) transcode.return_value = { "method": "post", @@ -18903,19 +27229,24 @@ def test_delete_connection_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 = developer_connect.FetchGitRefsResponse.to_json( + developer_connect.FetchGitRefsResponse() + ) req.return_value.content = return_value - request = developer_connect.DeleteConnectionRequest() + request = developer_connect.FetchGitRefsRequest() 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 = developer_connect.FetchGitRefsResponse() + post_with_metadata.return_value = ( + developer_connect.FetchGitRefsResponse(), + metadata, + ) - client.delete_connection( + client.fetch_git_refs( request, metadata=[ ("key", "val"), @@ -18928,14 +27259,16 @@ def test_delete_connection_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_git_repository_link_rest_bad_request( - request_type=developer_connect.CreateGitRepositoryLinkRequest, +def test_diff_git_repository_link_commit_rest_bad_request( + request_type=developer_connect.DiffGitRepositoryLinkCommitRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/connections/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -18949,130 +27282,54 @@ def test_create_git_repository_link_rest_bad_request( 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_git_repository_link(request) - - -@pytest.mark.parametrize( - "request_type", - [ - developer_connect.CreateGitRepositoryLinkRequest, - dict, - ], -) -def test_create_git_repository_link_rest_call_success(request_type): - client = DeveloperConnectClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/connections/sample3"} - request_init["git_repository_link"] = { - "name": "name_value", - "clone_uri": "clone_uri_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "etag": "etag_value", - "reconciling": True, - "annotations": {}, - "uid": "uid_value", - "webhook_id": "webhook_id_value", - "git_proxy_uri": "git_proxy_uri_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 = developer_connect.CreateGitRepositoryLinkRequest.meta.fields[ - "git_repository_link" - ] - - 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["git_repository_link"].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, - } - ) + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.diff_git_repository_link_commit(request) - # 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["git_repository_link"][field])): - del request_init["git_repository_link"][field][i][subfield] - else: - del request_init["git_repository_link"][field][subfield] + +@pytest.mark.parametrize( + "request_type", + [ + developer_connect.DiffGitRepositoryLinkCommitRequest, + dict, + ], +) +def test_diff_git_repository_link_commit_rest_call_success(request_type): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.DiffGitRepositoryLinkCommitResponse() # 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 = developer_connect.DiffGitRepositoryLinkCommitResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_git_repository_link(request) + response = client.diff_git_repository_link_commit(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, developer_connect.DiffGitRepositoryLinkCommitResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_git_repository_link_rest_interceptors(null_interceptor): +def test_diff_git_repository_link_commit_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19084,24 +27341,24 @@ def test_create_git_repository_link_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.DeveloperConnectRestInterceptor, - "post_create_git_repository_link", + "post_diff_git_repository_link_commit", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_create_git_repository_link_with_metadata", + "post_diff_git_repository_link_commit_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_create_git_repository_link" + transports.DeveloperConnectRestInterceptor, + "pre_diff_git_repository_link_commit", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.CreateGitRepositoryLinkRequest.pb( - developer_connect.CreateGitRepositoryLinkRequest() + pb_message = developer_connect.DiffGitRepositoryLinkCommitRequest.pb( + developer_connect.DiffGitRepositoryLinkCommitRequest() ) transcode.return_value = { "method": "post", @@ -19113,19 +27370,24 @@ def test_create_git_repository_link_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 = developer_connect.DiffGitRepositoryLinkCommitResponse.to_json( + developer_connect.DiffGitRepositoryLinkCommitResponse() + ) req.return_value.content = return_value - request = developer_connect.CreateGitRepositoryLinkRequest() + request = developer_connect.DiffGitRepositoryLinkCommitRequest() 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 = developer_connect.DiffGitRepositoryLinkCommitResponse() + post_with_metadata.return_value = ( + developer_connect.DiffGitRepositoryLinkCommitResponse(), + metadata, + ) - client.create_git_repository_link( + client.diff_git_repository_link_commit( request, metadata=[ ("key", "val"), @@ -19138,8 +27400,8 @@ def test_create_git_repository_link_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_git_repository_link_rest_bad_request( - request_type=developer_connect.DeleteGitRepositoryLinkRequest, +def test_fetch_git_repository_link_commit_rest_bad_request( + request_type=developer_connect.FetchGitRepositoryLinkCommitRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -19163,17 +27425,17 @@ def test_delete_git_repository_link_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_git_repository_link(request) + client.fetch_git_repository_link_commit(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.DeleteGitRepositoryLinkRequest, + developer_connect.FetchGitRepositoryLinkCommitRequest, dict, ], ) -def test_delete_git_repository_link_rest_call_success(request_type): +def test_fetch_git_repository_link_commit_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -19187,23 +27449,28 @@ def test_delete_git_repository_link_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 = operations_pb2.Operation(name="operations/spam") + return_value = developer_connect.FetchGitRepositoryLinkCommitResponse() # 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 = developer_connect.FetchGitRepositoryLinkCommitResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_git_repository_link(request) + response = client.fetch_git_repository_link_commit(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, developer_connect.FetchGitRepositoryLinkCommitResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_git_repository_link_rest_interceptors(null_interceptor): +def test_fetch_git_repository_link_commit_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19215,24 +27482,24 @@ def test_delete_git_repository_link_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.DeveloperConnectRestInterceptor, - "post_delete_git_repository_link", + "post_fetch_git_repository_link_commit", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_delete_git_repository_link_with_metadata", + "post_fetch_git_repository_link_commit_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_delete_git_repository_link" + transports.DeveloperConnectRestInterceptor, + "pre_fetch_git_repository_link_commit", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.DeleteGitRepositoryLinkRequest.pb( - developer_connect.DeleteGitRepositoryLinkRequest() + pb_message = developer_connect.FetchGitRepositoryLinkCommitRequest.pb( + developer_connect.FetchGitRepositoryLinkCommitRequest() ) transcode.return_value = { "method": "post", @@ -19244,19 +27511,24 @@ def test_delete_git_repository_link_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 = developer_connect.FetchGitRepositoryLinkCommitResponse.to_json( + developer_connect.FetchGitRepositoryLinkCommitResponse() + ) req.return_value.content = return_value - request = developer_connect.DeleteGitRepositoryLinkRequest() + request = developer_connect.FetchGitRepositoryLinkCommitRequest() 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 = developer_connect.FetchGitRepositoryLinkCommitResponse() + post_with_metadata.return_value = ( + developer_connect.FetchGitRepositoryLinkCommitResponse(), + metadata, + ) - client.delete_git_repository_link( + client.fetch_git_repository_link_commit( request, metadata=[ ("key", "val"), @@ -19269,14 +27541,16 @@ def test_delete_git_repository_link_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_git_repository_links_rest_bad_request( - request_type=developer_connect.ListGitRepositoryLinksRequest, +def test_fetch_git_repository_link_commit_list_rest_bad_request( + request_type=developer_connect.FetchGitRepositoryLinkCommitListRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/connections/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -19292,31 +27566,32 @@ def test_list_git_repository_links_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_git_repository_links(request) + client.fetch_git_repository_link_commit_list(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.ListGitRepositoryLinksRequest, + developer_connect.FetchGitRepositoryLinkCommitListRequest, dict, ], ) -def test_list_git_repository_links_rest_call_success(request_type): +def test_fetch_git_repository_link_commit_list_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/connections/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.ListGitRepositoryLinksResponse( + return_value = developer_connect.FetchGitRepositoryLinkCommitListResponse( next_page_token="next_page_token_value", - unreachable=["unreachable_value"], ) # Wrap the value into a proper Response obj @@ -19324,21 +27599,22 @@ def test_list_git_repository_links_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.ListGitRepositoryLinksResponse.pb(return_value) + return_value = developer_connect.FetchGitRepositoryLinkCommitListResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_git_repository_links(request) + response = client.fetch_git_repository_link_commit_list(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListGitRepositoryLinksPager) + assert isinstance(response, pagers.FetchGitRepositoryLinkCommitListPager) assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_git_repository_links_rest_interceptors(null_interceptor): +def test_fetch_git_repository_link_commit_list_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19351,21 +27627,23 @@ def test_list_git_repository_links_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.DeveloperConnectRestInterceptor, "post_list_git_repository_links" + transports.DeveloperConnectRestInterceptor, + "post_fetch_git_repository_link_commit_list", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_list_git_repository_links_with_metadata", + "post_fetch_git_repository_link_commit_list_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_list_git_repository_links" + transports.DeveloperConnectRestInterceptor, + "pre_fetch_git_repository_link_commit_list", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.ListGitRepositoryLinksRequest.pb( - developer_connect.ListGitRepositoryLinksRequest() + pb_message = developer_connect.FetchGitRepositoryLinkCommitListRequest.pb( + developer_connect.FetchGitRepositoryLinkCommitListRequest() ) transcode.return_value = { "method": "post", @@ -19377,24 +27655,26 @@ def test_list_git_repository_links_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 = developer_connect.ListGitRepositoryLinksResponse.to_json( - developer_connect.ListGitRepositoryLinksResponse() + return_value = ( + developer_connect.FetchGitRepositoryLinkCommitListResponse.to_json( + developer_connect.FetchGitRepositoryLinkCommitListResponse() + ) ) req.return_value.content = return_value - request = developer_connect.ListGitRepositoryLinksRequest() + request = developer_connect.FetchGitRepositoryLinkCommitListRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = developer_connect.ListGitRepositoryLinksResponse() + post.return_value = developer_connect.FetchGitRepositoryLinkCommitListResponse() post_with_metadata.return_value = ( - developer_connect.ListGitRepositoryLinksResponse(), + developer_connect.FetchGitRepositoryLinkCommitListResponse(), metadata, ) - client.list_git_repository_links( + client.fetch_git_repository_link_commit_list( request, metadata=[ ("key", "val"), @@ -19407,8 +27687,8 @@ def test_list_git_repository_links_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_git_repository_link_rest_bad_request( - request_type=developer_connect.GetGitRepositoryLinkRequest, +def test_fetch_git_repository_link_file_blame_rest_bad_request( + request_type=developer_connect.FetchGitRepositoryLinkFileBlameRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -19432,17 +27712,17 @@ def test_get_git_repository_link_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_git_repository_link(request) + client.fetch_git_repository_link_file_blame(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.GetGitRepositoryLinkRequest, + developer_connect.FetchGitRepositoryLinkFileBlameRequest, dict, ], ) -def test_get_git_repository_link_rest_call_success(request_type): +def test_fetch_git_repository_link_file_blame_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -19456,41 +27736,30 @@ def test_get_git_repository_link_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 = developer_connect.GitRepositoryLink( - name="name_value", - clone_uri="clone_uri_value", - etag="etag_value", - reconciling=True, - uid="uid_value", - webhook_id="webhook_id_value", - git_proxy_uri="git_proxy_uri_value", - ) + return_value = developer_connect.FetchGitRepositoryLinkFileBlameResponse() # 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 = developer_connect.GitRepositoryLink.pb(return_value) + return_value = developer_connect.FetchGitRepositoryLinkFileBlameResponse.pb( + return_value + ) json_return_value = json_format.MessageToJson(return_value) response_value.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_git_repository_link(request) + response = client.fetch_git_repository_link_file_blame(request) # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.GitRepositoryLink) - assert response.name == "name_value" - assert response.clone_uri == "clone_uri_value" - assert response.etag == "etag_value" - assert response.reconciling is True - assert response.uid == "uid_value" - assert response.webhook_id == "webhook_id_value" - assert response.git_proxy_uri == "git_proxy_uri_value" + assert isinstance( + response, developer_connect.FetchGitRepositoryLinkFileBlameResponse + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_git_repository_link_rest_interceptors(null_interceptor): +def test_fetch_git_repository_link_file_blame_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19503,21 +27772,23 @@ def test_get_git_repository_link_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.DeveloperConnectRestInterceptor, "post_get_git_repository_link" + transports.DeveloperConnectRestInterceptor, + "post_fetch_git_repository_link_file_blame", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_get_git_repository_link_with_metadata", + "post_fetch_git_repository_link_file_blame_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_get_git_repository_link" + transports.DeveloperConnectRestInterceptor, + "pre_fetch_git_repository_link_file_blame", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.GetGitRepositoryLinkRequest.pb( - developer_connect.GetGitRepositoryLinkRequest() + pb_message = developer_connect.FetchGitRepositoryLinkFileBlameRequest.pb( + developer_connect.FetchGitRepositoryLinkFileBlameRequest() ) transcode.return_value = { "method": "post", @@ -19529,24 +27800,26 @@ def test_get_git_repository_link_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 = developer_connect.GitRepositoryLink.to_json( - developer_connect.GitRepositoryLink() + return_value = ( + developer_connect.FetchGitRepositoryLinkFileBlameResponse.to_json( + developer_connect.FetchGitRepositoryLinkFileBlameResponse() + ) ) req.return_value.content = return_value - request = developer_connect.GetGitRepositoryLinkRequest() + request = developer_connect.FetchGitRepositoryLinkFileBlameRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = developer_connect.GitRepositoryLink() + post.return_value = developer_connect.FetchGitRepositoryLinkFileBlameResponse() post_with_metadata.return_value = ( - developer_connect.GitRepositoryLink(), + developer_connect.FetchGitRepositoryLinkFileBlameResponse(), metadata, ) - client.get_git_repository_link( + client.fetch_git_repository_link_file_blame( request, metadata=[ ("key", "val"), @@ -19559,15 +27832,15 @@ def test_get_git_repository_link_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_read_write_token_rest_bad_request( - request_type=developer_connect.FetchReadWriteTokenRequest, +def test_fetch_git_repository_link_pull_request_rest_bad_request( + request_type=developer_connect.FetchGitRepositoryLinkPullRequestRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" } request = request_type(**request_init) @@ -19584,33 +27857,40 @@ def test_fetch_read_write_token_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.fetch_read_write_token(request) + client.fetch_git_repository_link_pull_request(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchReadWriteTokenRequest, + developer_connect.FetchGitRepositoryLinkPullRequestRequest, dict, ], ) -def test_fetch_read_write_token_rest_call_success(request_type): +def test_fetch_git_repository_link_pull_request_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.FetchReadWriteTokenResponse( - token="token_value", - git_username="git_username_value", + return_value = developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_value", ) # Wrap the value into a proper Response obj @@ -19618,21 +27898,28 @@ def test_fetch_read_write_token_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.FetchReadWriteTokenResponse.pb(return_value) + return_value = developer_connect.PullRequest.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.fetch_read_write_token(request) + response = client.fetch_git_repository_link_pull_request(request) # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.FetchReadWriteTokenResponse) - assert response.token == "token_value" - assert response.git_username == "git_username_value" + assert isinstance(response, developer_connect.PullRequest) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.body == "body_value" + assert response.head_ref == "head_ref_value" + assert response.base_ref == "base_ref_value" + assert response.author == "author_value" + assert response.state == developer_connect.PullRequest.State.OPEN + assert response.mergeability == developer_connect.PullRequest.Mergeability.MERGEABLE + assert response.html_url == "html_url_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_read_write_token_rest_interceptors(null_interceptor): +def test_fetch_git_repository_link_pull_request_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19645,21 +27932,23 @@ def test_fetch_read_write_token_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.DeveloperConnectRestInterceptor, "post_fetch_read_write_token" + transports.DeveloperConnectRestInterceptor, + "post_fetch_git_repository_link_pull_request", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_fetch_read_write_token_with_metadata", + "post_fetch_git_repository_link_pull_request_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_fetch_read_write_token" + transports.DeveloperConnectRestInterceptor, + "pre_fetch_git_repository_link_pull_request", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.FetchReadWriteTokenRequest.pb( - developer_connect.FetchReadWriteTokenRequest() + pb_message = developer_connect.FetchGitRepositoryLinkPullRequestRequest.pb( + developer_connect.FetchGitRepositoryLinkPullRequestRequest() ) transcode.return_value = { "method": "post", @@ -19671,24 +27960,21 @@ def test_fetch_read_write_token_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 = developer_connect.FetchReadWriteTokenResponse.to_json( - developer_connect.FetchReadWriteTokenResponse() + return_value = developer_connect.PullRequest.to_json( + developer_connect.PullRequest() ) req.return_value.content = return_value - request = developer_connect.FetchReadWriteTokenRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = developer_connect.FetchReadWriteTokenResponse() - post_with_metadata.return_value = ( - developer_connect.FetchReadWriteTokenResponse(), - metadata, - ) + post.return_value = developer_connect.PullRequest() + post_with_metadata.return_value = developer_connect.PullRequest(), metadata - client.fetch_read_write_token( + client.fetch_git_repository_link_pull_request( request, metadata=[ ("key", "val"), @@ -19701,15 +27987,15 @@ def test_fetch_read_write_token_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_read_token_rest_bad_request( - request_type=developer_connect.FetchReadTokenRequest, +def test_add_git_repository_link_pull_request_comment_rest_bad_request( + request_type=developer_connect.AddGitRepositoryLinkPullRequestCommentRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" } request = request_type(**request_init) @@ -19726,33 +28012,34 @@ def test_fetch_read_token_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.fetch_read_token(request) + client.add_git_repository_link_pull_request_comment(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchReadTokenRequest, + developer_connect.AddGitRepositoryLinkPullRequestCommentRequest, dict, ], ) -def test_fetch_read_token_rest_call_success(request_type): +def test_add_git_repository_link_pull_request_comment_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.FetchReadTokenResponse( - token="token_value", - git_username="git_username_value", + return_value = developer_connect.PullRequestComment( + id="id_value", + body="body_value", + author="author_value", ) # Wrap the value into a proper Response obj @@ -19760,21 +28047,24 @@ def test_fetch_read_token_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.FetchReadTokenResponse.pb(return_value) + return_value = developer_connect.PullRequestComment.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.fetch_read_token(request) + response = client.add_git_repository_link_pull_request_comment(request) # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.FetchReadTokenResponse) - assert response.token == "token_value" - assert response.git_username == "git_username_value" + assert isinstance(response, developer_connect.PullRequestComment) + assert response.id == "id_value" + assert response.body == "body_value" + assert response.author == "author_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_read_token_rest_interceptors(null_interceptor): +def test_add_git_repository_link_pull_request_comment_rest_interceptors( + null_interceptor, +): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19787,21 +28077,23 @@ def test_fetch_read_token_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.DeveloperConnectRestInterceptor, "post_fetch_read_token" + transports.DeveloperConnectRestInterceptor, + "post_add_git_repository_link_pull_request_comment", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_fetch_read_token_with_metadata", + "post_add_git_repository_link_pull_request_comment_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_fetch_read_token" + transports.DeveloperConnectRestInterceptor, + "pre_add_git_repository_link_pull_request_comment", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.FetchReadTokenRequest.pb( - developer_connect.FetchReadTokenRequest() + pb_message = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest.pb( + developer_connect.AddGitRepositoryLinkPullRequestCommentRequest() ) transcode.return_value = { "method": "post", @@ -19813,24 +28105,24 @@ def test_fetch_read_token_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 = developer_connect.FetchReadTokenResponse.to_json( - developer_connect.FetchReadTokenResponse() + return_value = developer_connect.PullRequestComment.to_json( + developer_connect.PullRequestComment() ) req.return_value.content = return_value - request = developer_connect.FetchReadTokenRequest() + request = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = developer_connect.FetchReadTokenResponse() + post.return_value = developer_connect.PullRequestComment() post_with_metadata.return_value = ( - developer_connect.FetchReadTokenResponse(), + developer_connect.PullRequestComment(), metadata, ) - client.fetch_read_token( + client.add_git_repository_link_pull_request_comment( request, metadata=[ ("key", "val"), @@ -19843,15 +28135,15 @@ def test_fetch_read_token_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_linkable_git_repositories_rest_bad_request( - request_type=developer_connect.FetchLinkableGitRepositoriesRequest, +def test_add_git_repository_link_pull_request_review_comment_rest_bad_request( + request_type=developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "connection": "projects/sample1/locations/sample2/connections/sample3" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" } request = request_type(**request_init) @@ -19868,32 +28160,41 @@ def test_fetch_linkable_git_repositories_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.fetch_linkable_git_repositories(request) + client.add_git_repository_link_pull_request_review_comment(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchLinkableGitRepositoriesRequest, + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest, dict, ], ) -def test_fetch_linkable_git_repositories_rest_call_success(request_type): +def test_add_git_repository_link_pull_request_review_comment_rest_call_success( + request_type, +): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "connection": "projects/sample1/locations/sample2/connections/sample3" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.FetchLinkableGitRepositoriesResponse( - next_page_token="next_page_token_value", + return_value = developer_connect.PullRequestReviewComment( + id="id_value", + body="body_value", + path="path_value", + first_line=1071, + last_line=955, + side=developer_connect.PullRequestReviewComment.DiffSide.BASE, + author="author_value", + commit_id="commit_id_value", ) # Wrap the value into a proper Response obj @@ -19901,22 +28202,29 @@ def test_fetch_linkable_git_repositories_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.FetchLinkableGitRepositoriesResponse.pb( - return_value - ) + return_value = developer_connect.PullRequestReviewComment.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.fetch_linkable_git_repositories(request) + response = client.add_git_repository_link_pull_request_review_comment(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchLinkableGitRepositoriesPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, developer_connect.PullRequestReviewComment) + assert response.id == "id_value" + assert response.body == "body_value" + assert response.path == "path_value" + assert response.first_line == 1071 + assert response.last_line == 955 + assert response.side == developer_connect.PullRequestReviewComment.DiffSide.BASE + assert response.author == "author_value" + assert response.commit_id == "commit_id_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_linkable_git_repositories_rest_interceptors(null_interceptor): +def test_add_git_repository_link_pull_request_review_comment_rest_interceptors( + null_interceptor, +): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -19930,22 +28238,24 @@ def test_fetch_linkable_git_repositories_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_fetch_linkable_git_repositories", + "post_add_git_repository_link_pull_request_review_comment", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_fetch_linkable_git_repositories_with_metadata", + "post_add_git_repository_link_pull_request_review_comment_with_metadata", ) as post_with_metadata, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "pre_fetch_linkable_git_repositories", + "pre_add_git_repository_link_pull_request_review_comment", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.FetchLinkableGitRepositoriesRequest.pb( - developer_connect.FetchLinkableGitRepositoriesRequest() + pb_message = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest.pb( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest() + ) ) transcode.return_value = { "method": "post", @@ -19956,25 +28266,27 @@ def test_fetch_linkable_git_repositories_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 = developer_connect.FetchLinkableGitRepositoriesResponse.to_json( - developer_connect.FetchLinkableGitRepositoriesResponse() + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = developer_connect.PullRequestReviewComment.to_json( + developer_connect.PullRequestReviewComment() ) req.return_value.content = return_value - request = developer_connect.FetchLinkableGitRepositoriesRequest() + request = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest() + ) metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = developer_connect.FetchLinkableGitRepositoriesResponse() + post.return_value = developer_connect.PullRequestReviewComment() post_with_metadata.return_value = ( - developer_connect.FetchLinkableGitRepositoriesResponse(), + developer_connect.PullRequestReviewComment(), metadata, ) - client.fetch_linkable_git_repositories( + client.add_git_repository_link_pull_request_review_comment( request, metadata=[ ("key", "val"), @@ -19987,15 +28299,15 @@ def test_fetch_linkable_git_repositories_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_git_hub_installations_rest_bad_request( - request_type=developer_connect.FetchGitHubInstallationsRequest, +def test_modify_git_repository_link_pull_request_rest_bad_request( + request_type=developer_connect.ModifyGitRepositoryLinkPullRequestRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "connection": "projects/sample1/locations/sample2/connections/sample3" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" } request = request_type(**request_init) @@ -20012,52 +28324,69 @@ def test_fetch_git_hub_installations_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.fetch_git_hub_installations(request) + client.modify_git_repository_link_pull_request(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchGitHubInstallationsRequest, + developer_connect.ModifyGitRepositoryLinkPullRequestRequest, dict, ], ) -def test_fetch_git_hub_installations_rest_call_success(request_type): +def test_modify_git_repository_link_pull_request_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "connection": "projects/sample1/locations/sample2/connections/sample3" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.FetchGitHubInstallationsResponse() + return_value = developer_connect.PullRequest( + id="id_value", + title="title_value", + body="body_value", + head_ref="head_ref_value", + base_ref="base_ref_value", + author="author_value", + state=developer_connect.PullRequest.State.OPEN, + mergeability=developer_connect.PullRequest.Mergeability.MERGEABLE, + html_url="html_url_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 = developer_connect.FetchGitHubInstallationsResponse.pb( - return_value - ) + return_value = developer_connect.PullRequest.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.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.fetch_git_hub_installations(request) + response = client.modify_git_repository_link_pull_request(request) # Establish that the response is the type that we expect. - assert isinstance(response, developer_connect.FetchGitHubInstallationsResponse) + assert isinstance(response, developer_connect.PullRequest) + assert response.id == "id_value" + assert response.title == "title_value" + assert response.body == "body_value" + assert response.head_ref == "head_ref_value" + assert response.base_ref == "base_ref_value" + assert response.author == "author_value" + assert response.state == developer_connect.PullRequest.State.OPEN + assert response.mergeability == developer_connect.PullRequest.Mergeability.MERGEABLE + assert response.html_url == "html_url_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_git_hub_installations_rest_interceptors(null_interceptor): +def test_modify_git_repository_link_pull_request_rest_interceptors(null_interceptor): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20071,22 +28400,22 @@ def test_fetch_git_hub_installations_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_fetch_git_hub_installations", + "post_modify_git_repository_link_pull_request", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_fetch_git_hub_installations_with_metadata", + "post_modify_git_repository_link_pull_request_with_metadata", ) as post_with_metadata, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "pre_fetch_git_hub_installations", + "pre_modify_git_repository_link_pull_request", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.FetchGitHubInstallationsRequest.pb( - developer_connect.FetchGitHubInstallationsRequest() + pb_message = developer_connect.ModifyGitRepositoryLinkPullRequestRequest.pb( + developer_connect.ModifyGitRepositoryLinkPullRequestRequest() ) transcode.return_value = { "method": "post", @@ -20098,24 +28427,21 @@ def test_fetch_git_hub_installations_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 = developer_connect.FetchGitHubInstallationsResponse.to_json( - developer_connect.FetchGitHubInstallationsResponse() + return_value = developer_connect.PullRequest.to_json( + developer_connect.PullRequest() ) req.return_value.content = return_value - request = developer_connect.FetchGitHubInstallationsRequest() + request = developer_connect.ModifyGitRepositoryLinkPullRequestRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = developer_connect.FetchGitHubInstallationsResponse() - post_with_metadata.return_value = ( - developer_connect.FetchGitHubInstallationsResponse(), - metadata, - ) + post.return_value = developer_connect.PullRequest() + post_with_metadata.return_value = developer_connect.PullRequest(), metadata - client.fetch_git_hub_installations( + client.modify_git_repository_link_pull_request( request, metadata=[ ("key", "val"), @@ -20128,15 +28454,15 @@ def test_fetch_git_hub_installations_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_fetch_git_refs_rest_bad_request( - request_type=developer_connect.FetchGitRefsRequest, +def test_fetch_git_repository_link_pull_request_list_rest_bad_request( + request_type=developer_connect.FetchGitRepositoryLinkPullRequestListRequest, ): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" } request = request_type(**request_init) @@ -20153,32 +28479,31 @@ def test_fetch_git_refs_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.fetch_git_refs(request) + client.fetch_git_repository_link_pull_request_list(request) @pytest.mark.parametrize( "request_type", [ - developer_connect.FetchGitRefsRequest, + developer_connect.FetchGitRepositoryLinkPullRequestListRequest, dict, ], ) -def test_fetch_git_refs_rest_call_success(request_type): +def test_fetch_git_repository_link_pull_request_list_rest_call_success(request_type): client = DeveloperConnectClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "git_repository_link": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/sample4" + "name": "projects/sample1/locations/sample2/connections/sample3/gitRepositoryLinks/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 = developer_connect.FetchGitRefsResponse( - ref_names=["ref_names_value"], + return_value = developer_connect.FetchGitRepositoryLinkPullRequestListResponse( next_page_token="next_page_token_value", ) @@ -20187,21 +28512,26 @@ def test_fetch_git_refs_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = developer_connect.FetchGitRefsResponse.pb(return_value) + return_value = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse.pb( + return_value + ) + ) json_return_value = json_format.MessageToJson(return_value) response_value.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.fetch_git_refs(request) + response = client.fetch_git_repository_link_pull_request_list(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.FetchGitRefsPager) - assert response.ref_names == ["ref_names_value"] + assert isinstance(response, pagers.FetchGitRepositoryLinkPullRequestListPager) assert response.next_page_token == "next_page_token_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_fetch_git_refs_rest_interceptors(null_interceptor): +def test_fetch_git_repository_link_pull_request_list_rest_interceptors( + null_interceptor, +): transport = transports.DeveloperConnectRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -20214,21 +28544,23 @@ def test_fetch_git_refs_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.DeveloperConnectRestInterceptor, "post_fetch_git_refs" + transports.DeveloperConnectRestInterceptor, + "post_fetch_git_repository_link_pull_request_list", ) as post, mock.patch.object( transports.DeveloperConnectRestInterceptor, - "post_fetch_git_refs_with_metadata", + "post_fetch_git_repository_link_pull_request_list_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.DeveloperConnectRestInterceptor, "pre_fetch_git_refs" + transports.DeveloperConnectRestInterceptor, + "pre_fetch_git_repository_link_pull_request_list", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = developer_connect.FetchGitRefsRequest.pb( - developer_connect.FetchGitRefsRequest() + pb_message = developer_connect.FetchGitRepositoryLinkPullRequestListRequest.pb( + developer_connect.FetchGitRepositoryLinkPullRequestListRequest() ) transcode.return_value = { "method": "post", @@ -20240,24 +28572,28 @@ def test_fetch_git_refs_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 = developer_connect.FetchGitRefsResponse.to_json( - developer_connect.FetchGitRefsResponse() + return_value = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse.to_json( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse() + ) ) req.return_value.content = return_value - request = developer_connect.FetchGitRefsRequest() + request = developer_connect.FetchGitRepositoryLinkPullRequestListRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = developer_connect.FetchGitRefsResponse() + post.return_value = ( + developer_connect.FetchGitRepositoryLinkPullRequestListResponse() + ) post_with_metadata.return_value = ( - developer_connect.FetchGitRefsResponse(), + developer_connect.FetchGitRepositoryLinkPullRequestListResponse(), metadata, ) - client.fetch_git_refs( + client.fetch_git_repository_link_pull_request_list( request, metadata=[ ("key", "val"), @@ -22666,6 +31002,27 @@ def test_fetch_read_token_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_open_git_repository_link_pull_request_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.open_git_repository_link_pull_request), "__call__" + ) as call: + client.open_git_repository_link_pull_request(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.OpenGitRepositoryLinkPullRequestRequest() + 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_fetch_linkable_git_repositories_empty_call_rest(): @@ -22727,6 +31084,198 @@ def test_fetch_git_refs_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_diff_git_repository_link_commit_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.diff_git_repository_link_commit), "__call__" + ) as call: + client.diff_git_repository_link_commit(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.DiffGitRepositoryLinkCommitRequest() + 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_fetch_git_repository_link_commit_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_commit), "__call__" + ) as call: + client.fetch_git_repository_link_commit(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkCommitRequest() + 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_fetch_git_repository_link_commit_list_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_commit_list), "__call__" + ) as call: + client.fetch_git_repository_link_commit_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkCommitListRequest() + 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_fetch_git_repository_link_file_blame_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_file_blame), "__call__" + ) as call: + client.fetch_git_repository_link_file_blame(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkFileBlameRequest() + 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_fetch_git_repository_link_pull_request_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request), "__call__" + ) as call: + client.fetch_git_repository_link_pull_request(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkPullRequestRequest() + 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_git_repository_link_pull_request_comment_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_comment), "__call__" + ) as call: + client.add_git_repository_link_pull_request_comment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.AddGitRepositoryLinkPullRequestCommentRequest() + 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_git_repository_link_pull_request_review_comment_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_git_repository_link_pull_request_review_comment), + "__call__", + ) as call: + client.add_git_repository_link_pull_request_review_comment(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = ( + developer_connect.AddGitRepositoryLinkPullRequestReviewCommentRequest() + ) + 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_modify_git_repository_link_pull_request_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.modify_git_repository_link_pull_request), "__call__" + ) as call: + client.modify_git_repository_link_pull_request(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.ModifyGitRepositoryLinkPullRequestRequest() + 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_fetch_git_repository_link_pull_request_list_empty_call_rest(): + client = DeveloperConnectClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.fetch_git_repository_link_pull_request_list), "__call__" + ) as call: + client.fetch_git_repository_link_pull_request_list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = developer_connect.FetchGitRepositoryLinkPullRequestListRequest() + 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_account_connectors_empty_call_rest(): @@ -23028,9 +31577,19 @@ def test_developer_connect_base_transport(): "get_git_repository_link", "fetch_read_write_token", "fetch_read_token", + "open_git_repository_link_pull_request", "fetch_linkable_git_repositories", "fetch_git_hub_installations", "fetch_git_refs", + "diff_git_repository_link_commit", + "fetch_git_repository_link_commit", + "fetch_git_repository_link_commit_list", + "fetch_git_repository_link_file_blame", + "fetch_git_repository_link_pull_request", + "add_git_repository_link_pull_request_comment", + "add_git_repository_link_pull_request_review_comment", + "modify_git_repository_link_pull_request", + "fetch_git_repository_link_pull_request_list", "list_account_connectors", "get_account_connector", "create_account_connector", @@ -23352,6 +31911,9 @@ def test_developer_connect_client_transport_session_collision(transport_name): session1 = client1.transport.fetch_read_token._session session2 = client2.transport.fetch_read_token._session assert session1 != session2 + session1 = client1.transport.open_git_repository_link_pull_request._session + session2 = client2.transport.open_git_repository_link_pull_request._session + assert session1 != session2 session1 = client1.transport.fetch_linkable_git_repositories._session session2 = client2.transport.fetch_linkable_git_repositories._session assert session1 != session2 @@ -23361,6 +31923,37 @@ def test_developer_connect_client_transport_session_collision(transport_name): session1 = client1.transport.fetch_git_refs._session session2 = client2.transport.fetch_git_refs._session assert session1 != session2 + session1 = client1.transport.diff_git_repository_link_commit._session + session2 = client2.transport.diff_git_repository_link_commit._session + assert session1 != session2 + session1 = client1.transport.fetch_git_repository_link_commit._session + session2 = client2.transport.fetch_git_repository_link_commit._session + assert session1 != session2 + session1 = client1.transport.fetch_git_repository_link_commit_list._session + session2 = client2.transport.fetch_git_repository_link_commit_list._session + assert session1 != session2 + session1 = client1.transport.fetch_git_repository_link_file_blame._session + session2 = client2.transport.fetch_git_repository_link_file_blame._session + assert session1 != session2 + session1 = client1.transport.fetch_git_repository_link_pull_request._session + session2 = client2.transport.fetch_git_repository_link_pull_request._session + assert session1 != session2 + session1 = client1.transport.add_git_repository_link_pull_request_comment._session + session2 = client2.transport.add_git_repository_link_pull_request_comment._session + assert session1 != session2 + session1 = ( + client1.transport.add_git_repository_link_pull_request_review_comment._session + ) + session2 = ( + client2.transport.add_git_repository_link_pull_request_review_comment._session + ) + assert session1 != session2 + session1 = client1.transport.modify_git_repository_link_pull_request._session + session2 = client2.transport.modify_git_repository_link_pull_request._session + assert session1 != session2 + session1 = client1.transport.fetch_git_repository_link_pull_request_list._session + session2 = client2.transport.fetch_git_repository_link_pull_request_list._session + assert session1 != session2 session1 = client1.transport.list_account_connectors._session session2 = client2.transport.list_account_connectors._session assert session1 != session2 diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/acl_config_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/acl_config_service.rst new file mode 100644 index 000000000000..818ccdfa41e6 --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/acl_config_service.rst @@ -0,0 +1,6 @@ +AclConfigService +---------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.acl_config_service + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/assistant_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/assistant_service.rst index c4ce368966f7..d5a2d27a4b7f 100644 --- a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/assistant_service.rst +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/assistant_service.rst @@ -4,3 +4,7 @@ AssistantService .. automodule:: google.cloud.discoveryengine_v1.services.assistant_service :members: :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1.services.assistant_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/collection_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/collection_service.rst new file mode 100644 index 000000000000..316370a55d65 --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/collection_service.rst @@ -0,0 +1,6 @@ +CollectionService +----------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.collection_service + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/data_connector_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/data_connector_service.rst new file mode 100644 index 000000000000..9e2870226f0e --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/data_connector_service.rst @@ -0,0 +1,6 @@ +DataConnectorService +-------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.data_connector_service + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/license_config_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/license_config_service.rst new file mode 100644 index 000000000000..5161dc65423e --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/license_config_service.rst @@ -0,0 +1,10 @@ +LicenseConfigService +-------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.license_config_service + :members: + :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1.services.license_config_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/services_.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/services_.rst index 53416f825944..9efe06aeabe7 100644 --- a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/services_.rst +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/services_.rst @@ -3,16 +3,20 @@ Services for Google Cloud Discoveryengine v1 API .. toctree:: :maxdepth: 2 + acl_config_service assistant_service cmek_config_service + collection_service completion_service control_service conversational_search_service + data_connector_service data_store_service document_service engine_service grounded_generation_service identity_mapping_store_service + license_config_service project_service rank_service recommendation_service @@ -24,3 +28,5 @@ Services for Google Cloud Discoveryengine v1 API site_search_engine_service user_event_service user_license_service + user_store_service + widget_config_service diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/serving_config_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/serving_config_service.rst index c5ca73caa7f6..15e0c8b83247 100644 --- a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/serving_config_service.rst +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/serving_config_service.rst @@ -4,3 +4,7 @@ ServingConfigService .. automodule:: google.cloud.discoveryengine_v1.services.serving_config_service :members: :inherited-members: + +.. automodule:: google.cloud.discoveryengine_v1.services.serving_config_service.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/user_store_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/user_store_service.rst new file mode 100644 index 000000000000..cfbfa70aaccb --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/user_store_service.rst @@ -0,0 +1,6 @@ +UserStoreService +---------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.user_store_service + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/widget_config_service.rst b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/widget_config_service.rst new file mode 100644 index 000000000000..5d0ec00e7bcd --- /dev/null +++ b/packages/google-cloud-discoveryengine/docs/discoveryengine_v1/widget_config_service.rst @@ -0,0 +1,6 @@ +WidgetConfigService +------------------------------------- + +.. automodule:: google.cloud.discoveryengine_v1.services.widget_config_service + :members: + :inherited-members: diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/__init__.py index 50ffb178bde7..5baddbb156ce 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/__init__.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/__init__.py @@ -26,16 +26,20 @@ # https://docs.python.org/3.15/library/sys.html#sys.set_lazy_imports_filter # Older Python versions safely ignore this variable. __lazy_modules__ = { + "google.cloud.discoveryengine_v1.services.acl_config_service", "google.cloud.discoveryengine_v1.services.assistant_service", "google.cloud.discoveryengine_v1.services.cmek_config_service", + "google.cloud.discoveryengine_v1.services.collection_service", "google.cloud.discoveryengine_v1.services.completion_service", "google.cloud.discoveryengine_v1.services.control_service", "google.cloud.discoveryengine_v1.services.conversational_search_service", + "google.cloud.discoveryengine_v1.services.data_connector_service", "google.cloud.discoveryengine_v1.services.data_store_service", "google.cloud.discoveryengine_v1.services.document_service", "google.cloud.discoveryengine_v1.services.engine_service", "google.cloud.discoveryengine_v1.services.grounded_generation_service", "google.cloud.discoveryengine_v1.services.identity_mapping_store_service", + "google.cloud.discoveryengine_v1.services.license_config_service", "google.cloud.discoveryengine_v1.services.project_service", "google.cloud.discoveryengine_v1.services.rank_service", "google.cloud.discoveryengine_v1.services.recommendation_service", @@ -47,12 +51,19 @@ "google.cloud.discoveryengine_v1.services.site_search_engine_service", "google.cloud.discoveryengine_v1.services.user_event_service", "google.cloud.discoveryengine_v1.services.user_license_service", + "google.cloud.discoveryengine_v1.services.user_store_service", + "google.cloud.discoveryengine_v1.services.widget_config_service", + "google.cloud.discoveryengine_v1.types.acl_config", + "google.cloud.discoveryengine_v1.types.acl_config_service", + "google.cloud.discoveryengine_v1.types.agent_gateway_setting", "google.cloud.discoveryengine_v1.types.answer", "google.cloud.discoveryengine_v1.types.assist_answer", "google.cloud.discoveryengine_v1.types.assistant", "google.cloud.discoveryengine_v1.types.assistant_service", "google.cloud.discoveryengine_v1.types.chunk", "google.cloud.discoveryengine_v1.types.cmek_config_service", + "google.cloud.discoveryengine_v1.types.collection", + "google.cloud.discoveryengine_v1.types.collection_service", "google.cloud.discoveryengine_v1.types.common", "google.cloud.discoveryengine_v1.types.completion", "google.cloud.discoveryengine_v1.types.completion_service", @@ -61,6 +72,8 @@ "google.cloud.discoveryengine_v1.types.conversation", "google.cloud.discoveryengine_v1.types.conversational_search_service", "google.cloud.discoveryengine_v1.types.custom_tuning_model", + "google.cloud.discoveryengine_v1.types.data_connector", + "google.cloud.discoveryengine_v1.types.data_connector_service", "google.cloud.discoveryengine_v1.types.data_store", "google.cloud.discoveryengine_v1.types.data_store_service", "google.cloud.discoveryengine_v1.types.document", @@ -68,11 +81,15 @@ "google.cloud.discoveryengine_v1.types.document_service", "google.cloud.discoveryengine_v1.types.engine", "google.cloud.discoveryengine_v1.types.engine_service", + "google.cloud.discoveryengine_v1.types.feedback", "google.cloud.discoveryengine_v1.types.grounded_generation_service", "google.cloud.discoveryengine_v1.types.grounding", "google.cloud.discoveryengine_v1.types.identity_mapping_store", "google.cloud.discoveryengine_v1.types.identity_mapping_store_service", "google.cloud.discoveryengine_v1.types.import_config", + "google.cloud.discoveryengine_v1.types.license_config", + "google.cloud.discoveryengine_v1.types.license_config_service", + "google.cloud.discoveryengine_v1.types.logging", "google.cloud.discoveryengine_v1.types.project", "google.cloud.discoveryengine_v1.types.project_service", "google.cloud.discoveryengine_v1.types.purge_config", @@ -93,9 +110,17 @@ "google.cloud.discoveryengine_v1.types.user_event_service", "google.cloud.discoveryengine_v1.types.user_license", "google.cloud.discoveryengine_v1.types.user_license_service", + "google.cloud.discoveryengine_v1.types.user_store", + "google.cloud.discoveryengine_v1.types.user_store_service", + "google.cloud.discoveryengine_v1.types.widget_config", + "google.cloud.discoveryengine_v1.types.widget_config_service", } +from .services.acl_config_service import ( + AclConfigServiceAsyncClient, + AclConfigServiceClient, +) from .services.assistant_service import ( AssistantServiceAsyncClient, AssistantServiceClient, @@ -104,6 +129,10 @@ CmekConfigServiceAsyncClient, CmekConfigServiceClient, ) +from .services.collection_service import ( + CollectionServiceAsyncClient, + CollectionServiceClient, +) from .services.completion_service import ( CompletionServiceAsyncClient, CompletionServiceClient, @@ -113,6 +142,10 @@ ConversationalSearchServiceAsyncClient, ConversationalSearchServiceClient, ) +from .services.data_connector_service import ( + DataConnectorServiceAsyncClient, + DataConnectorServiceClient, +) from .services.data_store_service import ( DataStoreServiceAsyncClient, DataStoreServiceClient, @@ -127,6 +160,10 @@ IdentityMappingStoreServiceAsyncClient, IdentityMappingStoreServiceClient, ) +from .services.license_config_service import ( + LicenseConfigServiceAsyncClient, + LicenseConfigServiceClient, +) from .services.project_service import ProjectServiceAsyncClient, ProjectServiceClient from .services.rank_service import RankServiceAsyncClient, RankServiceClient from .services.recommendation_service import ( @@ -156,6 +193,17 @@ UserLicenseServiceAsyncClient, UserLicenseServiceClient, ) +from .services.user_store_service import ( + UserStoreServiceAsyncClient, + UserStoreServiceClient, +) +from .services.widget_config_service import ( + WidgetConfigServiceAsyncClient, + WidgetConfigServiceClient, +) +from .types.acl_config import AclConfig +from .types.acl_config_service import GetAclConfigRequest, UpdateAclConfigRequest +from .types.agent_gateway_setting import AgentGatewaySetting from .types.answer import Answer from .types.assist_answer import ( AssistAnswer, @@ -165,8 +213,14 @@ from .types.assistant import Assistant from .types.assistant_service import ( AssistUserMetadata, + CreateAssistantRequest, + DeleteAssistantRequest, + GetAssistantRequest, + ListAssistantsRequest, + ListAssistantsResponse, StreamAssistRequest, StreamAssistResponse, + UpdateAssistantRequest, ) from .types.chunk import Chunk from .types.cmek_config_service import ( @@ -180,10 +234,14 @@ UpdateCmekConfigMetadata, UpdateCmekConfigRequest, ) +from .types.collection import Collection +from .types.collection_service import DeleteCollectionMetadata, DeleteCollectionRequest from .types.common import ( CustomAttribute, + DataProtectionPolicy, DoubleList, HealthcareFhirConfig, + IdpConfig, IndustryVertical, Interval, Principal, @@ -191,11 +249,19 @@ SearchLinkPromotion, SearchTier, SearchUseCase, + SessionConfig, SolutionType, + SubscriptionTerm, + SubscriptionTier, UserInfo, ) from .types.completion import CompletionSuggestion, SuggestionDenyListEntry -from .types.completion_service import CompleteQueryRequest, CompleteQueryResponse +from .types.completion_service import ( + AdvancedCompleteQueryRequest, + AdvancedCompleteQueryResponse, + CompleteQueryRequest, + CompleteQueryResponse, +) from .types.control import Condition, Control from .types.control_service import ( CreateControlRequest, @@ -232,6 +298,24 @@ UpdateSessionRequest, ) from .types.custom_tuning_model import CustomTuningModel +from .types.data_connector import ( + ActionConfig, + AlertPolicyConfig, + BAPConfig, + CliConfig, + ConnectorType, + DataConnector, + DestinationConfig, + DynamicTool, + IdentityScheduleConfig, + Tenant, +) +from .types.data_connector_service import ( + GetDataConnectorRequest, + SetUpDataConnectorMetadata, + SetUpDataConnectorRequest, + UpdateDataConnectorRequest, +) from .types.data_store import ( AdvancedSiteSearchConfig, DataStore, @@ -271,10 +355,13 @@ ListEnginesResponse, UpdateEngineRequest, ) +from .types.feedback import Feedback from .types.grounded_generation_service import ( CheckGroundingRequest, CheckGroundingResponse, CheckGroundingSpec, + Citation, + CitationMetadata, GenerateGroundedContentRequest, GenerateGroundedContentResponse, GroundedGenerationContent, @@ -319,6 +406,19 @@ ImportUserEventsResponse, SpannerSource, ) +from .types.license_config import LicenseConfig +from .types.license_config_service import ( + CreateLicenseConfigRequest, + DistributeLicenseConfigRequest, + DistributeLicenseConfigResponse, + GetLicenseConfigRequest, + ListLicenseConfigsRequest, + ListLicenseConfigsResponse, + RetractLicenseConfigRequest, + RetractLicenseConfigResponse, + UpdateLicenseConfigRequest, +) +from .types.logging import ObservabilityConfig from .types.project import Project from .types.project_service import ProvisionProjectMetadata, ProvisionProjectRequest from .types.purge_config import ( @@ -359,8 +459,15 @@ TrainCustomModelRequest, TrainCustomModelResponse, ) -from .types.serving_config import ServingConfig -from .types.serving_config_service import UpdateServingConfigRequest +from .types.serving_config import AnswerGenerationSpec, ServingConfig +from .types.serving_config_service import ( + CreateServingConfigRequest, + DeleteServingConfigRequest, + GetServingConfigRequest, + ListServingConfigsRequest, + ListServingConfigsResponse, + UpdateServingConfigRequest, +) from .types.session import Query, Session from .types.site_search_engine import ( Sitemap, @@ -414,26 +521,39 @@ UserEvent, ) from .types.user_event_service import CollectUserEventRequest, WriteUserEventRequest -from .types.user_license import UserLicense +from .types.user_license import LicenseConfigUsageStats, UserLicense from .types.user_license_service import ( BatchUpdateUserLicensesMetadata, BatchUpdateUserLicensesRequest, BatchUpdateUserLicensesResponse, + ListLicenseConfigsUsageStatsRequest, + ListLicenseConfigsUsageStatsResponse, ListUserLicensesRequest, ListUserLicensesResponse, ) +from .types.user_store import UserStore +from .types.user_store_service import GetUserStoreRequest, UpdateUserStoreRequest +from .types.widget_config import ModelInfoView, WidgetConfig +from .types.widget_config_service import ( + GetWidgetConfigRequest, + UpdateWidgetConfigRequest, +) __all__ = ( + "AclConfigServiceAsyncClient", "AssistantServiceAsyncClient", "CmekConfigServiceAsyncClient", + "CollectionServiceAsyncClient", "CompletionServiceAsyncClient", "ControlServiceAsyncClient", "ConversationalSearchServiceAsyncClient", + "DataConnectorServiceAsyncClient", "DataStoreServiceAsyncClient", "DocumentServiceAsyncClient", "EngineServiceAsyncClient", "GroundedGenerationServiceAsyncClient", "IdentityMappingStoreServiceAsyncClient", + "LicenseConfigServiceAsyncClient", "ProjectServiceAsyncClient", "RankServiceAsyncClient", "RecommendationServiceAsyncClient", @@ -445,9 +565,19 @@ "SiteSearchEngineServiceAsyncClient", "UserEventServiceAsyncClient", "UserLicenseServiceAsyncClient", + "UserStoreServiceAsyncClient", + "WidgetConfigServiceAsyncClient", + "AclConfig", + "AclConfigServiceClient", + "ActionConfig", + "AdvancedCompleteQueryRequest", + "AdvancedCompleteQueryResponse", "AdvancedSiteSearchConfig", + "AgentGatewaySetting", + "AlertPolicyConfig", "AlloyDbSource", "Answer", + "AnswerGenerationSpec", "AnswerQueryRequest", "AnswerQueryResponse", "AssistAnswer", @@ -456,6 +586,7 @@ "AssistantContent", "AssistantGroundedContent", "AssistantServiceClient", + "BAPConfig", "BatchCreateTargetSiteMetadata", "BatchCreateTargetSitesRequest", "BatchCreateTargetSitesResponse", @@ -474,16 +605,22 @@ "CheckGroundingResponse", "CheckGroundingSpec", "Chunk", + "Citation", + "CitationMetadata", + "CliConfig", "CloudSqlSource", "CmekConfig", "CmekConfigServiceClient", "CollectUserEventRequest", + "Collection", + "CollectionServiceClient", "CompleteQueryRequest", "CompleteQueryResponse", "CompletionInfo", "CompletionServiceClient", "CompletionSuggestion", "Condition", + "ConnectorType", "Control", "ControlServiceClient", "Conversation", @@ -492,6 +629,7 @@ "ConversationalSearchServiceClient", "ConverseConversationRequest", "ConverseConversationResponse", + "CreateAssistantRequest", "CreateControlRequest", "CreateConversationRequest", "CreateDataStoreMetadata", @@ -500,8 +638,10 @@ "CreateEngineMetadata", "CreateEngineRequest", "CreateIdentityMappingStoreRequest", + "CreateLicenseConfigRequest", "CreateSchemaMetadata", "CreateSchemaRequest", + "CreateServingConfigRequest", "CreateSessionRequest", "CreateSitemapMetadata", "CreateSitemapRequest", @@ -509,10 +649,16 @@ "CreateTargetSiteRequest", "CustomAttribute", "CustomTuningModel", + "DataConnector", + "DataConnectorServiceClient", + "DataProtectionPolicy", "DataStore", "DataStoreServiceClient", + "DeleteAssistantRequest", "DeleteCmekConfigMetadata", "DeleteCmekConfigRequest", + "DeleteCollectionMetadata", + "DeleteCollectionRequest", "DeleteControlRequest", "DeleteConversationRequest", "DeleteDataStoreMetadata", @@ -524,25 +670,31 @@ "DeleteIdentityMappingStoreRequest", "DeleteSchemaMetadata", "DeleteSchemaRequest", + "DeleteServingConfigRequest", "DeleteSessionRequest", "DeleteSitemapMetadata", "DeleteSitemapRequest", "DeleteTargetSiteMetadata", "DeleteTargetSiteRequest", + "DestinationConfig", "DisableAdvancedSiteSearchMetadata", "DisableAdvancedSiteSearchRequest", "DisableAdvancedSiteSearchResponse", + "DistributeLicenseConfigRequest", + "DistributeLicenseConfigResponse", "Document", "DocumentInfo", "DocumentProcessingConfig", "DocumentServiceClient", "DoubleList", + "DynamicTool", "EnableAdvancedSiteSearchMetadata", "EnableAdvancedSiteSearchRequest", "EnableAdvancedSiteSearchResponse", "Engine", "EngineServiceClient", "FactChunk", + "Feedback", "FetchDomainVerificationStatusRequest", "FetchDomainVerificationStatusResponse", "FetchSitemapsRequest", @@ -552,18 +704,25 @@ "GcsSource", "GenerateGroundedContentRequest", "GenerateGroundedContentResponse", + "GetAclConfigRequest", "GetAnswerRequest", + "GetAssistantRequest", "GetCmekConfigRequest", "GetControlRequest", "GetConversationRequest", + "GetDataConnectorRequest", "GetDataStoreRequest", "GetDocumentRequest", "GetEngineRequest", "GetIdentityMappingStoreRequest", + "GetLicenseConfigRequest", "GetSchemaRequest", + "GetServingConfigRequest", "GetSessionRequest", "GetSiteSearchEngineRequest", "GetTargetSiteRequest", + "GetUserStoreRequest", + "GetWidgetConfigRequest", "GroundedGenerationContent", "GroundedGenerationServiceClient", "GroundingFact", @@ -573,6 +732,8 @@ "IdentityMappingEntryOperationMetadata", "IdentityMappingStore", "IdentityMappingStoreServiceClient", + "IdentityScheduleConfig", + "IdpConfig", "ImportCompletionSuggestionsMetadata", "ImportCompletionSuggestionsRequest", "ImportCompletionSuggestionsResponse", @@ -590,6 +751,11 @@ "ImportUserEventsResponse", "IndustryVertical", "Interval", + "LicenseConfig", + "LicenseConfigServiceClient", + "LicenseConfigUsageStats", + "ListAssistantsRequest", + "ListAssistantsResponse", "ListCmekConfigsRequest", "ListCmekConfigsResponse", "ListControlsRequest", @@ -608,8 +774,14 @@ "ListIdentityMappingStoresResponse", "ListIdentityMappingsRequest", "ListIdentityMappingsResponse", + "ListLicenseConfigsRequest", + "ListLicenseConfigsResponse", + "ListLicenseConfigsUsageStatsRequest", + "ListLicenseConfigsUsageStatsResponse", "ListSchemasRequest", "ListSchemasResponse", + "ListServingConfigsRequest", + "ListServingConfigsResponse", "ListSessionsRequest", "ListSessionsResponse", "ListTargetSitesRequest", @@ -617,7 +789,9 @@ "ListUserLicensesRequest", "ListUserLicensesResponse", "MediaInfo", + "ModelInfoView", "NaturalLanguageQueryUnderstandingConfig", + "ObservabilityConfig", "PageInfo", "PanelInfo", "Principal", @@ -651,6 +825,8 @@ "RecrawlUrisRequest", "RecrawlUrisResponse", "Reply", + "RetractLicenseConfigRequest", + "RetractLicenseConfigResponse", "SafetyRating", "Schema", "SchemaServiceClient", @@ -666,7 +842,10 @@ "ServingConfig", "ServingConfigServiceClient", "Session", + "SessionConfig", "SessionServiceClient", + "SetUpDataConnectorMetadata", + "SetUpDataConnectorRequest", "SingleRegionKey", "SiteSearchEngine", "SiteSearchEngineServiceClient", @@ -676,31 +855,44 @@ "SpannerSource", "StreamAssistRequest", "StreamAssistResponse", + "SubscriptionTerm", + "SubscriptionTier", "SuggestionDenyListEntry", "TargetSite", + "Tenant", "TextInput", "TrainCustomModelMetadata", "TrainCustomModelRequest", "TrainCustomModelResponse", "TransactionInfo", + "UpdateAclConfigRequest", + "UpdateAssistantRequest", "UpdateCmekConfigMetadata", "UpdateCmekConfigRequest", "UpdateControlRequest", "UpdateConversationRequest", + "UpdateDataConnectorRequest", "UpdateDataStoreRequest", "UpdateDocumentRequest", "UpdateEngineRequest", + "UpdateLicenseConfigRequest", "UpdateSchemaMetadata", "UpdateSchemaRequest", "UpdateServingConfigRequest", "UpdateSessionRequest", "UpdateTargetSiteMetadata", "UpdateTargetSiteRequest", + "UpdateUserStoreRequest", + "UpdateWidgetConfigRequest", "UserEvent", "UserEventServiceClient", "UserInfo", "UserLicense", "UserLicenseServiceClient", + "UserStore", + "UserStoreServiceClient", + "WidgetConfig", + "WidgetConfigServiceClient", "WorkspaceConfig", "WriteUserEventRequest", ) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_metadata.json b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_metadata.json index e95ac5ea50c2..46b8b1c24f29 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_metadata.json +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/gapic_metadata.json @@ -5,35 +5,159 @@ "protoPackage": "google.cloud.discoveryengine.v1", "schema": "1.0", "services": { + "AclConfigService": { + "clients": { + "grpc": { + "libraryClient": "AclConfigServiceClient", + "rpcs": { + "GetAclConfig": { + "methods": [ + "get_acl_config" + ] + }, + "UpdateAclConfig": { + "methods": [ + "update_acl_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AclConfigServiceAsyncClient", + "rpcs": { + "GetAclConfig": { + "methods": [ + "get_acl_config" + ] + }, + "UpdateAclConfig": { + "methods": [ + "update_acl_config" + ] + } + } + }, + "rest": { + "libraryClient": "AclConfigServiceClient", + "rpcs": { + "GetAclConfig": { + "methods": [ + "get_acl_config" + ] + }, + "UpdateAclConfig": { + "methods": [ + "update_acl_config" + ] + } + } + } + } + }, "AssistantService": { "clients": { "grpc": { "libraryClient": "AssistantServiceClient", "rpcs": { + "CreateAssistant": { + "methods": [ + "create_assistant" + ] + }, + "DeleteAssistant": { + "methods": [ + "delete_assistant" + ] + }, + "GetAssistant": { + "methods": [ + "get_assistant" + ] + }, + "ListAssistants": { + "methods": [ + "list_assistants" + ] + }, "StreamAssist": { "methods": [ "stream_assist" ] + }, + "UpdateAssistant": { + "methods": [ + "update_assistant" + ] } } }, "grpc-async": { "libraryClient": "AssistantServiceAsyncClient", "rpcs": { + "CreateAssistant": { + "methods": [ + "create_assistant" + ] + }, + "DeleteAssistant": { + "methods": [ + "delete_assistant" + ] + }, + "GetAssistant": { + "methods": [ + "get_assistant" + ] + }, + "ListAssistants": { + "methods": [ + "list_assistants" + ] + }, "StreamAssist": { "methods": [ "stream_assist" ] + }, + "UpdateAssistant": { + "methods": [ + "update_assistant" + ] } } }, "rest": { "libraryClient": "AssistantServiceClient", "rpcs": { + "CreateAssistant": { + "methods": [ + "create_assistant" + ] + }, + "DeleteAssistant": { + "methods": [ + "delete_assistant" + ] + }, + "GetAssistant": { + "methods": [ + "get_assistant" + ] + }, + "ListAssistants": { + "methods": [ + "list_assistants" + ] + }, "StreamAssist": { "methods": [ "stream_assist" ] + }, + "UpdateAssistant": { + "methods": [ + "update_assistant" + ] } } } @@ -118,11 +242,80 @@ } } }, + "CollectionService": { + "clients": { + "grpc": { + "libraryClient": "CollectionServiceClient", + "rpcs": { + "DeleteCollection": { + "methods": [ + "delete_collection" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CollectionServiceAsyncClient", + "rpcs": { + "DeleteCollection": { + "methods": [ + "delete_collection" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + } + } + }, + "rest": { + "libraryClient": "CollectionServiceClient", + "rpcs": { + "DeleteCollection": { + "methods": [ + "delete_collection" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + } + } + } + } + }, "CompletionService": { "clients": { "grpc": { "libraryClient": "CompletionServiceClient", "rpcs": { + "AdvancedCompleteQuery": { + "methods": [ + "advanced_complete_query" + ] + }, "CompleteQuery": { "methods": [ "complete_query" @@ -153,6 +346,11 @@ "grpc-async": { "libraryClient": "CompletionServiceAsyncClient", "rpcs": { + "AdvancedCompleteQuery": { + "methods": [ + "advanced_complete_query" + ] + }, "CompleteQuery": { "methods": [ "complete_query" @@ -183,6 +381,11 @@ "rest": { "libraryClient": "CompletionServiceClient", "rpcs": { + "AdvancedCompleteQuery": { + "methods": [ + "advanced_complete_query" + ] + }, "CompleteQuery": { "methods": [ "complete_query" @@ -535,6 +738,70 @@ } } }, + "DataConnectorService": { + "clients": { + "grpc": { + "libraryClient": "DataConnectorServiceClient", + "rpcs": { + "GetDataConnector": { + "methods": [ + "get_data_connector" + ] + }, + "SetUpDataConnector": { + "methods": [ + "set_up_data_connector" + ] + }, + "UpdateDataConnector": { + "methods": [ + "update_data_connector" + ] + } + } + }, + "grpc-async": { + "libraryClient": "DataConnectorServiceAsyncClient", + "rpcs": { + "GetDataConnector": { + "methods": [ + "get_data_connector" + ] + }, + "SetUpDataConnector": { + "methods": [ + "set_up_data_connector" + ] + }, + "UpdateDataConnector": { + "methods": [ + "update_data_connector" + ] + } + } + }, + "rest": { + "libraryClient": "DataConnectorServiceClient", + "rpcs": { + "GetDataConnector": { + "methods": [ + "get_data_connector" + ] + }, + "SetUpDataConnector": { + "methods": [ + "set_up_data_connector" + ] + }, + "UpdateDataConnector": { + "methods": [ + "update_data_connector" + ] + } + } + } + } + }, "DataStoreService": { "clients": { "grpc": { @@ -555,11 +822,21 @@ "get_data_store" ] }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, "ListDataStores": { "methods": [ "list_data_stores" ] }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, "UpdateDataStore": { "methods": [ "update_data_store" @@ -585,11 +862,21 @@ "get_data_store" ] }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, "ListDataStores": { "methods": [ "list_data_stores" ] }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, "UpdateDataStore": { "methods": [ "update_data_store" @@ -615,11 +902,21 @@ "get_data_store" ] }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, "ListDataStores": { "methods": [ "list_data_stores" ] }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, "UpdateDataStore": { "methods": [ "update_data_store" @@ -788,11 +1085,21 @@ "get_engine" ] }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, "ListEngines": { "methods": [ "list_engines" ] }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, "UpdateEngine": { "methods": [ "update_engine" @@ -818,11 +1125,21 @@ "get_engine" ] }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, "ListEngines": { "methods": [ "list_engines" ] }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, "UpdateEngine": { "methods": [ "update_engine" @@ -848,11 +1165,21 @@ "get_engine" ] }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, "ListEngines": { "methods": [ "list_engines" ] }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, "UpdateEngine": { "methods": [ "update_engine" @@ -1050,6 +1377,115 @@ } } }, + "LicenseConfigService": { + "clients": { + "grpc": { + "libraryClient": "LicenseConfigServiceClient", + "rpcs": { + "CreateLicenseConfig": { + "methods": [ + "create_license_config" + ] + }, + "DistributeLicenseConfig": { + "methods": [ + "distribute_license_config" + ] + }, + "GetLicenseConfig": { + "methods": [ + "get_license_config" + ] + }, + "ListLicenseConfigs": { + "methods": [ + "list_license_configs" + ] + }, + "RetractLicenseConfig": { + "methods": [ + "retract_license_config" + ] + }, + "UpdateLicenseConfig": { + "methods": [ + "update_license_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "LicenseConfigServiceAsyncClient", + "rpcs": { + "CreateLicenseConfig": { + "methods": [ + "create_license_config" + ] + }, + "DistributeLicenseConfig": { + "methods": [ + "distribute_license_config" + ] + }, + "GetLicenseConfig": { + "methods": [ + "get_license_config" + ] + }, + "ListLicenseConfigs": { + "methods": [ + "list_license_configs" + ] + }, + "RetractLicenseConfig": { + "methods": [ + "retract_license_config" + ] + }, + "UpdateLicenseConfig": { + "methods": [ + "update_license_config" + ] + } + } + }, + "rest": { + "libraryClient": "LicenseConfigServiceClient", + "rpcs": { + "CreateLicenseConfig": { + "methods": [ + "create_license_config" + ] + }, + "DistributeLicenseConfig": { + "methods": [ + "distribute_license_config" + ] + }, + "GetLicenseConfig": { + "methods": [ + "get_license_config" + ] + }, + "ListLicenseConfigs": { + "methods": [ + "list_license_configs" + ] + }, + "RetractLicenseConfig": { + "methods": [ + "retract_license_config" + ] + }, + "UpdateLicenseConfig": { + "methods": [ + "update_license_config" + ] + } + } + } + } + }, "ProjectService": { "clients": { "grpc": { @@ -1349,6 +1785,26 @@ "grpc": { "libraryClient": "ServingConfigServiceClient", "rpcs": { + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, "UpdateServingConfig": { "methods": [ "update_serving_config" @@ -1359,6 +1815,26 @@ "grpc-async": { "libraryClient": "ServingConfigServiceAsyncClient", "rpcs": { + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, "UpdateServingConfig": { "methods": [ "update_serving_config" @@ -1369,6 +1845,26 @@ "rest": { "libraryClient": "ServingConfigServiceClient", "rpcs": { + "CreateServingConfig": { + "methods": [ + "create_serving_config" + ] + }, + "DeleteServingConfig": { + "methods": [ + "delete_serving_config" + ] + }, + "GetServingConfig": { + "methods": [ + "get_serving_config" + ] + }, + "ListServingConfigs": { + "methods": [ + "list_serving_configs" + ] + }, "UpdateServingConfig": { "methods": [ "update_serving_config" @@ -1805,6 +2301,11 @@ "batch_update_user_licenses" ] }, + "ListLicenseConfigsUsageStats": { + "methods": [ + "list_license_configs_usage_stats" + ] + }, "ListUserLicenses": { "methods": [ "list_user_licenses" @@ -1820,6 +2321,11 @@ "batch_update_user_licenses" ] }, + "ListLicenseConfigsUsageStats": { + "methods": [ + "list_license_configs_usage_stats" + ] + }, "ListUserLicenses": { "methods": [ "list_user_licenses" @@ -1835,6 +2341,11 @@ "batch_update_user_licenses" ] }, + "ListLicenseConfigsUsageStats": { + "methods": [ + "list_license_configs_usage_stats" + ] + }, "ListUserLicenses": { "methods": [ "list_user_licenses" @@ -1843,6 +2354,104 @@ } } } + }, + "UserStoreService": { + "clients": { + "grpc": { + "libraryClient": "UserStoreServiceClient", + "rpcs": { + "GetUserStore": { + "methods": [ + "get_user_store" + ] + }, + "UpdateUserStore": { + "methods": [ + "update_user_store" + ] + } + } + }, + "grpc-async": { + "libraryClient": "UserStoreServiceAsyncClient", + "rpcs": { + "GetUserStore": { + "methods": [ + "get_user_store" + ] + }, + "UpdateUserStore": { + "methods": [ + "update_user_store" + ] + } + } + }, + "rest": { + "libraryClient": "UserStoreServiceClient", + "rpcs": { + "GetUserStore": { + "methods": [ + "get_user_store" + ] + }, + "UpdateUserStore": { + "methods": [ + "update_user_store" + ] + } + } + } + } + }, + "WidgetConfigService": { + "clients": { + "grpc": { + "libraryClient": "WidgetConfigServiceClient", + "rpcs": { + "GetWidgetConfig": { + "methods": [ + "get_widget_config" + ] + }, + "UpdateWidgetConfig": { + "methods": [ + "update_widget_config" + ] + } + } + }, + "grpc-async": { + "libraryClient": "WidgetConfigServiceAsyncClient", + "rpcs": { + "GetWidgetConfig": { + "methods": [ + "get_widget_config" + ] + }, + "UpdateWidgetConfig": { + "methods": [ + "update_widget_config" + ] + } + } + }, + "rest": { + "libraryClient": "WidgetConfigServiceClient", + "rpcs": { + "GetWidgetConfig": { + "methods": [ + "get_widget_config" + ] + }, + "UpdateWidgetConfig": { + "methods": [ + "update_widget_config" + ] + } + } + } + } } } } diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/__init__.py new file mode 100644 index 000000000000..1f391c0152a8 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/__init__.py @@ -0,0 +1,22 @@ +# -*- 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 .async_client import AclConfigServiceAsyncClient +from .client import AclConfigServiceClient + +__all__ = ( + "AclConfigServiceClient", + "AclConfigServiceAsyncClient", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/async_client.py new file mode 100644 index 000000000000..08854f23c4be --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/async_client.py @@ -0,0 +1,695 @@ +# -*- 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 logging as std_logging +import re +from collections import OrderedDict +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +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_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.discoveryengine_v1.types import acl_config, acl_config_service, common + +from .client import AclConfigServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, AclConfigServiceTransport +from .transports.grpc_asyncio import AclConfigServiceGrpcAsyncIOTransport + +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__) + + +class AclConfigServiceAsyncClient: + """Service for managing Acl Configuration.""" + + _client: AclConfigServiceClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = AclConfigServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = AclConfigServiceClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = AclConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = AclConfigServiceClient._DEFAULT_UNIVERSE + + acl_config_path = staticmethod(AclConfigServiceClient.acl_config_path) + parse_acl_config_path = staticmethod(AclConfigServiceClient.parse_acl_config_path) + common_billing_account_path = staticmethod( + AclConfigServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + AclConfigServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(AclConfigServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + AclConfigServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + AclConfigServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + AclConfigServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod(AclConfigServiceClient.common_project_path) + parse_common_project_path = staticmethod( + AclConfigServiceClient.parse_common_project_path + ) + common_location_path = staticmethod(AclConfigServiceClient.common_location_path) + parse_common_location_path = staticmethod( + AclConfigServiceClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AclConfigServiceAsyncClient: The constructed client. + """ + sa_info_func = ( + AclConfigServiceClient.from_service_account_info.__func__ # type: ignore + ) + return sa_info_func(AclConfigServiceAsyncClient, info, *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: + AclConfigServiceAsyncClient: The constructed client. + """ + sa_file_func = ( + AclConfigServiceClient.from_service_account_file.__func__ # type: ignore + ) + return sa_file_func(AclConfigServiceAsyncClient, filename, *args, **kwargs) + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return AclConfigServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> AclConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AclConfigServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + @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._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = AclConfigServiceClient.get_transport_class + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, AclConfigServiceTransport, Callable[..., AclConfigServiceTransport] + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the acl config service async client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AclConfigServiceTransport,Callable[..., AclConfigServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the AclConfigServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = AclConfigServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.discoveryengine_v1.AclConfigServiceAsyncClient`.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "universeDomain": getattr( + self._client._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._client._transport, "_credentials") + else { + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "credentialsType": None, + }, + ) + + async def update_acl_config( + self, + request: Optional[ + Union[acl_config_service.UpdateAclConfigRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> acl_config.AclConfig: + r"""Default ACL configuration for use in a location of a + customer's project. Updates will only reflect to new + data stores. Existing data stores will still use the old + value. + + .. 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 discoveryengine_v1 + + async def sample_update_acl_config(): + # Create a client + client = discoveryengine_v1.AclConfigServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateAclConfigRequest( + ) + + # Make the request + response = await client.update_acl_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateAclConfigRequest, dict]]): + The request object. Request message for UpdateAclConfig + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.discoveryengine_v1.types.AclConfig: + Access Control Configuration. + """ + # 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, acl_config_service.UpdateAclConfigRequest): + request = acl_config_service.UpdateAclConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_acl_config + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("acl_config.name", request.acl_config.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 get_acl_config( + self, + request: Optional[Union[acl_config_service.GetAclConfigRequest, 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]]] = (), + ) -> acl_config.AclConfig: + r"""Gets the [AclConfig][google.cloud.discoveryengine.v1.AclConfig]. + + .. 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 discoveryengine_v1 + + async def sample_get_acl_config(): + # Create a client + client = discoveryengine_v1.AclConfigServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetAclConfigRequest( + name="name_value", + ) + + # Make the request + response = await client.get_acl_config(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.GetAclConfigRequest, dict]]): + The request object. Request message for + GetAclConfigRequest method. + name (:class:`str`): + Required. Resource name of + [AclConfig][google.cloud.discoveryengine.v1.AclConfig], + such as ``projects/*/locations/*/aclConfig``. + + If the caller does not have permission to access the + [AclConfig][google.cloud.discoveryengine.v1.AclConfig], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + 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.discoveryengine_v1.types.AclConfig: + Access Control Configuration. + """ + # 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, acl_config_service.GetAclConfigRequest): + request = acl_config_service.GetAclConfigRequest(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_acl_config + ] + + # 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_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self.transport._wrapped_methods[self._client._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + await rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def __aenter__(self) -> "AclConfigServiceAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +__all__ = ("AclConfigServiceAsyncClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/client.py new file mode 100644 index 000000000000..3fc38a9b16ad --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/client.py @@ -0,0 +1,999 @@ +# -*- 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.discoveryengine_v1 import gapic_version as package_version +from google.cloud.discoveryengine_v1._compat import ( + get_api_endpoint, + get_default_mtls_endpoint, + get_universe_domain, + read_environment_variables, + should_use_client_cert, +) + +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.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.cloud.discoveryengine_v1.types import acl_config, acl_config_service, common + +from .transports.base import DEFAULT_CLIENT_INFO, AclConfigServiceTransport +from .transports.grpc import AclConfigServiceGrpcTransport +from .transports.grpc_asyncio import AclConfigServiceGrpcAsyncIOTransport +from .transports.rest import AclConfigServiceRestTransport + + +class AclConfigServiceClientMeta(type): + """Metaclass for the AclConfigService 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[AclConfigServiceTransport]] + _transport_registry["grpc"] = AclConfigServiceGrpcTransport + _transport_registry["grpc_asyncio"] = AclConfigServiceGrpcAsyncIOTransport + _transport_registry["rest"] = AclConfigServiceRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[AclConfigServiceTransport]: + """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 AclConfigServiceClient(metaclass=AclConfigServiceClientMeta): + """Service for managing Acl Configuration.""" + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "discoveryengine.googleapis.com" + DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT) + + _DEFAULT_ENDPOINT_TEMPLATE = "discoveryengine.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + AclConfigServiceClient: 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: + AclConfigServiceClient: 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) -> AclConfigServiceTransport: + """Returns the transport used by the client instance. + + Returns: + AclConfigServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def acl_config_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified acl_config string.""" + return "projects/{project}/locations/{location}/aclConfig".format( + project=project, + location=location, + ) + + @staticmethod + def parse_acl_config_path(path: str) -> Dict[str, str]: + """Parses a acl_config path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/aclConfig$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """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 = should_use_client_cert() + 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 # type: ignore + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @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 + + 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, AclConfigServiceTransport, Callable[..., AclConfigServiceTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the acl config service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,AclConfigServiceTransport,Callable[..., AclConfigServiceTransport]]]): + 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 AclConfigServiceTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + self._use_client_cert, self._use_mtls_endpoint, self._universe_domain_env = ( + read_environment_variables() + ) + self._client_cert_source = AclConfigServiceClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = get_universe_domain( + universe_domain_opt, + self._universe_domain_env, + default_universe=AclConfigServiceClient._DEFAULT_UNIVERSE, + ) + 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, AclConfigServiceTransport) + if transport_provided: + # transport is a AclConfigServiceTransport 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(AclConfigServiceTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or get_api_endpoint( + api_override=self._client_options.api_endpoint, + universe_domain=self._universe_domain, + default_universe=AclConfigServiceClient._DEFAULT_UNIVERSE, + default_mtls_endpoint=AclConfigServiceClient.DEFAULT_MTLS_ENDPOINT, + default_endpoint_template=AclConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE, + use_mtls=self._use_mtls_endpoint == "always" + or (self._use_mtls_endpoint == "auto" and self._client_cert_source), + ) + + 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[AclConfigServiceTransport], + Callable[..., AclConfigServiceTransport], + ] = ( + AclConfigServiceClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., AclConfigServiceTransport], 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.discoveryengine_v1.AclConfigServiceClient`.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "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.discoveryengine.v1.AclConfigService", + "credentialsType": None, + }, + ) + + def update_acl_config( + self, + request: Optional[ + Union[acl_config_service.UpdateAclConfigRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> acl_config.AclConfig: + r"""Default ACL configuration for use in a location of a + customer's project. Updates will only reflect to new + data stores. Existing data stores will still use the old + value. + + .. 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 discoveryengine_v1 + + def sample_update_acl_config(): + # Create a client + client = discoveryengine_v1.AclConfigServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.UpdateAclConfigRequest( + ) + + # Make the request + response = client.update_acl_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.UpdateAclConfigRequest, dict]): + The request object. Request message for UpdateAclConfig + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.discoveryengine_v1.types.AclConfig: + Access Control Configuration. + """ + # 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, acl_config_service.UpdateAclConfigRequest): + request = acl_config_service.UpdateAclConfigRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_acl_config] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("acl_config.name", request.acl_config.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 get_acl_config( + self, + request: Optional[Union[acl_config_service.GetAclConfigRequest, 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]]] = (), + ) -> acl_config.AclConfig: + r"""Gets the [AclConfig][google.cloud.discoveryengine.v1.AclConfig]. + + .. 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 discoveryengine_v1 + + def sample_get_acl_config(): + # Create a client + client = discoveryengine_v1.AclConfigServiceClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetAclConfigRequest( + name="name_value", + ) + + # Make the request + response = client.get_acl_config(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.discoveryengine_v1.types.GetAclConfigRequest, dict]): + The request object. Request message for + GetAclConfigRequest method. + name (str): + Required. Resource name of + [AclConfig][google.cloud.discoveryengine.v1.AclConfig], + such as ``projects/*/locations/*/aclConfig``. + + If the caller does not have permission to access the + [AclConfig][google.cloud.discoveryengine.v1.AclConfig], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + 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.discoveryengine_v1.types.AclConfig: + Access Control Configuration. + """ + # 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, acl_config_service.GetAclConfigRequest): + request = acl_config_service.GetAclConfigRequest(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_acl_config] + + # 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 __enter__(self) -> "AclConfigServiceClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def list_operations( + self, + request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.ListOperationsRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.ListOperationsRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_operations] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def get_operation( + self, + request: Optional[Union[operations_pb2.GetOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.GetOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.GetOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + try: + # Send the request. + response = rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + except core_exceptions.GoogleAPICallError as e: + self._add_cred_info_for_auth_errors(e) + raise e + + def cancel_operation( + self, + request: Optional[Union[operations_pb2.CancelOperationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if request is None: + request_pb = operations_pb2.CancelOperationRequest() + elif isinstance(request, dict): + request_pb = operations_pb2.CancelOperationRequest(**request) + else: + request_pb = request + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel_operation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request_pb.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + rpc( + request_pb, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("AclConfigServiceClient",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/README.rst b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/README.rst new file mode 100644 index 000000000000..27930d4db5ee --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``AclConfigServiceTransport`` is the ABC for all transports. + +- public child ``AclConfigServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``AclConfigServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseAclConfigServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``AclConfigServiceRestTransport`` 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-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/__init__.py new file mode 100644 index 000000000000..87322302a120 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- 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 AclConfigServiceTransport +from .grpc import AclConfigServiceGrpcTransport +from .grpc_asyncio import AclConfigServiceGrpcAsyncIOTransport +from .rest import AclConfigServiceRestInterceptor, AclConfigServiceRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[AclConfigServiceTransport]] +_transport_registry["grpc"] = AclConfigServiceGrpcTransport +_transport_registry["grpc_asyncio"] = AclConfigServiceGrpcAsyncIOTransport +_transport_registry["rest"] = AclConfigServiceRestTransport + +__all__ = ( + "AclConfigServiceTransport", + "AclConfigServiceGrpcTransport", + "AclConfigServiceGrpcAsyncIOTransport", + "AclConfigServiceRestTransport", + "AclConfigServiceRestInterceptor", +) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/base.py new file mode 100644 index 000000000000..f535b941df6a --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/base.py @@ -0,0 +1,238 @@ +# -*- 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.discoveryengine_v1 import gapic_version as package_version +from google.cloud.discoveryengine_v1.types import acl_config, acl_config_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AclConfigServiceTransport(abc.ABC): + """Abstract transport class for AclConfigService.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/discoveryengine.readwrite", + "https://www.googleapis.com/auth/discoveryengine.serving.readwrite", + ) + + DEFAULT_HOST: str = "discoveryengine.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: 'discoveryengine.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.update_acl_config: gapic_v1.method.wrap_method( + self.update_acl_config, + default_timeout=None, + client_info=client_info, + ), + self.get_acl_config: gapic_v1.method.wrap_method( + self.get_acl_config, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: gapic_v1.method.wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: gapic_v1.method.wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: gapic_v1.method.wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def update_acl_config( + self, + ) -> Callable[ + [acl_config_service.UpdateAclConfigRequest], + Union[acl_config.AclConfig, Awaitable[acl_config.AclConfig]], + ]: + raise NotImplementedError() + + @property + def get_acl_config( + self, + ) -> Callable[ + [acl_config_service.GetAclConfigRequest], + Union[acl_config.AclConfig, Awaitable[acl_config.AclConfig]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[ + [operations_pb2.CancelOperationRequest], + None, + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("AclConfigServiceTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/grpc.py new file mode 100644 index 000000000000..b8d22a140145 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/grpc.py @@ -0,0 +1,446 @@ +# -*- 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 pickle +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple, Union + +import google.auth # type: ignore +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import gapic_v1, grpc_helpers +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson + +from google.cloud.discoveryengine_v1.types import acl_config, acl_config_service + +from .base import DEFAULT_CLIENT_INFO, AclConfigServiceTransport + +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__) + + +class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER + def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = response.result() + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response for {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": client_call_details.method, + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AclConfigServiceGrpcTransport(AclConfigServiceTransport): + """gRPC backend transport for AclConfigService. + + Service for managing Acl Configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + 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 a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + 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. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientInterceptor() + self._logged_channel = grpc.intercept_channel( + self._grpc_channel, self._interceptor + ) + + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): 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 optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def update_acl_config( + self, + ) -> Callable[[acl_config_service.UpdateAclConfigRequest], acl_config.AclConfig]: + r"""Return a callable for the update acl config method over gRPC. + + Default ACL configuration for use in a location of a + customer's project. Updates will only reflect to new + data stores. Existing data stores will still use the old + value. + + Returns: + Callable[[~.UpdateAclConfigRequest], + ~.AclConfig]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_acl_config" not in self._stubs: + self._stubs["update_acl_config"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1.AclConfigService/UpdateAclConfig", + request_serializer=acl_config_service.UpdateAclConfigRequest.serialize, + response_deserializer=acl_config.AclConfig.deserialize, + ) + return self._stubs["update_acl_config"] + + @property + def get_acl_config( + self, + ) -> Callable[[acl_config_service.GetAclConfigRequest], acl_config.AclConfig]: + r"""Return a callable for the get acl config method over gRPC. + + Gets the [AclConfig][google.cloud.discoveryengine.v1.AclConfig]. + + Returns: + Callable[[~.GetAclConfigRequest], + ~.AclConfig]: + 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_acl_config" not in self._stubs: + self._stubs["get_acl_config"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1.AclConfigService/GetAclConfig", + request_serializer=acl_config_service.GetAclConfigRequest.serialize, + response_deserializer=acl_config.AclConfig.deserialize, + ) + return self._stubs["get_acl_config"] + + def close(self): + self._logged_channel.close() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("AclConfigServiceGrpcTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/grpc_asyncio.py new file mode 100644 index 000000000000..254974bb139e --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/grpc_asyncio.py @@ -0,0 +1,493 @@ +# -*- 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 inspect +import json +import logging as std_logging +import pickle +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union + +import google.protobuf.message +import grpc # type: ignore +import proto # type: ignore +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf.json_format import MessageToJson +from grpc.experimental import aio # type: ignore + +from google.cloud.discoveryengine_v1.types import acl_config, acl_config_service + +from .base import DEFAULT_CLIENT_INFO, AclConfigServiceTransport +from .grpc import AclConfigServiceGrpcTransport + +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__) + + +class _LoggingClientAIOInterceptor( + grpc.aio.UnaryUnaryClientInterceptor +): # pragma: NO COVER + async def intercept_unary_unary(self, continuation, client_call_details, request): + logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ) + if logging_enabled: # pragma: NO COVER + request_metadata = client_call_details.metadata + if isinstance(request, proto.Message): + request_payload = type(request).to_json(request) + elif isinstance(request, google.protobuf.message.Message): + request_payload = MessageToJson(request) + else: + request_payload = f"{type(request).__name__}: {pickle.dumps(request)!r}" + + request_metadata = { + key: value.decode("utf-8") if isinstance(value, bytes) else value + for key, value in request_metadata + } + grpc_request = { + "payload": request_payload, + "requestMethod": "grpc", + "metadata": dict(request_metadata), + } + _LOGGER.debug( + f"Sending request for {client_call_details.method}", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": str(client_call_details.method), + "request": grpc_request, + "metadata": grpc_request["metadata"], + }, + ) + response = await continuation(client_call_details, request) + if logging_enabled: # pragma: NO COVER + response_metadata = await response.trailing_metadata() + # Convert gRPC metadata `` to list of tuples + metadata = ( + dict([(k, str(v)) for k, v in response_metadata]) + if response_metadata + else None + ) + result = await response + if isinstance(result, proto.Message): + response_payload = type(result).to_json(result) + elif isinstance(result, google.protobuf.message.Message): + response_payload = MessageToJson(result) + else: + response_payload = f"{type(result).__name__}: {pickle.dumps(result)!r}" + grpc_response = { + "payload": response_payload, + "metadata": metadata, + "status": "OK", + } + _LOGGER.debug( + f"Received response to rpc {client_call_details.method}.", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": str(client_call_details.method), + "response": grpc_response, + "metadata": grpc_response["metadata"], + }, + ) + return response + + +class AclConfigServiceGrpcAsyncIOTransport(AclConfigServiceTransport): + """gRPC AsyncIO backend transport for AclConfigService. + + Service for managing Acl Configuration. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. This argument will be + removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "discoveryengine.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if a ``channel`` instance is provided. + credentials_file (Optional[str]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if a ``channel`` instance is provided. + This argument will be removed in the next major version of this library. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + 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. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = None + self._ignore_credentials = True + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + self._interceptor = _LoggingClientAIOInterceptor() + self._grpc_channel._unary_unary_interceptors.append(self._interceptor) + self._logged_channel = self._grpc_channel + self._wrap_with_kind = ( + "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters + ) + # Wrap messages. This must be done after self._logged_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def update_acl_config( + self, + ) -> Callable[ + [acl_config_service.UpdateAclConfigRequest], Awaitable[acl_config.AclConfig] + ]: + r"""Return a callable for the update acl config method over gRPC. + + Default ACL configuration for use in a location of a + customer's project. Updates will only reflect to new + data stores. Existing data stores will still use the old + value. + + Returns: + Callable[[~.UpdateAclConfigRequest], + Awaitable[~.AclConfig]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_acl_config" not in self._stubs: + self._stubs["update_acl_config"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1.AclConfigService/UpdateAclConfig", + request_serializer=acl_config_service.UpdateAclConfigRequest.serialize, + response_deserializer=acl_config.AclConfig.deserialize, + ) + return self._stubs["update_acl_config"] + + @property + def get_acl_config( + self, + ) -> Callable[ + [acl_config_service.GetAclConfigRequest], Awaitable[acl_config.AclConfig] + ]: + r"""Return a callable for the get acl config method over gRPC. + + Gets the [AclConfig][google.cloud.discoveryengine.v1.AclConfig]. + + Returns: + Callable[[~.GetAclConfigRequest], + Awaitable[~.AclConfig]]: + 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_acl_config" not in self._stubs: + self._stubs["get_acl_config"] = self._logged_channel.unary_unary( + "/google.cloud.discoveryengine.v1.AclConfigService/GetAclConfig", + request_serializer=acl_config_service.GetAclConfigRequest.serialize, + response_deserializer=acl_config.AclConfig.deserialize, + ) + return self._stubs["get_acl_config"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.update_acl_config: self._wrap_method( + self.update_acl_config, + default_timeout=None, + client_info=client_info, + ), + self.get_acl_config: self._wrap_method( + self.get_acl_config, + default_timeout=None, + client_info=client_info, + ), + self.cancel_operation: self._wrap_method( + self.cancel_operation, + default_timeout=None, + client_info=client_info, + ), + self.get_operation: self._wrap_method( + self.get_operation, + default_timeout=None, + client_info=client_info, + ), + self.list_operations: self._wrap_method( + self.list_operations, + default_timeout=None, + client_info=client_info, + ), + } + + def _wrap_method(self, func, *args, **kwargs): + if self._wrap_with_kind: # pragma: NO COVER + kwargs["kind"] = self.kind + return gapic_v1.method_async.wrap_method(func, *args, **kwargs) + + def close(self): + return self._logged_channel.close() + + @property + def kind(self) -> str: + return "grpc_asyncio" + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_operations" not in self._stubs: + self._stubs["list_operations"] = self._logged_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + +__all__ = ("AclConfigServiceGrpcAsyncIOTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/rest.py new file mode 100644 index 000000000000..ab9d003d0dd7 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/rest.py @@ -0,0 +1,1078 @@ +# -*- 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.discoveryengine_v1._compat import transcode_request +from google.cloud.discoveryengine_v1.types import acl_config, acl_config_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseAclConfigServiceRestTransport + +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}", +) + +DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class AclConfigServiceRestInterceptor: + """Interceptor for AclConfigService. + + 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 AclConfigServiceRestTransport. + + .. code-block:: python + class MyCustomAclConfigServiceInterceptor(AclConfigServiceRestInterceptor): + def pre_get_acl_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_acl_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_acl_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_acl_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = AclConfigServiceRestTransport(interceptor=MyCustomAclConfigServiceInterceptor()) + client = AclConfigServiceClient(transport=transport) + + + """ + + def pre_get_acl_config( + self, + request: acl_config_service.GetAclConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + acl_config_service.GetAclConfigRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_acl_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AclConfigService server. + """ + return request, metadata + + def post_get_acl_config( + self, response: acl_config.AclConfig + ) -> acl_config.AclConfig: + """Post-rpc interceptor for get_acl_config + + DEPRECATED. Please use the `post_get_acl_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AclConfigService server but before + it is returned to user code. This `post_get_acl_config` interceptor runs + before the `post_get_acl_config_with_metadata` interceptor. + """ + return response + + def post_get_acl_config_with_metadata( + self, + response: acl_config.AclConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[acl_config.AclConfig, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_acl_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AclConfigService server but before it is returned to user code. + + We recommend only using this `post_get_acl_config_with_metadata` + interceptor in new development instead of the `post_get_acl_config` interceptor. + When both interceptors are used, this `post_get_acl_config_with_metadata` interceptor runs after the + `post_get_acl_config` interceptor. The (possibly modified) response returned by + `post_get_acl_config` will be passed to + `post_get_acl_config_with_metadata`. + """ + return response, metadata + + def pre_update_acl_config( + self, + request: acl_config_service.UpdateAclConfigRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + acl_config_service.UpdateAclConfigRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for update_acl_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the AclConfigService server. + """ + return request, metadata + + def post_update_acl_config( + self, response: acl_config.AclConfig + ) -> acl_config.AclConfig: + """Post-rpc interceptor for update_acl_config + + DEPRECATED. Please use the `post_update_acl_config_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the AclConfigService server but before + it is returned to user code. This `post_update_acl_config` interceptor runs + before the `post_update_acl_config_with_metadata` interceptor. + """ + return response + + def post_update_acl_config_with_metadata( + self, + response: acl_config.AclConfig, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[acl_config.AclConfig, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_acl_config + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the AclConfigService server but before it is returned to user code. + + We recommend only using this `post_update_acl_config_with_metadata` + interceptor in new development instead of the `post_update_acl_config` interceptor. + When both interceptors are used, this `post_update_acl_config_with_metadata` interceptor runs after the + `post_update_acl_config` interceptor. The (possibly modified) response returned by + `post_update_acl_config` will be passed to + `post_update_acl_config_with_metadata`. + """ + return response, metadata + + 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 AclConfigService 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 AclConfigService 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 AclConfigService 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 AclConfigService 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 AclConfigService 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 AclConfigService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class AclConfigServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: AclConfigServiceRestInterceptor + + +class AclConfigServiceRestTransport(_BaseAclConfigServiceRestTransport): + """REST backend synchronous transport for AclConfigService. + + Service for managing Acl Configuration. + + 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 = "discoveryengine.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[AclConfigServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'discoveryengine.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[AclConfigServiceRestInterceptor]): 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 AclConfigServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _GetAclConfig( + _BaseAclConfigServiceRestTransport._BaseGetAclConfig, AclConfigServiceRestStub + ): + def __hash__(self): + return hash("AclConfigServiceRestTransport.GetAclConfig") + + @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: acl_config_service.GetAclConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> acl_config.AclConfig: + r"""Call the get acl config method over HTTP. + + Args: + request (~.acl_config_service.GetAclConfigRequest): + The request object. Request message for + GetAclConfigRequest method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.acl_config.AclConfig: + Access Control Configuration. + """ + + http_options = ( + _BaseAclConfigServiceRestTransport._BaseGetAclConfig._get_http_options() + ) + request, metadata = self._interceptor.pre_get_acl_config(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAclConfigServiceRestTransport._BaseGetAclConfig, + "_BaseGetAclConfig__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.discoveryengine_v1.AclConfigServiceClient.GetAclConfig", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": "GetAclConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AclConfigServiceRestTransport._GetAclConfig._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 = acl_config.AclConfig() + pb_resp = acl_config.AclConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_acl_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_acl_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = acl_config.AclConfig.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.discoveryengine_v1.AclConfigServiceClient.get_acl_config", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": "GetAclConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _UpdateAclConfig( + _BaseAclConfigServiceRestTransport._BaseUpdateAclConfig, + AclConfigServiceRestStub, + ): + def __hash__(self): + return hash("AclConfigServiceRestTransport.UpdateAclConfig") + + @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: acl_config_service.UpdateAclConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> acl_config.AclConfig: + r"""Call the update acl config method over HTTP. + + Args: + request (~.acl_config_service.UpdateAclConfigRequest): + The request object. Request message for UpdateAclConfig + method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: + ~.acl_config.AclConfig: + Access Control Configuration. + """ + + http_options = _BaseAclConfigServiceRestTransport._BaseUpdateAclConfig._get_http_options() + request, metadata = self._interceptor.pre_update_acl_config( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAclConfigServiceRestTransport._BaseUpdateAclConfig, + "_BaseUpdateAclConfig__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=True, + ) + + 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.discoveryengine_v1.AclConfigServiceClient.UpdateAclConfig", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": "UpdateAclConfig", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AclConfigServiceRestTransport._UpdateAclConfig._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 = acl_config.AclConfig() + pb_resp = acl_config.AclConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_acl_config(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_acl_config_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = acl_config.AclConfig.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.discoveryengine_v1.AclConfigServiceClient.update_acl_config", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": "UpdateAclConfig", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get_acl_config( + self, + ) -> Callable[[acl_config_service.GetAclConfigRequest], acl_config.AclConfig]: + # 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._GetAclConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_acl_config( + self, + ) -> Callable[[acl_config_service.UpdateAclConfigRequest], acl_config.AclConfig]: + # 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._UpdateAclConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_operation(self): + return self._CancelOperation(self._session, self._host, self._interceptor) # type: ignore + + class _CancelOperation( + _BaseAclConfigServiceRestTransport._BaseCancelOperation, + AclConfigServiceRestStub, + ): + def __hash__(self): + return hash("AclConfigServiceRestTransport.CancelOperation") + + @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: operations_pb2.CancelOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> None: + r"""Call the cancel operation method over HTTP. + + Args: + request (operations_pb2.CancelOperationRequest): + The request object for CancelOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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`. + """ + + http_options = _BaseAclConfigServiceRestTransport._BaseCancelOperation._get_http_options() + request, metadata = self._interceptor.pre_cancel_operation( + request, metadata + ) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAclConfigServiceRestTransport._BaseCancelOperation, + "_BaseCancelOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + 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 = json_format.MessageToJson(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.discoveryengine_v1.AclConfigServiceClient.CancelOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": "CancelOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AclConfigServiceRestTransport._CancelOperation._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 self._interceptor.post_cancel_operation(None) + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation( + _BaseAclConfigServiceRestTransport._BaseGetOperation, AclConfigServiceRestStub + ): + def __hash__(self): + return hash("AclConfigServiceRestTransport.GetOperation") + + @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: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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: Response from GetOperation method. + """ + + http_options = ( + _BaseAclConfigServiceRestTransport._BaseGetOperation._get_http_options() + ) + request, metadata = self._interceptor.pre_get_operation(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAclConfigServiceRestTransport._BaseGetOperation, + "_BaseGetOperation__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + 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 = json_format.MessageToJson(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.discoveryengine_v1.AclConfigServiceClient.GetOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": "GetOperation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AclConfigServiceRestTransport._GetOperation._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) + + content = response.content.decode("utf-8") + resp = operations_pb2.Operation() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_get_operation(resp) + 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.discoveryengine_v1.AclConfigServiceAsyncClient.GetOperation", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": "GetOperation", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def list_operations(self): + return self._ListOperations(self._session, self._host, self._interceptor) # type: ignore + + class _ListOperations( + _BaseAclConfigServiceRestTransport._BaseListOperations, AclConfigServiceRestStub + ): + def __hash__(self): + return hash("AclConfigServiceRestTransport.ListOperations") + + @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: operations_pb2.ListOperationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Call the list operations method over HTTP. + + Args: + request (operations_pb2.ListOperationsRequest): + The request object for ListOperations method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.ListOperationsResponse: Response from ListOperations method. + """ + + http_options = _BaseAclConfigServiceRestTransport._BaseListOperations._get_http_options() + request, metadata = self._interceptor.pre_list_operations(request, metadata) + transcoded_request, body, query_params = transcode_request( + http_options, + request, + required_fields_default_values=getattr( + _BaseAclConfigServiceRestTransport._BaseListOperations, + "_BaseListOperations__REQUIRED_FIELDS_DEFAULT_VALUES", + None, + ), + rest_numeric_enums=False, + ) + + 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 = json_format.MessageToJson(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.discoveryengine_v1.AclConfigServiceClient.ListOperations", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": "ListOperations", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = AclConfigServiceRestTransport._ListOperations._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) + + content = response.content.decode("utf-8") + resp = operations_pb2.ListOperationsResponse() + resp = json_format.Parse(content, resp) + resp = self._interceptor.post_list_operations(resp) + 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.discoveryengine_v1.AclConfigServiceAsyncClient.ListOperations", + extra={ + "serviceName": "google.cloud.discoveryengine.v1.AclConfigService", + "rpcName": "ListOperations", + "httpResponse": http_response, + "metadata": http_response["headers"], + }, + ) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("AclConfigServiceRestTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/rest_base.py new file mode 100644 index 000000000000..5bcc5b0b5bb4 --- /dev/null +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/acl_config_service/transports/rest_base.py @@ -0,0 +1,308 @@ +# -*- 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.cloud.location import locations_pb2 # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import json_format + +from google.cloud.discoveryengine_v1.types import acl_config, acl_config_service + +from .base import DEFAULT_CLIENT_INFO, AclConfigServiceTransport + + +class _BaseAclConfigServiceRestTransport(AclConfigServiceTransport): + """Base REST backend transport for AclConfigService. + + 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 = "discoveryengine.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: 'discoveryengine.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 _BaseGetAclConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/aclConfig}", + }, + ] + return http_options + + class _BaseUpdateAclConfig: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{acl_config.name=projects/*/locations/*/aclConfig}", + "body": "acl_config", + }, + ] + return http_options + + class _BaseCancelOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}:cancel", + "body": "*", + }, + ] + return http_options + + class _BaseGetOperation: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataConnector/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/engines/*/assistants/*/agents/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/engines/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/dataStores/*/branches/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/dataStores/*/models/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/dataStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/identityMappingStores/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/operations/*}", + }, + ] + return http_options + + class _BaseListOperations: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataConnector}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/schemas/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine/targetSites}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/siteSearchEngine}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*/engines/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/collections/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/dataStores/*/branches/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/dataStores/*/models/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/dataStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/identityMappingStores/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*}/operations", + }, + { + "method": "get", + "uri": "/v1/{name=projects/*}/operations", + }, + ] + return http_options + + +__all__ = ("_BaseAclConfigServiceRestTransport",) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/async_client.py index fd91f576fde5..2a4293f20299 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/async_client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/async_client.py @@ -46,10 +46,18 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.AsyncRetry, object, None] # 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.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore -from google.cloud.discoveryengine_v1.types import assist_answer, assistant_service +from google.cloud.discoveryengine_v1.services.assistant_service import pagers +from google.cloud.discoveryengine_v1.types import ( + assist_answer, + assistant, + assistant_service, +) +from google.cloud.discoveryengine_v1.types import assistant as gcd_assistant from .client import AssistantServiceClient from .transports.base import DEFAULT_CLIENT_INFO, AssistantServiceTransport @@ -85,12 +93,20 @@ class AssistantServiceAsyncClient: ) assistant_path = staticmethod(AssistantServiceClient.assistant_path) parse_assistant_path = staticmethod(AssistantServiceClient.parse_assistant_path) + content_policy_path = staticmethod(AssistantServiceClient.content_policy_path) + parse_content_policy_path = staticmethod( + AssistantServiceClient.parse_content_policy_path + ) data_store_path = staticmethod(AssistantServiceClient.data_store_path) parse_data_store_path = staticmethod(AssistantServiceClient.parse_data_store_path) document_path = staticmethod(AssistantServiceClient.document_path) parse_document_path = staticmethod(AssistantServiceClient.parse_document_path) + engine_path = staticmethod(AssistantServiceClient.engine_path) + parse_engine_path = staticmethod(AssistantServiceClient.parse_engine_path) session_path = staticmethod(AssistantServiceClient.session_path) parse_session_path = staticmethod(AssistantServiceClient.parse_session_path) + template_path = staticmethod(AssistantServiceClient.template_path) + parse_template_path = staticmethod(AssistantServiceClient.parse_template_path) common_billing_account_path = staticmethod( AssistantServiceClient.common_billing_account_path ) @@ -400,6 +416,592 @@ async def sample_stream_assist(): # Done; return the response. return response + async def create_assistant( + self, + request: Optional[Union[assistant_service.CreateAssistantRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> assistant.Assistant: + r"""Creates an + [Assistant][google.cloud.discoveryengine.v1.Assistant]. + + .. 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 discoveryengine_v1 + + async def sample_create_assistant(): + # Create a client + client = discoveryengine_v1.AssistantServiceAsyncClient() + + # Initialize request argument(s) + assistant = discoveryengine_v1.Assistant() + assistant.display_name = "display_name_value" + + request = discoveryengine_v1.CreateAssistantRequest( + parent="parent_value", + assistant=assistant, + assistant_id="assistant_id_value", + ) + + # Make the request + response = await client.create_assistant(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.CreateAssistantRequest, dict]]): + The request object. Request for the + [AssistantService.CreateAssistant][google.cloud.discoveryengine.v1.AssistantService.CreateAssistant] + method. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.discoveryengine_v1.types.Assistant: + Discovery Engine Assistant resource. + """ + # 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, assistant_service.CreateAssistantRequest): + request = assistant_service.CreateAssistantRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_assistant + ] + + # 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 delete_assistant( + self, + request: Optional[Union[assistant_service.DeleteAssistantRequest, 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]]] = (), + ) -> None: + r"""Deletes an + [Assistant][google.cloud.discoveryengine.v1.Assistant]. + + .. 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 discoveryengine_v1 + + async def sample_delete_assistant(): + # Create a client + client = discoveryengine_v1.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.DeleteAssistantRequest( + name="name_value", + ) + + # Make the request + await client.delete_assistant(request=request) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.DeleteAssistantRequest, dict]]): + The request object. Request message for the + [AssistantService.DeleteAssistant][google.cloud.discoveryengine.v1.AssistantService.DeleteAssistant] + method. + name (:class:`str`): + Required. Resource name of + [Assistant][google.cloud.discoveryengine.v1.Assistant]. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/assistants/{assistant}`` + + If the caller does not have permission to delete the + [Assistant][google.cloud.discoveryengine.v1.Assistant], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [Assistant][google.cloud.discoveryengine.v1.Assistant] + to delete does not exist, a NOT_FOUND error is returned. + + 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`. + """ + # 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, assistant_service.DeleteAssistantRequest): + request = assistant_service.DeleteAssistantRequest(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_assistant + ] + + # 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. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def update_assistant( + self, + request: Optional[Union[assistant_service.UpdateAssistantRequest, dict]] = None, + *, + assistant: Optional[gcd_assistant.Assistant] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> gcd_assistant.Assistant: + r"""Updates an + [Assistant][google.cloud.discoveryengine.v1.Assistant] + + .. 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 discoveryengine_v1 + + async def sample_update_assistant(): + # Create a client + client = discoveryengine_v1.AssistantServiceAsyncClient() + + # Initialize request argument(s) + assistant = discoveryengine_v1.Assistant() + assistant.display_name = "display_name_value" + + request = discoveryengine_v1.UpdateAssistantRequest( + assistant=assistant, + ) + + # Make the request + response = await client.update_assistant(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateAssistantRequest, dict]]): + The request object. Request message for the + [AssistantService.UpdateAssistant][google.cloud.discoveryengine.v1.AssistantService.UpdateAssistant] + method. + assistant (:class:`google.cloud.discoveryengine_v1.types.Assistant`): + Required. The + [Assistant][google.cloud.discoveryengine.v1.Assistant] + to update. + + The + [Assistant][google.cloud.discoveryengine.v1.Assistant]'s + ``name`` field is used to identify the + [Assistant][google.cloud.discoveryengine.v1.Assistant] + to update. Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/assistants/{assistant}`` + + If the caller does not have permission to update the + [Assistant][google.cloud.discoveryengine.v1.Assistant], + regardless of whether or not it exists, a + PERMISSION_DENIED error is returned. + + If the + [Assistant][google.cloud.discoveryengine.v1.Assistant] + to update does not exist, a NOT_FOUND error is returned. + + This corresponds to the ``assistant`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`): + The list of fields to update. + This corresponds to the ``update_mask`` 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.discoveryengine_v1.types.Assistant: + Discovery Engine Assistant 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 = [assistant, update_mask] + 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, assistant_service.UpdateAssistantRequest): + request = assistant_service.UpdateAssistantRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if assistant is not None: + request.assistant = assistant + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_assistant + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("assistant.name", request.assistant.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 get_assistant( + self, + request: Optional[Union[assistant_service.GetAssistantRequest, 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]]] = (), + ) -> assistant.Assistant: + r"""Gets an [Assistant][google.cloud.discoveryengine.v1.Assistant]. + + .. 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 discoveryengine_v1 + + async def sample_get_assistant(): + # Create a client + client = discoveryengine_v1.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.GetAssistantRequest( + name="name_value", + ) + + # Make the request + response = await client.get_assistant(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.GetAssistantRequest, dict]]): + The request object. Request message for the + [AssistantService.GetAssistant][google.cloud.discoveryengine.v1.AssistantService.GetAssistant] + method. + name (:class:`str`): + Required. Resource name of + [Assistant][google.cloud.discoveryengine.v1.Assistant]. + Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/assistants/{assistant}`` + + 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.discoveryengine_v1.types.Assistant: + Discovery Engine Assistant 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 = [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, assistant_service.GetAssistantRequest): + request = assistant_service.GetAssistantRequest(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_assistant + ] + + # 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_assistants( + self, + request: Optional[Union[assistant_service.ListAssistantsRequest, 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.ListAssistantsAsyncPager: + r"""Lists all + [Assistant][google.cloud.discoveryengine.v1.Assistant]s under an + [Engine][google.cloud.discoveryengine.v1.Engine]. + + .. 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 discoveryengine_v1 + + async def sample_list_assistants(): + # Create a client + client = discoveryengine_v1.AssistantServiceAsyncClient() + + # Initialize request argument(s) + request = discoveryengine_v1.ListAssistantsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_assistants(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.discoveryengine_v1.types.ListAssistantsRequest, dict]]): + The request object. Request message for the + [AssistantService.ListAssistants][google.cloud.discoveryengine.v1.AssistantService.ListAssistants] + method. + parent (:class:`str`): + Required. The parent resource name. Format: + ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}`` + + 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.discoveryengine_v1.services.assistant_service.pagers.ListAssistantsAsyncPager: + Response message for the + [AssistantService.ListAssistants][google.cloud.discoveryengine.v1.AssistantService.ListAssistants] + method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + 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, assistant_service.ListAssistantsRequest): + request = assistant_service.ListAssistantsRequest(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_assistants + ] + + # 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.ListAssistantsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # 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-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/client.py index 2ced38c66c85..e2a91adc5738 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/client.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/client.py @@ -69,10 +69,18 @@ _LOGGER = std_logging.getLogger(__name__) +import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore +import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.cloud.location import locations_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore -from google.cloud.discoveryengine_v1.types import assist_answer, assistant_service +from google.cloud.discoveryengine_v1.services.assistant_service import pagers +from google.cloud.discoveryengine_v1.types import ( + assist_answer, + assistant, + assistant_service, +) +from google.cloud.discoveryengine_v1.types import assistant as gcd_assistant from .transports.base import DEFAULT_CLIENT_INFO, AssistantServiceTransport from .transports.grpc import AssistantServiceGrpcTransport @@ -228,6 +236,28 @@ def parse_assistant_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def content_policy_path( + organization: str, + location: str, + content_policy: str, + ) -> str: + """Returns a fully-qualified content_policy string.""" + return "organizations/{organization}/locations/{location}/contentPolicies/{content_policy}".format( + organization=organization, + location=location, + content_policy=content_policy, + ) + + @staticmethod + def parse_content_policy_path(path: str) -> Dict[str, str]: + """Parses a content_policy path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/locations/(?P.+?)/contentPolicies/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def data_store_path( project: str, @@ -276,6 +306,30 @@ def parse_document_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def engine_path( + project: str, + location: str, + collection: str, + engine: str, + ) -> str: + """Returns a fully-qualified engine string.""" + return "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format( + project=project, + location=location, + collection=collection, + engine=engine, + ) + + @staticmethod + def parse_engine_path(path: str) -> Dict[str, str]: + """Parses a engine path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/engines/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def session_path( project: str, @@ -300,6 +354,28 @@ def parse_session_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def template_path( + project: str, + location: str, + template: str, + ) -> str: + """Returns a fully-qualified template string.""" + return "projects/{project}/locations/{location}/templates/{template}".format( + project=project, + location=location, + template=template, + ) + + @staticmethod + def parse_template_path(path: str) -> Dict[str, str]: + """Parses a template path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/templates/(?P