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.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
@staticmethod
def common_billing_account_path(
billing_account: str,
@@ -789,6 +865,578 @@ def sample_stream_assist():
# Done; return the response.
return response
+ 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
+
+ def sample_create_assistant():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # 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 = client.create_assistant(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (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.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each 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._transport._wrapped_methods[self._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._validate_universe_domain()
+
+ # Send the request.
+ response = rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ 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
+
+ def sample_delete_assistant():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteAssistantRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ client.delete_assistant(request=request)
+
+ Args:
+ request (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 (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.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, 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._transport._wrapped_methods[self._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._validate_universe_domain()
+
+ # Send the request.
+ rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ 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
+
+ def sample_update_assistant():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # Initialize request argument(s)
+ assistant = discoveryengine_v1.Assistant()
+ assistant.display_name = "display_name_value"
+
+ request = discoveryengine_v1.UpdateAssistantRequest(
+ assistant=assistant,
+ )
+
+ # Make the request
+ response = client.update_assistant(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (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 (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 (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.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each 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._transport._wrapped_methods[self._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._validate_universe_domain()
+
+ # Send the request.
+ response = rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ 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
+
+ def sample_get_assistant():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetAssistantRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_assistant(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (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 (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.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each 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._transport._wrapped_methods[self._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._validate_universe_domain()
+
+ # Send the request.
+ response = rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ 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.ListAssistantsPager:
+ 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
+
+ def sample_list_assistants():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListAssistantsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_assistants(request=request)
+
+ # Handle the response
+ for response in page_result:
+ print(response)
+
+ Args:
+ request (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 (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.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each 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.ListAssistantsPager:
+ 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._transport._wrapped_methods[self._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._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.ListAssistantsPager(
+ method=rpc,
+ request=request,
+ response=response,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
def __enter__(self) -> "AssistantServiceClient":
return self
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/pagers.py
new file mode 100644
index 000000000000..8b79f758dfdd
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/pagers.py
@@ -0,0 +1,197 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import (
+ Any,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+ Optional,
+ Sequence,
+ Tuple,
+ Union,
+)
+
+from google.api_core import gapic_v1
+from google.api_core import retry as retries
+from google.api_core import retry_async as retries_async
+
+try:
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
+ OptionalAsyncRetry = Union[
+ retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
+ ]
+except AttributeError: # pragma: NO COVER
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
+
+from google.cloud.discoveryengine_v1.types import assistant, assistant_service
+
+
+class ListAssistantsPager:
+ """A pager for iterating through ``list_assistants`` requests.
+
+ This class thinly wraps an initial
+ :class:`google.cloud.discoveryengine_v1.types.ListAssistantsResponse` object, and
+ provides an ``__iter__`` method to iterate through its
+ ``assistants`` field.
+
+ If there are more pages, the ``__iter__`` method will make additional
+ ``ListAssistants`` requests and continue to iterate
+ through the ``assistants`` field on the
+ corresponding responses.
+
+ All the usual :class:`google.cloud.discoveryengine_v1.types.ListAssistantsResponse`
+ 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[..., assistant_service.ListAssistantsResponse],
+ request: assistant_service.ListAssistantsRequest,
+ response: assistant_service.ListAssistantsResponse,
+ *,
+ 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.discoveryengine_v1.types.ListAssistantsRequest):
+ The initial request object.
+ response (google.cloud.discoveryengine_v1.types.ListAssistantsResponse):
+ 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 = assistant_service.ListAssistantsRequest(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[assistant_service.ListAssistantsResponse]:
+ 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[assistant.Assistant]:
+ for page in self.pages:
+ yield from page.assistants
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
+class ListAssistantsAsyncPager:
+ """A pager for iterating through ``list_assistants`` requests.
+
+ This class thinly wraps an initial
+ :class:`google.cloud.discoveryengine_v1.types.ListAssistantsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``assistants`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListAssistants`` requests and continue to iterate
+ through the ``assistants`` field on the
+ corresponding responses.
+
+ All the usual :class:`google.cloud.discoveryengine_v1.types.ListAssistantsResponse`
+ 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[assistant_service.ListAssistantsResponse]],
+ request: assistant_service.ListAssistantsRequest,
+ response: assistant_service.ListAssistantsResponse,
+ *,
+ 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.discoveryengine_v1.types.ListAssistantsRequest):
+ The initial request object.
+ response (google.cloud.discoveryengine_v1.types.ListAssistantsResponse):
+ 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 = assistant_service.ListAssistantsRequest(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[assistant_service.ListAssistantsResponse]:
+ 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[assistant.Assistant]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.assistants:
+ 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-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/base.py
index e1cb4a4f0806..5c3716c739de 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/base.py
@@ -19,6 +19,7 @@
import google.api_core
import google.auth # type: ignore
import google.protobuf
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
@@ -28,7 +29,8 @@
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 assistant_service
+from google.cloud.discoveryengine_v1.types import assistant, assistant_service
+from google.cloud.discoveryengine_v1.types import assistant as gcd_assistant
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=package_version.__version__
@@ -39,7 +41,12 @@
class AssistantServiceTransport(abc.ABC):
"""Abstract transport class for AssistantService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ AUTH_SCOPES = (
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ )
DEFAULT_HOST: str = "discoveryengine.googleapis.com"
@@ -156,6 +163,31 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=300.0,
client_info=client_info,
),
+ self.create_assistant: gapic_v1.method.wrap_method(
+ self.create_assistant,
+ default_timeout=30.0,
+ client_info=client_info,
+ ),
+ self.delete_assistant: gapic_v1.method.wrap_method(
+ self.delete_assistant,
+ default_timeout=30.0,
+ client_info=client_info,
+ ),
+ self.update_assistant: gapic_v1.method.wrap_method(
+ self.update_assistant,
+ default_timeout=30.0,
+ client_info=client_info,
+ ),
+ self.get_assistant: gapic_v1.method.wrap_method(
+ self.get_assistant,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.list_assistants: gapic_v1.method.wrap_method(
+ self.list_assistants,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.cancel_operation: gapic_v1.method.wrap_method(
self.cancel_operation,
default_timeout=None,
@@ -194,6 +226,54 @@ def stream_assist(
]:
raise NotImplementedError()
+ @property
+ def create_assistant(
+ self,
+ ) -> Callable[
+ [assistant_service.CreateAssistantRequest],
+ Union[assistant.Assistant, Awaitable[assistant.Assistant]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def delete_assistant(
+ self,
+ ) -> Callable[
+ [assistant_service.DeleteAssistantRequest],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def update_assistant(
+ self,
+ ) -> Callable[
+ [assistant_service.UpdateAssistantRequest],
+ Union[gcd_assistant.Assistant, Awaitable[gcd_assistant.Assistant]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def get_assistant(
+ self,
+ ) -> Callable[
+ [assistant_service.GetAssistantRequest],
+ Union[assistant.Assistant, Awaitable[assistant.Assistant]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def list_assistants(
+ self,
+ ) -> Callable[
+ [assistant_service.ListAssistantsRequest],
+ Union[
+ assistant_service.ListAssistantsResponse,
+ Awaitable[assistant_service.ListAssistantsResponse],
+ ],
+ ]:
+ raise NotImplementedError()
+
@property
def list_operations(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/grpc.py
index 83f67a306152..1c085b279335 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/grpc.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/grpc.py
@@ -20,6 +20,7 @@
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
import google.auth # type: ignore
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
@@ -30,7 +31,8 @@
from google.longrunning import operations_pb2 # type: ignore
from google.protobuf.json_format import MessageToJson
-from google.cloud.discoveryengine_v1.types import assistant_service
+from google.cloud.discoveryengine_v1.types import assistant, assistant_service
+from google.cloud.discoveryengine_v1.types import assistant as gcd_assistant
from .base import DEFAULT_CLIENT_INFO, AssistantServiceTransport
@@ -356,6 +358,144 @@ def stream_assist(
)
return self._stubs["stream_assist"]
+ @property
+ def create_assistant(
+ self,
+ ) -> Callable[[assistant_service.CreateAssistantRequest], assistant.Assistant]:
+ r"""Return a callable for the create assistant method over gRPC.
+
+ Creates an
+ [Assistant][google.cloud.discoveryengine.v1.Assistant].
+
+ Returns:
+ Callable[[~.CreateAssistantRequest],
+ ~.Assistant]:
+ 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_assistant" not in self._stubs:
+ self._stubs["create_assistant"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/CreateAssistant",
+ request_serializer=assistant_service.CreateAssistantRequest.serialize,
+ response_deserializer=assistant.Assistant.deserialize,
+ )
+ return self._stubs["create_assistant"]
+
+ @property
+ def delete_assistant(
+ self,
+ ) -> Callable[[assistant_service.DeleteAssistantRequest], empty_pb2.Empty]:
+ r"""Return a callable for the delete assistant method over gRPC.
+
+ Deletes an
+ [Assistant][google.cloud.discoveryengine.v1.Assistant].
+
+ Returns:
+ Callable[[~.DeleteAssistantRequest],
+ ~.Empty]:
+ 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_assistant" not in self._stubs:
+ self._stubs["delete_assistant"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/DeleteAssistant",
+ request_serializer=assistant_service.DeleteAssistantRequest.serialize,
+ response_deserializer=empty_pb2.Empty.FromString,
+ )
+ return self._stubs["delete_assistant"]
+
+ @property
+ def update_assistant(
+ self,
+ ) -> Callable[[assistant_service.UpdateAssistantRequest], gcd_assistant.Assistant]:
+ r"""Return a callable for the update assistant method over gRPC.
+
+ Updates an
+ [Assistant][google.cloud.discoveryengine.v1.Assistant]
+
+ Returns:
+ Callable[[~.UpdateAssistantRequest],
+ ~.Assistant]:
+ 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_assistant" not in self._stubs:
+ self._stubs["update_assistant"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/UpdateAssistant",
+ request_serializer=assistant_service.UpdateAssistantRequest.serialize,
+ response_deserializer=gcd_assistant.Assistant.deserialize,
+ )
+ return self._stubs["update_assistant"]
+
+ @property
+ def get_assistant(
+ self,
+ ) -> Callable[[assistant_service.GetAssistantRequest], assistant.Assistant]:
+ r"""Return a callable for the get assistant method over gRPC.
+
+ Gets an [Assistant][google.cloud.discoveryengine.v1.Assistant].
+
+ Returns:
+ Callable[[~.GetAssistantRequest],
+ ~.Assistant]:
+ 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_assistant" not in self._stubs:
+ self._stubs["get_assistant"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/GetAssistant",
+ request_serializer=assistant_service.GetAssistantRequest.serialize,
+ response_deserializer=assistant.Assistant.deserialize,
+ )
+ return self._stubs["get_assistant"]
+
+ @property
+ def list_assistants(
+ self,
+ ) -> Callable[
+ [assistant_service.ListAssistantsRequest],
+ assistant_service.ListAssistantsResponse,
+ ]:
+ r"""Return a callable for the list assistants method over gRPC.
+
+ Lists all
+ [Assistant][google.cloud.discoveryengine.v1.Assistant]s under an
+ [Engine][google.cloud.discoveryengine.v1.Engine].
+
+ Returns:
+ Callable[[~.ListAssistantsRequest],
+ ~.ListAssistantsResponse]:
+ 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_assistants" not in self._stubs:
+ self._stubs["list_assistants"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/ListAssistants",
+ request_serializer=assistant_service.ListAssistantsRequest.serialize,
+ response_deserializer=assistant_service.ListAssistantsResponse.deserialize,
+ )
+ return self._stubs["list_assistants"]
+
def close(self):
self._logged_channel.close()
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/grpc_asyncio.py
index 648963b95ece..ff9967dc13ea 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/grpc_asyncio.py
@@ -20,6 +20,7 @@
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
@@ -33,7 +34,8 @@
from google.protobuf.json_format import MessageToJson
from grpc.experimental import aio # type: ignore
-from google.cloud.discoveryengine_v1.types import assistant_service
+from google.cloud.discoveryengine_v1.types import assistant, assistant_service
+from google.cloud.discoveryengine_v1.types import assistant as gcd_assistant
from .base import DEFAULT_CLIENT_INFO, AssistantServiceTransport
from .grpc import AssistantServiceGrpcTransport
@@ -365,6 +367,152 @@ def stream_assist(
)
return self._stubs["stream_assist"]
+ @property
+ def create_assistant(
+ self,
+ ) -> Callable[
+ [assistant_service.CreateAssistantRequest], Awaitable[assistant.Assistant]
+ ]:
+ r"""Return a callable for the create assistant method over gRPC.
+
+ Creates an
+ [Assistant][google.cloud.discoveryengine.v1.Assistant].
+
+ Returns:
+ Callable[[~.CreateAssistantRequest],
+ Awaitable[~.Assistant]]:
+ 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_assistant" not in self._stubs:
+ self._stubs["create_assistant"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/CreateAssistant",
+ request_serializer=assistant_service.CreateAssistantRequest.serialize,
+ response_deserializer=assistant.Assistant.deserialize,
+ )
+ return self._stubs["create_assistant"]
+
+ @property
+ def delete_assistant(
+ self,
+ ) -> Callable[
+ [assistant_service.DeleteAssistantRequest], Awaitable[empty_pb2.Empty]
+ ]:
+ r"""Return a callable for the delete assistant method over gRPC.
+
+ Deletes an
+ [Assistant][google.cloud.discoveryengine.v1.Assistant].
+
+ Returns:
+ Callable[[~.DeleteAssistantRequest],
+ Awaitable[~.Empty]]:
+ 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_assistant" not in self._stubs:
+ self._stubs["delete_assistant"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/DeleteAssistant",
+ request_serializer=assistant_service.DeleteAssistantRequest.serialize,
+ response_deserializer=empty_pb2.Empty.FromString,
+ )
+ return self._stubs["delete_assistant"]
+
+ @property
+ def update_assistant(
+ self,
+ ) -> Callable[
+ [assistant_service.UpdateAssistantRequest], Awaitable[gcd_assistant.Assistant]
+ ]:
+ r"""Return a callable for the update assistant method over gRPC.
+
+ Updates an
+ [Assistant][google.cloud.discoveryengine.v1.Assistant]
+
+ Returns:
+ Callable[[~.UpdateAssistantRequest],
+ Awaitable[~.Assistant]]:
+ 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_assistant" not in self._stubs:
+ self._stubs["update_assistant"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/UpdateAssistant",
+ request_serializer=assistant_service.UpdateAssistantRequest.serialize,
+ response_deserializer=gcd_assistant.Assistant.deserialize,
+ )
+ return self._stubs["update_assistant"]
+
+ @property
+ def get_assistant(
+ self,
+ ) -> Callable[
+ [assistant_service.GetAssistantRequest], Awaitable[assistant.Assistant]
+ ]:
+ r"""Return a callable for the get assistant method over gRPC.
+
+ Gets an [Assistant][google.cloud.discoveryengine.v1.Assistant].
+
+ Returns:
+ Callable[[~.GetAssistantRequest],
+ Awaitable[~.Assistant]]:
+ 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_assistant" not in self._stubs:
+ self._stubs["get_assistant"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/GetAssistant",
+ request_serializer=assistant_service.GetAssistantRequest.serialize,
+ response_deserializer=assistant.Assistant.deserialize,
+ )
+ return self._stubs["get_assistant"]
+
+ @property
+ def list_assistants(
+ self,
+ ) -> Callable[
+ [assistant_service.ListAssistantsRequest],
+ Awaitable[assistant_service.ListAssistantsResponse],
+ ]:
+ r"""Return a callable for the list assistants method over gRPC.
+
+ Lists all
+ [Assistant][google.cloud.discoveryengine.v1.Assistant]s under an
+ [Engine][google.cloud.discoveryengine.v1.Engine].
+
+ Returns:
+ Callable[[~.ListAssistantsRequest],
+ Awaitable[~.ListAssistantsResponse]]:
+ 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_assistants" not in self._stubs:
+ self._stubs["list_assistants"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.AssistantService/ListAssistants",
+ request_serializer=assistant_service.ListAssistantsRequest.serialize,
+ response_deserializer=assistant_service.ListAssistantsResponse.deserialize,
+ )
+ return self._stubs["list_assistants"]
+
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
@@ -382,6 +530,31 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=300.0,
client_info=client_info,
),
+ self.create_assistant: self._wrap_method(
+ self.create_assistant,
+ default_timeout=30.0,
+ client_info=client_info,
+ ),
+ self.delete_assistant: self._wrap_method(
+ self.delete_assistant,
+ default_timeout=30.0,
+ client_info=client_info,
+ ),
+ self.update_assistant: self._wrap_method(
+ self.update_assistant,
+ default_timeout=30.0,
+ client_info=client_info,
+ ),
+ self.get_assistant: self._wrap_method(
+ self.get_assistant,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.list_assistants: self._wrap_method(
+ self.list_assistants,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.cancel_operation: self._wrap_method(
self.cancel_operation,
default_timeout=None,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/rest.py
index 684507deb85f..b7c3a1ce3200 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/rest.py
@@ -20,6 +20,7 @@
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import google.protobuf
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
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
@@ -31,7 +32,8 @@
from requests import __version__ as requests_version
from google.cloud.discoveryengine_v1._compat import transcode_request
-from google.cloud.discoveryengine_v1.types import assistant_service
+from google.cloud.discoveryengine_v1.types import assistant, assistant_service
+from google.cloud.discoveryengine_v1.types import assistant as gcd_assistant
from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
from .rest_base import _BaseAssistantServiceRestTransport
@@ -74,6 +76,34 @@ class AssistantServiceRestInterceptor:
.. code-block:: python
class MyCustomAssistantServiceInterceptor(AssistantServiceRestInterceptor):
+ def pre_create_assistant(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_create_assistant(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_delete_assistant(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def pre_get_assistant(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_get_assistant(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_list_assistants(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_list_assistants(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
def pre_stream_assist(self, request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
@@ -82,12 +112,181 @@ def post_stream_assist(self, response):
logging.log(f"Received response: {response}")
return response
+ def pre_update_assistant(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_update_assistant(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
transport = AssistantServiceRestTransport(interceptor=MyCustomAssistantServiceInterceptor())
client = AssistantServiceClient(transport=transport)
"""
+ def pre_create_assistant(
+ self,
+ request: assistant_service.CreateAssistantRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ assistant_service.CreateAssistantRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for create_assistant
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the AssistantService server.
+ """
+ return request, metadata
+
+ def post_create_assistant(
+ self, response: assistant.Assistant
+ ) -> assistant.Assistant:
+ """Post-rpc interceptor for create_assistant
+
+ DEPRECATED. Please use the `post_create_assistant_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the AssistantService server but before
+ it is returned to user code. This `post_create_assistant` interceptor runs
+ before the `post_create_assistant_with_metadata` interceptor.
+ """
+ return response
+
+ def post_create_assistant_with_metadata(
+ self,
+ response: assistant.Assistant,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[assistant.Assistant, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for create_assistant
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the AssistantService server but before it is returned to user code.
+
+ We recommend only using this `post_create_assistant_with_metadata`
+ interceptor in new development instead of the `post_create_assistant` interceptor.
+ When both interceptors are used, this `post_create_assistant_with_metadata` interceptor runs after the
+ `post_create_assistant` interceptor. The (possibly modified) response returned by
+ `post_create_assistant` will be passed to
+ `post_create_assistant_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_delete_assistant(
+ self,
+ request: assistant_service.DeleteAssistantRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ assistant_service.DeleteAssistantRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for delete_assistant
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the AssistantService server.
+ """
+ return request, metadata
+
+ def pre_get_assistant(
+ self,
+ request: assistant_service.GetAssistantRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ assistant_service.GetAssistantRequest, Sequence[Tuple[str, Union[str, bytes]]]
+ ]:
+ """Pre-rpc interceptor for get_assistant
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the AssistantService server.
+ """
+ return request, metadata
+
+ def post_get_assistant(self, response: assistant.Assistant) -> assistant.Assistant:
+ """Post-rpc interceptor for get_assistant
+
+ DEPRECATED. Please use the `post_get_assistant_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the AssistantService server but before
+ it is returned to user code. This `post_get_assistant` interceptor runs
+ before the `post_get_assistant_with_metadata` interceptor.
+ """
+ return response
+
+ def post_get_assistant_with_metadata(
+ self,
+ response: assistant.Assistant,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[assistant.Assistant, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for get_assistant
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the AssistantService server but before it is returned to user code.
+
+ We recommend only using this `post_get_assistant_with_metadata`
+ interceptor in new development instead of the `post_get_assistant` interceptor.
+ When both interceptors are used, this `post_get_assistant_with_metadata` interceptor runs after the
+ `post_get_assistant` interceptor. The (possibly modified) response returned by
+ `post_get_assistant` will be passed to
+ `post_get_assistant_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_list_assistants(
+ self,
+ request: assistant_service.ListAssistantsRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ assistant_service.ListAssistantsRequest, Sequence[Tuple[str, Union[str, bytes]]]
+ ]:
+ """Pre-rpc interceptor for list_assistants
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the AssistantService server.
+ """
+ return request, metadata
+
+ def post_list_assistants(
+ self, response: assistant_service.ListAssistantsResponse
+ ) -> assistant_service.ListAssistantsResponse:
+ """Post-rpc interceptor for list_assistants
+
+ DEPRECATED. Please use the `post_list_assistants_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the AssistantService server but before
+ it is returned to user code. This `post_list_assistants` interceptor runs
+ before the `post_list_assistants_with_metadata` interceptor.
+ """
+ return response
+
+ def post_list_assistants_with_metadata(
+ self,
+ response: assistant_service.ListAssistantsResponse,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ assistant_service.ListAssistantsResponse,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Post-rpc interceptor for list_assistants
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the AssistantService server but before it is returned to user code.
+
+ We recommend only using this `post_list_assistants_with_metadata`
+ interceptor in new development instead of the `post_list_assistants` interceptor.
+ When both interceptors are used, this `post_list_assistants_with_metadata` interceptor runs after the
+ `post_list_assistants` interceptor. The (possibly modified) response returned by
+ `post_list_assistants` will be passed to
+ `post_list_assistants_with_metadata`.
+ """
+ return response, metadata
+
def pre_stream_assist(
self,
request: assistant_service.StreamAssistRequest,
@@ -138,6 +337,55 @@ def post_stream_assist_with_metadata(
"""
return response, metadata
+ def pre_update_assistant(
+ self,
+ request: assistant_service.UpdateAssistantRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ assistant_service.UpdateAssistantRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for update_assistant
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the AssistantService server.
+ """
+ return request, metadata
+
+ def post_update_assistant(
+ self, response: gcd_assistant.Assistant
+ ) -> gcd_assistant.Assistant:
+ """Post-rpc interceptor for update_assistant
+
+ DEPRECATED. Please use the `post_update_assistant_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the AssistantService server but before
+ it is returned to user code. This `post_update_assistant` interceptor runs
+ before the `post_update_assistant_with_metadata` interceptor.
+ """
+ return response
+
+ def post_update_assistant_with_metadata(
+ self,
+ response: gcd_assistant.Assistant,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[gcd_assistant.Assistant, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for update_assistant
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the AssistantService server but before it is returned to user code.
+
+ We recommend only using this `post_update_assistant_with_metadata`
+ interceptor in new development instead of the `post_update_assistant` interceptor.
+ When both interceptors are used, this `post_update_assistant_with_metadata` interceptor runs after the
+ `post_update_assistant` interceptor. The (possibly modified) response returned by
+ `post_update_assistant` will be passed to
+ `post_update_assistant_with_metadata`.
+ """
+ return response, metadata
+
def pre_cancel_operation(
self,
request: operations_pb2.CancelOperationRequest,
@@ -306,11 +554,12 @@ def __init__(
self._interceptor = interceptor or AssistantServiceRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _StreamAssist(
- _BaseAssistantServiceRestTransport._BaseStreamAssist, AssistantServiceRestStub
+ class _CreateAssistant(
+ _BaseAssistantServiceRestTransport._BaseCreateAssistant,
+ AssistantServiceRestStub,
):
def __hash__(self):
- return hash("AssistantServiceRestTransport.StreamAssist")
+ return hash("AssistantServiceRestTransport.CreateAssistant")
@staticmethod
def _get_response(
@@ -332,24 +581,23 @@ def _get_response(
headers=headers,
params=rest_helpers.flatten_query_params(query_params, strict=True),
data=body,
- stream=True,
)
return response
def __call__(
self,
- request: assistant_service.StreamAssistRequest,
+ request: assistant_service.CreateAssistantRequest,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Optional[float] = None,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
- ) -> rest_streaming.ResponseIterator:
- r"""Call the stream assist method over HTTP.
+ ) -> assistant.Assistant:
+ r"""Call the create assistant method over HTTP.
Args:
- request (~.assistant_service.StreamAssistRequest):
+ request (~.assistant_service.CreateAssistantRequest):
The request object. Request for the
- [AssistantService.StreamAssist][google.cloud.discoveryengine.v1.AssistantService.StreamAssist]
+ [AssistantService.CreateAssistant][google.cloud.discoveryengine.v1.AssistantService.CreateAssistant]
method.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
@@ -360,23 +608,20 @@ def __call__(
be of type `bytes`.
Returns:
- ~.assistant_service.StreamAssistResponse:
- Response for the
- [AssistantService.StreamAssist][google.cloud.discoveryengine.v1.AssistantService.StreamAssist]
- method.
-
+ ~.assistant.Assistant:
+ Discovery Engine Assistant resource.
"""
- http_options = (
- _BaseAssistantServiceRestTransport._BaseStreamAssist._get_http_options()
+ http_options = _BaseAssistantServiceRestTransport._BaseCreateAssistant._get_http_options()
+ request, metadata = self._interceptor.pre_create_assistant(
+ request, metadata
)
- request, metadata = self._interceptor.pre_stream_assist(request, metadata)
transcoded_request, body, query_params = transcode_request(
http_options,
request,
required_fields_default_values=getattr(
- _BaseAssistantServiceRestTransport._BaseStreamAssist,
- "_BaseStreamAssist__REQUIRED_FIELDS_DEFAULT_VALUES",
+ _BaseAssistantServiceRestTransport._BaseCreateAssistant,
+ "_BaseCreateAssistant__REQUIRED_FIELDS_DEFAULT_VALUES",
None,
),
rest_numeric_enums=True,
@@ -400,17 +645,17 @@ def __call__(
"headers": dict(metadata),
}
_LOGGER.debug(
- f"Sending request for google.cloud.discoveryengine_v1.AssistantServiceClient.StreamAssist",
+ f"Sending request for google.cloud.discoveryengine_v1.AssistantServiceClient.CreateAssistant",
extra={
"serviceName": "google.cloud.discoveryengine.v1.AssistantService",
- "rpcName": "StreamAssist",
+ "rpcName": "CreateAssistant",
"httpRequest": http_request,
"metadata": http_request["headers"],
},
)
# Send the request
- response = AssistantServiceRestTransport._StreamAssist._get_response(
+ response = AssistantServiceRestTransport._CreateAssistant._get_response(
self._host,
metadata,
query_params,
@@ -426,42 +671,795 @@ def __call__(
raise core_exceptions.from_http_response(response)
# Return the response
- resp = rest_streaming.ResponseIterator(
- response, assistant_service.StreamAssistResponse
- )
+ resp = assistant.Assistant()
+ pb_resp = assistant.Assistant.pb(resp)
- resp = self._interceptor.post_stream_assist(resp)
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_create_assistant(resp)
response_metadata = [(k, str(v)) for k, v in response.headers.items()]
- resp, _ = self._interceptor.post_stream_assist_with_metadata(
+ resp, _ = self._interceptor.post_create_assistant_with_metadata(
resp, response_metadata
)
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
logging.DEBUG
): # pragma: NO COVER
+ try:
+ response_payload = assistant.Assistant.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.AssistantServiceClient.stream_assist",
+ "Received response for google.cloud.discoveryengine_v1.AssistantServiceClient.create_assistant",
extra={
"serviceName": "google.cloud.discoveryengine.v1.AssistantService",
- "rpcName": "StreamAssist",
+ "rpcName": "CreateAssistant",
"metadata": http_response["headers"],
"httpResponse": http_response,
},
)
return resp
- @property
- def stream_assist(
- self,
- ) -> Callable[
- [assistant_service.StreamAssistRequest], assistant_service.StreamAssistResponse
- ]:
- # 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._StreamAssist(self._session, self._host, self._interceptor) # type: ignore
+ class _DeleteAssistant(
+ _BaseAssistantServiceRestTransport._BaseDeleteAssistant,
+ AssistantServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("AssistantServiceRestTransport.DeleteAssistant")
+
+ @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: assistant_service.DeleteAssistantRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ):
+ r"""Call the delete assistant method over HTTP.
+
+ Args:
+ request (~.assistant_service.DeleteAssistantRequest):
+ The request object. Request message for the
+ [AssistantService.DeleteAssistant][google.cloud.discoveryengine.v1.AssistantService.DeleteAssistant]
+ 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 = _BaseAssistantServiceRestTransport._BaseDeleteAssistant._get_http_options()
+ request, metadata = self._interceptor.pre_delete_assistant(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseAssistantServiceRestTransport._BaseDeleteAssistant,
+ "_BaseDeleteAssistant__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.AssistantServiceClient.DeleteAssistant",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.AssistantService",
+ "rpcName": "DeleteAssistant",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = AssistantServiceRestTransport._DeleteAssistant._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)
+
+ class _GetAssistant(
+ _BaseAssistantServiceRestTransport._BaseGetAssistant, AssistantServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("AssistantServiceRestTransport.GetAssistant")
+
+ @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: assistant_service.GetAssistantRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> assistant.Assistant:
+ r"""Call the get assistant method over HTTP.
+
+ Args:
+ request (~.assistant_service.GetAssistantRequest):
+ The request object. Request message for the
+ [AssistantService.GetAssistant][google.cloud.discoveryengine.v1.AssistantService.GetAssistant]
+ 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:
+ ~.assistant.Assistant:
+ Discovery Engine Assistant resource.
+ """
+
+ http_options = (
+ _BaseAssistantServiceRestTransport._BaseGetAssistant._get_http_options()
+ )
+ request, metadata = self._interceptor.pre_get_assistant(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseAssistantServiceRestTransport._BaseGetAssistant,
+ "_BaseGetAssistant__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.AssistantServiceClient.GetAssistant",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.AssistantService",
+ "rpcName": "GetAssistant",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = AssistantServiceRestTransport._GetAssistant._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 = assistant.Assistant()
+ pb_resp = assistant.Assistant.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_get_assistant(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_get_assistant_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = assistant.Assistant.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.AssistantServiceClient.get_assistant",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.AssistantService",
+ "rpcName": "GetAssistant",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _ListAssistants(
+ _BaseAssistantServiceRestTransport._BaseListAssistants, AssistantServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("AssistantServiceRestTransport.ListAssistants")
+
+ @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: assistant_service.ListAssistantsRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> assistant_service.ListAssistantsResponse:
+ r"""Call the list assistants method over HTTP.
+
+ Args:
+ request (~.assistant_service.ListAssistantsRequest):
+ The request object. Request message for the
+ [AssistantService.ListAssistants][google.cloud.discoveryengine.v1.AssistantService.ListAssistants]
+ 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:
+ ~.assistant_service.ListAssistantsResponse:
+ Response message for the
+ [AssistantService.ListAssistants][google.cloud.discoveryengine.v1.AssistantService.ListAssistants]
+ method.
+
+ """
+
+ http_options = _BaseAssistantServiceRestTransport._BaseListAssistants._get_http_options()
+ request, metadata = self._interceptor.pre_list_assistants(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseAssistantServiceRestTransport._BaseListAssistants,
+ "_BaseListAssistants__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.AssistantServiceClient.ListAssistants",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.AssistantService",
+ "rpcName": "ListAssistants",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = AssistantServiceRestTransport._ListAssistants._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 = assistant_service.ListAssistantsResponse()
+ pb_resp = assistant_service.ListAssistantsResponse.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_list_assistants(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_list_assistants_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = assistant_service.ListAssistantsResponse.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.AssistantServiceClient.list_assistants",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.AssistantService",
+ "rpcName": "ListAssistants",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _StreamAssist(
+ _BaseAssistantServiceRestTransport._BaseStreamAssist, AssistantServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("AssistantServiceRestTransport.StreamAssist")
+
+ @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,
+ stream=True,
+ )
+ return response
+
+ def __call__(
+ self,
+ request: assistant_service.StreamAssistRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> rest_streaming.ResponseIterator:
+ r"""Call the stream assist method over HTTP.
+
+ Args:
+ request (~.assistant_service.StreamAssistRequest):
+ The request object. Request for the
+ [AssistantService.StreamAssist][google.cloud.discoveryengine.v1.AssistantService.StreamAssist]
+ 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:
+ ~.assistant_service.StreamAssistResponse:
+ Response for the
+ [AssistantService.StreamAssist][google.cloud.discoveryengine.v1.AssistantService.StreamAssist]
+ method.
+
+ """
+
+ http_options = (
+ _BaseAssistantServiceRestTransport._BaseStreamAssist._get_http_options()
+ )
+ request, metadata = self._interceptor.pre_stream_assist(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseAssistantServiceRestTransport._BaseStreamAssist,
+ "_BaseStreamAssist__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.AssistantServiceClient.StreamAssist",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.AssistantService",
+ "rpcName": "StreamAssist",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = AssistantServiceRestTransport._StreamAssist._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 = rest_streaming.ResponseIterator(
+ response, assistant_service.StreamAssistResponse
+ )
+
+ resp = self._interceptor.post_stream_assist(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_stream_assist_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ http_response = {
+ "headers": dict(response.headers),
+ "status": response.status_code,
+ }
+ _LOGGER.debug(
+ "Received response for google.cloud.discoveryengine_v1.AssistantServiceClient.stream_assist",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.AssistantService",
+ "rpcName": "StreamAssist",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _UpdateAssistant(
+ _BaseAssistantServiceRestTransport._BaseUpdateAssistant,
+ AssistantServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("AssistantServiceRestTransport.UpdateAssistant")
+
+ @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: assistant_service.UpdateAssistantRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> gcd_assistant.Assistant:
+ r"""Call the update assistant method over HTTP.
+
+ Args:
+ request (~.assistant_service.UpdateAssistantRequest):
+ The request object. Request message for the
+ [AssistantService.UpdateAssistant][google.cloud.discoveryengine.v1.AssistantService.UpdateAssistant]
+ 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:
+ ~.gcd_assistant.Assistant:
+ Discovery Engine Assistant resource.
+ """
+
+ http_options = _BaseAssistantServiceRestTransport._BaseUpdateAssistant._get_http_options()
+ request, metadata = self._interceptor.pre_update_assistant(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseAssistantServiceRestTransport._BaseUpdateAssistant,
+ "_BaseUpdateAssistant__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.AssistantServiceClient.UpdateAssistant",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.AssistantService",
+ "rpcName": "UpdateAssistant",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = AssistantServiceRestTransport._UpdateAssistant._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 = gcd_assistant.Assistant()
+ pb_resp = gcd_assistant.Assistant.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_update_assistant(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_update_assistant_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = gcd_assistant.Assistant.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.AssistantServiceClient.update_assistant",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.AssistantService",
+ "rpcName": "UpdateAssistant",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ @property
+ def create_assistant(
+ self,
+ ) -> Callable[[assistant_service.CreateAssistantRequest], assistant.Assistant]:
+ # 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._CreateAssistant(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def delete_assistant(
+ self,
+ ) -> Callable[[assistant_service.DeleteAssistantRequest], empty_pb2.Empty]:
+ # 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._DeleteAssistant(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def get_assistant(
+ self,
+ ) -> Callable[[assistant_service.GetAssistantRequest], assistant.Assistant]:
+ # 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._GetAssistant(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def list_assistants(
+ self,
+ ) -> Callable[
+ [assistant_service.ListAssistantsRequest],
+ assistant_service.ListAssistantsResponse,
+ ]:
+ # 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._ListAssistants(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def stream_assist(
+ self,
+ ) -> Callable[
+ [assistant_service.StreamAssistRequest], assistant_service.StreamAssistResponse
+ ]:
+ # 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._StreamAssist(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def update_assistant(
+ self,
+ ) -> Callable[[assistant_service.UpdateAssistantRequest], gcd_assistant.Assistant]:
+ # 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._UpdateAssistant(self._session, self._host, self._interceptor) # type: ignore
@property
def cancel_operation(self):
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/rest_base.py
index 54334bd21477..1380b036d5ad 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/assistant_service/transports/rest_base.py
@@ -17,12 +17,14 @@
import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
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 assistant_service
+from google.cloud.discoveryengine_v1.types import assistant, assistant_service
+from google.cloud.discoveryengine_v1.types import assistant as gcd_assistant
from .base import DEFAULT_CLIENT_INFO, AssistantServiceTransport
@@ -89,6 +91,73 @@ def __init__(
api_audience=api_audience,
)
+ class _BaseCreateAssistant:
+ def __hash__(self): # pragma: NO COVER
+ return NotImplementedError("__hash__ must be implemented.")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
+ "assistantId": "",
+ }
+
+ @staticmethod
+ def _get_http_options():
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v1/{parent=projects/*/locations/*/collections/*/engines/*}/assistants",
+ "body": "assistant",
+ },
+ ]
+ return http_options
+
+ class _BaseDeleteAssistant:
+ 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/*/collections/*/engines/*/assistants/*}",
+ },
+ ]
+ return http_options
+
+ class _BaseGetAssistant:
+ 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/*/collections/*/engines/*/assistants/*}",
+ },
+ ]
+ return http_options
+
+ class _BaseListAssistants:
+ 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/*/collections/*/engines/*}/assistants",
+ },
+ ]
+ return http_options
+
class _BaseStreamAssist:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@@ -106,6 +175,23 @@ def _get_http_options():
]
return http_options
+ class _BaseUpdateAssistant:
+ 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/{assistant.name=projects/*/locations/*/collections/*/engines/*/assistants/*}",
+ "body": "assistant",
+ },
+ ]
+ return http_options
+
class _BaseCancelOperation:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@@ -175,6 +261,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/base.py
index 50d2ca4a4c5f..6ad3bcf74b15 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/base.py
@@ -39,7 +39,11 @@
class CmekConfigServiceTransport(abc.ABC):
"""Abstract transport class for CmekConfigService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/rest.py
index cfa86c2df07d..baa63b11483c 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/rest.py
@@ -544,6 +544,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/rest_base.py
index a901f30675ef..1e498850d074 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/cmek_config_service/transports/rest_base.py
@@ -232,6 +232,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/__init__.py
new file mode 100644
index 000000000000..19aa72fcae8e
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_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 CollectionServiceAsyncClient
+from .client import CollectionServiceClient
+
+__all__ = (
+ "CollectionServiceClient",
+ "CollectionServiceAsyncClient",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/async_client.py
new file mode 100644
index 000000000000..45d84c541deb
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/async_client.py
@@ -0,0 +1,929 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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
+
+import google.api_core.operation as operation # type: ignore
+import google.api_core.operation_async as operation_async # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
+import google.protobuf.empty_pb2 as empty_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 collection_service
+
+from .client import CollectionServiceClient
+from .transports.base import DEFAULT_CLIENT_INFO, CollectionServiceTransport
+from .transports.grpc_asyncio import CollectionServiceGrpcAsyncIOTransport
+
+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 CollectionServiceAsyncClient:
+ """Service for managing
+ [Collection][google.cloud.discoveryengine.v1.Collection]s.
+ """
+
+ _client: CollectionServiceClient
+
+ # Copy defaults from the synchronous client for use here.
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
+ DEFAULT_ENDPOINT = CollectionServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = CollectionServiceClient.DEFAULT_MTLS_ENDPOINT
+ _DEFAULT_ENDPOINT_TEMPLATE = CollectionServiceClient._DEFAULT_ENDPOINT_TEMPLATE
+ _DEFAULT_UNIVERSE = CollectionServiceClient._DEFAULT_UNIVERSE
+
+ collection_path = staticmethod(CollectionServiceClient.collection_path)
+ parse_collection_path = staticmethod(CollectionServiceClient.parse_collection_path)
+ common_billing_account_path = staticmethod(
+ CollectionServiceClient.common_billing_account_path
+ )
+ parse_common_billing_account_path = staticmethod(
+ CollectionServiceClient.parse_common_billing_account_path
+ )
+ common_folder_path = staticmethod(CollectionServiceClient.common_folder_path)
+ parse_common_folder_path = staticmethod(
+ CollectionServiceClient.parse_common_folder_path
+ )
+ common_organization_path = staticmethod(
+ CollectionServiceClient.common_organization_path
+ )
+ parse_common_organization_path = staticmethod(
+ CollectionServiceClient.parse_common_organization_path
+ )
+ common_project_path = staticmethod(CollectionServiceClient.common_project_path)
+ parse_common_project_path = staticmethod(
+ CollectionServiceClient.parse_common_project_path
+ )
+ common_location_path = staticmethod(CollectionServiceClient.common_location_path)
+ parse_common_location_path = staticmethod(
+ CollectionServiceClient.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:
+ CollectionServiceAsyncClient: The constructed client.
+ """
+ sa_info_func = (
+ CollectionServiceClient.from_service_account_info.__func__ # type: ignore
+ )
+ return sa_info_func(CollectionServiceAsyncClient, 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:
+ CollectionServiceAsyncClient: The constructed client.
+ """
+ sa_file_func = (
+ CollectionServiceClient.from_service_account_file.__func__ # type: ignore
+ )
+ return sa_file_func(CollectionServiceAsyncClient, 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 CollectionServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
+
+ @property
+ def transport(self) -> CollectionServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ CollectionServiceTransport: 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 = CollectionServiceClient.get_transport_class
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[ga_credentials.Credentials] = None,
+ transport: Optional[
+ Union[
+ str,
+ CollectionServiceTransport,
+ Callable[..., CollectionServiceTransport],
+ ]
+ ] = "grpc_asyncio",
+ client_options: Optional[ClientOptions] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the collection 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,CollectionServiceTransport,Callable[..., CollectionServiceTransport]]]):
+ 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 CollectionServiceTransport 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 = CollectionServiceClient(
+ 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.CollectionServiceAsyncClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "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.CollectionService",
+ "credentialsType": None,
+ },
+ )
+
+ async def delete_collection(
+ self,
+ request: Optional[
+ Union[collection_service.DeleteCollectionRequest, 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
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ .. code-block:: python
+
+ # This snippet has been automatically generated and should be regarded as a
+ # code template only.
+ # It will require modifications to work:
+ # - It may require correct/in-range values for request initialization.
+ # - It may require specifying regional endpoints when creating the service
+ # client as shown in:
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
+ from google.cloud import discoveryengine_v1
+
+ async def sample_delete_collection():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteCollectionRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ operation = await client.delete_collection(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = await operation.result()
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.DeleteCollectionRequest, dict]]):
+ The request object. Request message for
+ [CollectionService.DeleteCollection][google.cloud.discoveryengine.v1.CollectionService.DeleteCollection]
+ method.
+ name (:class:`str`):
+ Required. The full resource name of the Collection, in
+ the format of
+ ``projects/{project}/locations/{location}/collections/{collection}``.
+
+ 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, collection_service.DeleteCollectionRequest):
+ request = collection_service.DeleteCollectionRequest(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_collection
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Validate the universe domain.
+ self._client._validate_universe_domain()
+
+ # Send the request.
+ response = await rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Wrap the response in an operation future.
+ response = operation_async.from_gapic(
+ response,
+ self._client._transport.operations_client,
+ empty_pb2.Empty,
+ metadata_type=collection_service.DeleteCollectionMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def get_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Gets the IAM access control policy for a
+ [Collection][google.cloud.discoveryengine.v1.Collection]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ async def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]):
+ The request object. Request message for ``GetIamPolicy`` method.
+ resource (:class:`str`):
+ REQUIRED: The resource for which the
+ policy is being requested. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ if isinstance(request, dict):
+ request = iam_policy_pb2.GetIamPolicyRequest(**request)
+ elif not request:
+ request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.get_iam_policy
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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 set_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Sets the IAM access control policy for a
+ [Collection][google.cloud.discoveryengine.v1.Collection]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on a Collection
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``
+ ``roles/discoveryengine.agentspaceAdmin``
+ ``roles/discoveryengine.viewer``
+ ``roles/discoveryengine.agentspaceViewer``
+ ``roles/discoveryengine.user``
+ ``roles/discoveryengine.agentspaceUser`` Attempting to grant any
+ other role will result in a warning in logging.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ async def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]):
+ The request object. Request message for ``SetIamPolicy`` method.
+ resource (:class:`str`):
+ REQUIRED: The resource for which the
+ policy is being specified. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ if isinstance(request, dict):
+ request = iam_policy_pb2.SetIamPolicyRequest(**request)
+ elif not request:
+ request = iam_policy_pb2.SetIamPolicyRequest(resource=resource)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.set_iam_policy
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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) -> "CollectionServiceAsyncClient":
+ 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__ = ("CollectionServiceAsyncClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/client.py
new file mode 100644
index 000000000000..824e022ef53d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/client.py
@@ -0,0 +1,1242 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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__)
+
+import google.api_core.operation as operation # type: ignore
+import google.api_core.operation_async as operation_async # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
+import google.protobuf.empty_pb2 as empty_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 collection_service
+
+from .transports.base import DEFAULT_CLIENT_INFO, CollectionServiceTransport
+from .transports.grpc import CollectionServiceGrpcTransport
+from .transports.grpc_asyncio import CollectionServiceGrpcAsyncIOTransport
+from .transports.rest import CollectionServiceRestTransport
+
+
+class CollectionServiceClientMeta(type):
+ """Metaclass for the CollectionService 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[CollectionServiceTransport]]
+ _transport_registry["grpc"] = CollectionServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = CollectionServiceGrpcAsyncIOTransport
+ _transport_registry["rest"] = CollectionServiceRestTransport
+
+ def get_transport_class(
+ cls,
+ label: Optional[str] = None,
+ ) -> Type[CollectionServiceTransport]:
+ """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 CollectionServiceClient(metaclass=CollectionServiceClientMeta):
+ """Service for managing
+ [Collection][google.cloud.discoveryengine.v1.Collection]s.
+ """
+
+ # 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:
+ CollectionServiceClient: 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:
+ CollectionServiceClient: 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) -> CollectionServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ CollectionServiceTransport: The transport used by the client
+ instance.
+ """
+ return self._transport
+
+ @staticmethod
+ def collection_path(
+ project: str,
+ location: str,
+ collection: str,
+ ) -> str:
+ """Returns a fully-qualified collection string."""
+ return (
+ "projects/{project}/locations/{location}/collections/{collection}".format(
+ project=project,
+ location=location,
+ collection=collection,
+ )
+ )
+
+ @staticmethod
+ def parse_collection_path(path: str) -> Dict[str, str]:
+ """Parses a collection path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_billing_account_path(
+ billing_account: str,
+ ) -> str:
+ """Returns a fully-qualified billing_account string."""
+ return "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+
+ @staticmethod
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
+ """Parse a billing_account path into its component segments."""
+ m = re.match(r"^billingAccounts/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_folder_path(
+ folder: str,
+ ) -> str:
+ """Returns a fully-qualified folder string."""
+ return "folders/{folder}".format(
+ folder=folder,
+ )
+
+ @staticmethod
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
+ """Parse a folder path into its component segments."""
+ m = re.match(r"^folders/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_organization_path(
+ organization: str,
+ ) -> str:
+ """Returns a fully-qualified organization string."""
+ return "organizations/{organization}".format(
+ organization=organization,
+ )
+
+ @staticmethod
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
+ """Parse a organization path into its component segments."""
+ m = re.match(r"^organizations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_project_path(
+ project: str,
+ ) -> str:
+ """Returns a fully-qualified project string."""
+ return "projects/{project}".format(
+ project=project,
+ )
+
+ @staticmethod
+ def parse_common_project_path(path: str) -> Dict[str, str]:
+ """Parse a project path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_location_path(
+ project: str,
+ location: str,
+ ) -> str:
+ """Returns a fully-qualified location string."""
+ return "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+
+ @staticmethod
+ def parse_common_location_path(path: str) -> Dict[str, str]:
+ """Parse a location path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @classmethod
+ def get_mtls_endpoint_and_cert_source(
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
+ ):
+ """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,
+ CollectionServiceTransport,
+ Callable[..., CollectionServiceTransport],
+ ]
+ ] = None,
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the collection 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,CollectionServiceTransport,Callable[..., CollectionServiceTransport]]]):
+ 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 CollectionServiceTransport 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 = CollectionServiceClient._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=CollectionServiceClient._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, CollectionServiceTransport)
+ if transport_provided:
+ # transport is a CollectionServiceTransport 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(CollectionServiceTransport, 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=CollectionServiceClient._DEFAULT_UNIVERSE,
+ default_mtls_endpoint=CollectionServiceClient.DEFAULT_MTLS_ENDPOINT,
+ default_endpoint_template=CollectionServiceClient._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[CollectionServiceTransport],
+ Callable[..., CollectionServiceTransport],
+ ] = (
+ CollectionServiceClient.get_transport_class(transport)
+ if isinstance(transport, str) or transport is None
+ else cast(Callable[..., CollectionServiceTransport], 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.CollectionServiceClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "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.CollectionService",
+ "credentialsType": None,
+ },
+ )
+
+ def delete_collection(
+ self,
+ request: Optional[
+ Union[collection_service.DeleteCollectionRequest, 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
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ .. code-block:: python
+
+ # This snippet has been automatically generated and should be regarded as a
+ # code template only.
+ # It will require modifications to work:
+ # - It may require correct/in-range values for request initialization.
+ # - It may require specifying regional endpoints when creating the service
+ # client as shown in:
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
+ from google.cloud import discoveryengine_v1
+
+ def sample_delete_collection():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteCollectionRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ operation = client.delete_collection(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = operation.result()
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.DeleteCollectionRequest, dict]):
+ The request object. Request message for
+ [CollectionService.DeleteCollection][google.cloud.discoveryengine.v1.CollectionService.DeleteCollection]
+ method.
+ name (str):
+ Required. The full resource name of the Collection, in
+ the format of
+ ``projects/{project}/locations/{location}/collections/{collection}``.
+
+ 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, collection_service.DeleteCollectionRequest):
+ request = collection_service.DeleteCollectionRequest(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_collection]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
+ )
+
+ # Validate the universe domain.
+ self._validate_universe_domain()
+
+ # Send the request.
+ response = rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Wrap the response in an operation future.
+ response = operation.from_gapic(
+ response,
+ self._transport.operations_client,
+ empty_pb2.Empty,
+ metadata_type=collection_service.DeleteCollectionMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ def get_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Gets the IAM access control policy for a
+ [Collection][google.cloud.discoveryengine.v1.Collection]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]):
+ The request object. Request message for ``GetIamPolicy`` method.
+ resource (str):
+ REQUIRED: The resource for which the
+ policy is being requested. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each value must be of type `str`,
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
+ be of type `bytes`.
+
+ Returns:
+ google.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ if isinstance(request, dict):
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ request = iam_policy_pb2.GetIamPolicyRequest(**request)
+ elif not request:
+ # Null request, just make one.
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ if resource is not None:
+ request.resource = resource
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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 set_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Sets the IAM access control policy for a
+ [Collection][google.cloud.discoveryengine.v1.Collection]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on a Collection
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``
+ ``roles/discoveryengine.agentspaceAdmin``
+ ``roles/discoveryengine.viewer``
+ ``roles/discoveryengine.agentspaceViewer``
+ ``roles/discoveryengine.user``
+ ``roles/discoveryengine.agentspaceUser`` Attempting to grant any
+ other role will result in a warning in logging.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]):
+ The request object. Request message for ``SetIamPolicy`` method.
+ resource (str):
+ REQUIRED: The resource for which the
+ policy is being specified. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each value must be of type `str`,
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
+ be of type `bytes`.
+
+ Returns:
+ google.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ if isinstance(request, dict):
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ request = iam_policy_pb2.SetIamPolicyRequest(**request)
+ elif not request:
+ # Null request, just make one.
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ if resource is not None:
+ request.resource = resource
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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) -> "CollectionServiceClient":
+ 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__ = ("CollectionServiceClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/README.rst b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/README.rst
new file mode 100644
index 000000000000..02f36c154103
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/README.rst
@@ -0,0 +1,10 @@
+
+transport inheritance structure
+_______________________________
+
+``CollectionServiceTransport`` is the ABC for all transports.
+
+- public child ``CollectionServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``).
+- public child ``CollectionServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``).
+- private child ``_BaseCollectionServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``).
+- public child ``CollectionServiceRestTransport`` 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/collection_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/__init__.py
new file mode 100644
index 000000000000..a8df7c672cab
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_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 CollectionServiceTransport
+from .grpc import CollectionServiceGrpcTransport
+from .grpc_asyncio import CollectionServiceGrpcAsyncIOTransport
+from .rest import CollectionServiceRestInterceptor, CollectionServiceRestTransport
+
+# Compile a registry of transports.
+_transport_registry = OrderedDict() # type: Dict[str, Type[CollectionServiceTransport]]
+_transport_registry["grpc"] = CollectionServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = CollectionServiceGrpcAsyncIOTransport
+_transport_registry["rest"] = CollectionServiceRestTransport
+
+__all__ = (
+ "CollectionServiceTransport",
+ "CollectionServiceGrpcTransport",
+ "CollectionServiceGrpcAsyncIOTransport",
+ "CollectionServiceRestTransport",
+ "CollectionServiceRestInterceptor",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/base.py
new file mode 100644
index 000000000000..538d567ada16
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/base.py
@@ -0,0 +1,259 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
+import google.protobuf
+from google.api_core import exceptions as core_exceptions
+from google.api_core import gapic_v1, operations_v1
+from google.api_core import retry as retries
+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 collection_service
+
+DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=package_version.__version__
+)
+DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
+
+
+class CollectionServiceTransport(abc.ABC):
+ """Abstract transport class for CollectionService."""
+
+ 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.delete_collection: gapic_v1.method.wrap_method(
+ self.delete_collection,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.get_iam_policy: gapic_v1.method.wrap_method(
+ self.get_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.set_iam_policy: gapic_v1.method.wrap_method(
+ self.set_iam_policy,
+ 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 operations_client(self):
+ """Return the client designed to process long-running operations."""
+ raise NotImplementedError()
+
+ @property
+ def delete_collection(
+ self,
+ ) -> Callable[
+ [collection_service.DeleteCollectionRequest],
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[
+ [iam_policy_pb2.GetIamPolicyRequest],
+ Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[
+ [iam_policy_pb2.SetIamPolicyRequest],
+ Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
+ ]:
+ 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__ = ("CollectionServiceTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/grpc.py
new file mode 100644
index 000000000000..f9be8bfa0148
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/grpc.py
@@ -0,0 +1,508 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
+import google.protobuf.message
+import grpc # type: ignore
+import proto # type: ignore
+from google.api_core import gapic_v1, grpc_helpers, operations_v1
+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 collection_service
+
+from .base import DEFAULT_CLIENT_INFO, CollectionServiceTransport
+
+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.CollectionService",
+ "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.CollectionService",
+ "rpcName": client_call_details.method,
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class CollectionServiceGrpcTransport(CollectionServiceTransport):
+ """gRPC backend transport for CollectionService.
+
+ Service for managing
+ [Collection][google.cloud.discoveryengine.v1.Collection]s.
+
+ 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] = {}
+ self._operations_client: Optional[operations_v1.OperationsClient] = None
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
+
+ if 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 operations_client(self) -> operations_v1.OperationsClient:
+ """Create the client designed to process long-running operations.
+
+ This property caches on the instance; repeated calls return the same
+ client.
+ """
+ # Quick check: Only create a new client if we do not already have one.
+ if self._operations_client is None:
+ self._operations_client = operations_v1.OperationsClient(
+ self._logged_channel
+ )
+
+ # Return the client from cache.
+ return self._operations_client
+
+ @property
+ def delete_collection(
+ self,
+ ) -> Callable[
+ [collection_service.DeleteCollectionRequest], operations_pb2.Operation
+ ]:
+ r"""Return a callable for the delete collection method over gRPC.
+
+ Deletes a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Returns:
+ Callable[[~.DeleteCollectionRequest],
+ ~.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_collection" not in self._stubs:
+ self._stubs["delete_collection"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.CollectionService/DeleteCollection",
+ request_serializer=collection_service.DeleteCollectionRequest.serialize,
+ response_deserializer=operations_pb2.Operation.FromString,
+ )
+ return self._stubs["delete_collection"]
+
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
+ r"""Return a callable for the get iam policy method over gRPC.
+
+ Gets the IAM access control policy for a
+ [Collection][google.cloud.discoveryengine.v1.Collection]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ Returns:
+ Callable[[~.GetIamPolicyRequest],
+ ~.Policy]:
+ 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_iam_policy" not in self._stubs:
+ self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.CollectionService/GetIamPolicy",
+ request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["get_iam_policy"]
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
+ r"""Return a callable for the set iam policy method over gRPC.
+
+ Sets the IAM access control policy for a
+ [Collection][google.cloud.discoveryengine.v1.Collection]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on a Collection
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``
+ ``roles/discoveryengine.agentspaceAdmin``
+ ``roles/discoveryengine.viewer``
+ ``roles/discoveryengine.agentspaceViewer``
+ ``roles/discoveryengine.user``
+ ``roles/discoveryengine.agentspaceUser`` Attempting to grant any
+ other role will result in a warning in logging.
+
+ Returns:
+ Callable[[~.SetIamPolicyRequest],
+ ~.Policy]:
+ 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 "set_iam_policy" not in self._stubs:
+ self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.CollectionService/SetIamPolicy",
+ request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["set_iam_policy"]
+
+ 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__ = ("CollectionServiceGrpcTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/grpc_asyncio.py
new file mode 100644
index 000000000000..d5a48f8b4857
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/grpc_asyncio.py
@@ -0,0 +1,557 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
+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, operations_v1
+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 collection_service
+
+from .base import DEFAULT_CLIENT_INFO, CollectionServiceTransport
+from .grpc import CollectionServiceGrpcTransport
+
+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.CollectionService",
+ "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.CollectionService",
+ "rpcName": str(client_call_details.method),
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class CollectionServiceGrpcAsyncIOTransport(CollectionServiceTransport):
+ """gRPC AsyncIO backend transport for CollectionService.
+
+ Service for managing
+ [Collection][google.cloud.discoveryengine.v1.Collection]s.
+
+ 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] = {}
+ self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
+
+ if 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 operations_client(self) -> operations_v1.OperationsAsyncClient:
+ """Create the client designed to process long-running operations.
+
+ This property caches on the instance; repeated calls return the same
+ client.
+ """
+ # Quick check: Only create a new client if we do not already have one.
+ if self._operations_client is None:
+ self._operations_client = operations_v1.OperationsAsyncClient(
+ self._logged_channel
+ )
+
+ # Return the client from cache.
+ return self._operations_client
+
+ @property
+ def delete_collection(
+ self,
+ ) -> Callable[
+ [collection_service.DeleteCollectionRequest],
+ Awaitable[operations_pb2.Operation],
+ ]:
+ r"""Return a callable for the delete collection method over gRPC.
+
+ Deletes a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Returns:
+ Callable[[~.DeleteCollectionRequest],
+ 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_collection" not in self._stubs:
+ self._stubs["delete_collection"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.CollectionService/DeleteCollection",
+ request_serializer=collection_service.DeleteCollectionRequest.serialize,
+ response_deserializer=operations_pb2.Operation.FromString,
+ )
+ return self._stubs["delete_collection"]
+
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
+ r"""Return a callable for the get iam policy method over gRPC.
+
+ Gets the IAM access control policy for a
+ [Collection][google.cloud.discoveryengine.v1.Collection]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ Returns:
+ Callable[[~.GetIamPolicyRequest],
+ Awaitable[~.Policy]]:
+ 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_iam_policy" not in self._stubs:
+ self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.CollectionService/GetIamPolicy",
+ request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["get_iam_policy"]
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
+ r"""Return a callable for the set iam policy method over gRPC.
+
+ Sets the IAM access control policy for a
+ [Collection][google.cloud.discoveryengine.v1.Collection]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on a Collection
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``
+ ``roles/discoveryengine.agentspaceAdmin``
+ ``roles/discoveryengine.viewer``
+ ``roles/discoveryengine.agentspaceViewer``
+ ``roles/discoveryengine.user``
+ ``roles/discoveryengine.agentspaceUser`` Attempting to grant any
+ other role will result in a warning in logging.
+
+ Returns:
+ Callable[[~.SetIamPolicyRequest],
+ Awaitable[~.Policy]]:
+ 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 "set_iam_policy" not in self._stubs:
+ self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.CollectionService/SetIamPolicy",
+ request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["set_iam_policy"]
+
+ def _prep_wrapped_messages(self, client_info):
+ """Precompute the wrapped methods, overriding the base class method to use async wrappers."""
+ self._wrapped_methods = {
+ self.delete_collection: self._wrap_method(
+ self.delete_collection,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.get_iam_policy: self._wrap_method(
+ self.get_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.set_iam_policy: self._wrap_method(
+ self.set_iam_policy,
+ 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__ = ("CollectionServiceGrpcAsyncIOTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/rest.py
new file mode 100644
index 000000000000..532ea50ad67f
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/rest.py
@@ -0,0 +1,1621 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
+import google.protobuf
+from google.api_core import exceptions as core_exceptions
+from google.api_core import gapic_v1, operations_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 collection_service
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .rest_base import _BaseCollectionServiceRestTransport
+
+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 CollectionServiceRestInterceptor:
+ """Interceptor for CollectionService.
+
+ 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 CollectionServiceRestTransport.
+
+ .. code-block:: python
+ class MyCustomCollectionServiceInterceptor(CollectionServiceRestInterceptor):
+ def pre_delete_collection(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_delete_collection(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_get_iam_policy(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_get_iam_policy(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_set_iam_policy(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_set_iam_policy(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ transport = CollectionServiceRestTransport(interceptor=MyCustomCollectionServiceInterceptor())
+ client = CollectionServiceClient(transport=transport)
+
+
+ """
+
+ def pre_delete_collection(
+ self,
+ request: collection_service.DeleteCollectionRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ collection_service.DeleteCollectionRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for delete_collection
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the CollectionService server.
+ """
+ return request, metadata
+
+ def post_delete_collection(
+ self, response: operations_pb2.Operation
+ ) -> operations_pb2.Operation:
+ """Post-rpc interceptor for delete_collection
+
+ DEPRECATED. Please use the `post_delete_collection_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the CollectionService server but before
+ it is returned to user code. This `post_delete_collection` interceptor runs
+ before the `post_delete_collection_with_metadata` interceptor.
+ """
+ return response
+
+ def post_delete_collection_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_collection
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the CollectionService server but before it is returned to user code.
+
+ We recommend only using this `post_delete_collection_with_metadata`
+ interceptor in new development instead of the `post_delete_collection` interceptor.
+ When both interceptors are used, this `post_delete_collection_with_metadata` interceptor runs after the
+ `post_delete_collection` interceptor. The (possibly modified) response returned by
+ `post_delete_collection` will be passed to
+ `post_delete_collection_with_metadata`.
+ """
+ return response, metadata
+
+ 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 CollectionService server.
+ """
+ return request, metadata
+
+ def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
+ """Post-rpc interceptor for get_iam_policy
+
+ DEPRECATED. Please use the `post_get_iam_policy_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the CollectionService server but before
+ it is returned to user code. This `post_get_iam_policy` interceptor runs
+ before the `post_get_iam_policy_with_metadata` interceptor.
+ """
+ return response
+
+ def post_get_iam_policy_with_metadata(
+ self,
+ response: policy_pb2.Policy,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for get_iam_policy
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the CollectionService server but before it is returned to user code.
+
+ We recommend only using this `post_get_iam_policy_with_metadata`
+ interceptor in new development instead of the `post_get_iam_policy` interceptor.
+ When both interceptors are used, this `post_get_iam_policy_with_metadata` interceptor runs after the
+ `post_get_iam_policy` interceptor. The (possibly modified) response returned by
+ `post_get_iam_policy` will be passed to
+ `post_get_iam_policy_with_metadata`.
+ """
+ return response, metadata
+
+ 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 CollectionService server.
+ """
+ return request, metadata
+
+ def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
+ """Post-rpc interceptor for set_iam_policy
+
+ DEPRECATED. Please use the `post_set_iam_policy_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the CollectionService server but before
+ it is returned to user code. This `post_set_iam_policy` interceptor runs
+ before the `post_set_iam_policy_with_metadata` interceptor.
+ """
+ return response
+
+ def post_set_iam_policy_with_metadata(
+ self,
+ response: policy_pb2.Policy,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """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 CollectionService server but before it is returned to user code.
+
+ We recommend only using this `post_set_iam_policy_with_metadata`
+ interceptor in new development instead of the `post_set_iam_policy` interceptor.
+ When both interceptors are used, this `post_set_iam_policy_with_metadata` interceptor runs after the
+ `post_set_iam_policy` interceptor. The (possibly modified) response returned by
+ `post_set_iam_policy` will be passed to
+ `post_set_iam_policy_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 CollectionService 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 CollectionService 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 CollectionService 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 CollectionService 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 CollectionService 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 CollectionService server but before
+ it is returned to user code.
+ """
+ return response
+
+
+@dataclasses.dataclass
+class CollectionServiceRestStub:
+ _session: AuthorizedSession
+ _host: str
+ _interceptor: CollectionServiceRestInterceptor
+
+
+class CollectionServiceRestTransport(_BaseCollectionServiceRestTransport):
+ """REST backend synchronous transport for CollectionService.
+
+ Service for managing
+ [Collection][google.cloud.discoveryengine.v1.Collection]s.
+
+ 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[CollectionServiceRestInterceptor] = 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[CollectionServiceRestInterceptor]): 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 CollectionServiceRestInterceptor()
+ 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/*/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": "*",
+ },
+ ],
+ "google.longrunning.Operations.GetOperation": [
+ {
+ "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/*}",
+ },
+ ],
+ "google.longrunning.Operations.ListOperations": [
+ {
+ "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",
+ },
+ ],
+ }
+
+ 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 _DeleteCollection(
+ _BaseCollectionServiceRestTransport._BaseDeleteCollection,
+ CollectionServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("CollectionServiceRestTransport.DeleteCollection")
+
+ @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: collection_service.DeleteCollectionRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> operations_pb2.Operation:
+ r"""Call the delete collection method over HTTP.
+
+ Args:
+ request (~.collection_service.DeleteCollectionRequest):
+ The request object. Request message for
+ [CollectionService.DeleteCollection][google.cloud.discoveryengine.v1.CollectionService.DeleteCollection]
+ 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:
+ This resource represents a
+ long-running operation that is the
+ result of a network API call.
+
+ """
+
+ http_options = _BaseCollectionServiceRestTransport._BaseDeleteCollection._get_http_options()
+ request, metadata = self._interceptor.pre_delete_collection(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseCollectionServiceRestTransport._BaseDeleteCollection,
+ "_BaseDeleteCollection__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.CollectionServiceClient.DeleteCollection",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "rpcName": "DeleteCollection",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = CollectionServiceRestTransport._DeleteCollection._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_collection(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_delete_collection_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.discoveryengine_v1.CollectionServiceClient.delete_collection",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "rpcName": "DeleteCollection",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _GetIamPolicy(
+ _BaseCollectionServiceRestTransport._BaseGetIamPolicy, CollectionServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("CollectionServiceRestTransport.GetIamPolicy")
+
+ @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: iam_policy_pb2.GetIamPolicyRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Call the get iam policy method over HTTP.
+
+ Args:
+ request (~.iam_policy_pb2.GetIamPolicyRequest):
+ The request object. Request message for ``GetIamPolicy`` 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:
+ ~.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which
+ specifies access controls for Google Cloud resources.
+
+ A ``Policy`` is a collection of ``bindings``. A
+ ``binding`` binds one or more ``members``, or
+ principals, to a single ``role``. Principals can be user
+ accounts, service accounts, Google groups, and domains
+ (such as G Suite). A ``role`` is a named list of
+ permissions; each ``role`` can be an IAM predefined role
+ or a user-created custom role.
+
+ For some types of Google Cloud resources, a ``binding``
+ can also specify a ``condition``, which is a logical
+ expression that allows access to a resource only if the
+ expression evaluates to ``true``. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the `IAM
+ documentation `__.
+
+ **JSON example:**
+
+ ::
+
+ {
+ "bindings": [
+ {
+ "role": "roles/resourcemanager.organizationAdmin",
+ "members": [
+ "user:mike@example.com",
+ "group:admins@example.com",
+ "domain:google.com",
+ "serviceAccount:my-project-id@appspot.gserviceaccount.com"
+ ]
+ },
+ {
+ "role": "roles/resourcemanager.organizationViewer",
+ "members": [
+ "user:eve@example.com"
+ ],
+ "condition": {
+ "title": "expirable access",
+ "description": "Does not grant access after Sep 2020",
+ "expression": "request.time <
+ timestamp('2020-10-01T00:00:00.000Z')",
+ }
+ }
+ ],
+ "etag": "BwWWja0YfJA=",
+ "version": 3
+ }
+
+ **YAML example:**
+
+ ::
+
+ bindings:
+ - members:
+ - user:mike@example.com
+ - group:admins@example.com
+ - domain:google.com
+ - serviceAccount:my-project-id@appspot.gserviceaccount.com
+ role: roles/resourcemanager.organizationAdmin
+ - members:
+ - user:eve@example.com
+ role: roles/resourcemanager.organizationViewer
+ condition:
+ title: expirable access
+ description: Does not grant access after Sep 2020
+ expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
+ etag: BwWWja0YfJA=
+ version: 3
+
+ For a description of IAM and its features, see the `IAM
+ documentation `__.
+
+ """
+
+ http_options = _BaseCollectionServiceRestTransport._BaseGetIamPolicy._get_http_options()
+ request, metadata = self._interceptor.pre_get_iam_policy(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseCollectionServiceRestTransport._BaseGetIamPolicy,
+ "_BaseGetIamPolicy__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 = 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.CollectionServiceClient.GetIamPolicy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "rpcName": "GetIamPolicy",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = CollectionServiceRestTransport._GetIamPolicy._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 = policy_pb2.Policy()
+ pb_resp = resp
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_get_iam_policy(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_get_iam_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.discoveryengine_v1.CollectionServiceClient.get_iam_policy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "rpcName": "GetIamPolicy",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _SetIamPolicy(
+ _BaseCollectionServiceRestTransport._BaseSetIamPolicy, CollectionServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("CollectionServiceRestTransport.SetIamPolicy")
+
+ @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: iam_policy_pb2.SetIamPolicyRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Call the set iam policy method over HTTP.
+
+ Args:
+ request (~.iam_policy_pb2.SetIamPolicyRequest):
+ The request object. Request message for ``SetIamPolicy`` 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:
+ ~.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which
+ specifies access controls for Google Cloud resources.
+
+ A ``Policy`` is a collection of ``bindings``. A
+ ``binding`` binds one or more ``members``, or
+ principals, to a single ``role``. Principals can be user
+ accounts, service accounts, Google groups, and domains
+ (such as G Suite). A ``role`` is a named list of
+ permissions; each ``role`` can be an IAM predefined role
+ or a user-created custom role.
+
+ For some types of Google Cloud resources, a ``binding``
+ can also specify a ``condition``, which is a logical
+ expression that allows access to a resource only if the
+ expression evaluates to ``true``. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the `IAM
+ documentation `__.
+
+ **JSON example:**
+
+ ::
+
+ {
+ "bindings": [
+ {
+ "role": "roles/resourcemanager.organizationAdmin",
+ "members": [
+ "user:mike@example.com",
+ "group:admins@example.com",
+ "domain:google.com",
+ "serviceAccount:my-project-id@appspot.gserviceaccount.com"
+ ]
+ },
+ {
+ "role": "roles/resourcemanager.organizationViewer",
+ "members": [
+ "user:eve@example.com"
+ ],
+ "condition": {
+ "title": "expirable access",
+ "description": "Does not grant access after Sep 2020",
+ "expression": "request.time <
+ timestamp('2020-10-01T00:00:00.000Z')",
+ }
+ }
+ ],
+ "etag": "BwWWja0YfJA=",
+ "version": 3
+ }
+
+ **YAML example:**
+
+ ::
+
+ bindings:
+ - members:
+ - user:mike@example.com
+ - group:admins@example.com
+ - domain:google.com
+ - serviceAccount:my-project-id@appspot.gserviceaccount.com
+ role: roles/resourcemanager.organizationAdmin
+ - members:
+ - user:eve@example.com
+ role: roles/resourcemanager.organizationViewer
+ condition:
+ title: expirable access
+ description: Does not grant access after Sep 2020
+ expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
+ etag: BwWWja0YfJA=
+ version: 3
+
+ For a description of IAM and its features, see the `IAM
+ documentation `__.
+
+ """
+
+ http_options = _BaseCollectionServiceRestTransport._BaseSetIamPolicy._get_http_options()
+ request, metadata = self._interceptor.pre_set_iam_policy(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseCollectionServiceRestTransport._BaseSetIamPolicy,
+ "_BaseSetIamPolicy__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 = 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.CollectionServiceClient.SetIamPolicy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "rpcName": "SetIamPolicy",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = CollectionServiceRestTransport._SetIamPolicy._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 = policy_pb2.Policy()
+ pb_resp = resp
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_set_iam_policy(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_set_iam_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.discoveryengine_v1.CollectionServiceClient.set_iam_policy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "rpcName": "SetIamPolicy",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ @property
+ def delete_collection(
+ self,
+ ) -> Callable[
+ [collection_service.DeleteCollectionRequest], 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._DeleteCollection(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
+ # 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._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
+ # 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._SetIamPolicy(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(
+ _BaseCollectionServiceRestTransport._BaseCancelOperation,
+ CollectionServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("CollectionServiceRestTransport.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 = _BaseCollectionServiceRestTransport._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(
+ _BaseCollectionServiceRestTransport._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.CollectionServiceClient.CancelOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "rpcName": "CancelOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = CollectionServiceRestTransport._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(
+ _BaseCollectionServiceRestTransport._BaseGetOperation, CollectionServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("CollectionServiceRestTransport.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 = _BaseCollectionServiceRestTransport._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(
+ _BaseCollectionServiceRestTransport._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.CollectionServiceClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "rpcName": "GetOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = CollectionServiceRestTransport._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.CollectionServiceAsyncClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "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(
+ _BaseCollectionServiceRestTransport._BaseListOperations,
+ CollectionServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("CollectionServiceRestTransport.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 = _BaseCollectionServiceRestTransport._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(
+ _BaseCollectionServiceRestTransport._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.CollectionServiceClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "rpcName": "ListOperations",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = CollectionServiceRestTransport._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.CollectionServiceAsyncClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CollectionService",
+ "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__ = ("CollectionServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/rest_base.py
new file mode 100644
index 000000000000..7dff51c32fcc
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/collection_service/transports/rest_base.py
@@ -0,0 +1,326 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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
+
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
+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 collection_service
+
+from .base import DEFAULT_CLIENT_INFO, CollectionServiceTransport
+
+
+class _BaseCollectionServiceRestTransport(CollectionServiceTransport):
+ """Base REST backend transport for CollectionService.
+
+ 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 _BaseDeleteCollection:
+ 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/*/collections/*}",
+ },
+ ]
+ return http_options
+
+ class _BaseGetIamPolicy:
+ 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/{resource=projects/*/locations/*/collections/*}:getIamPolicy",
+ },
+ ]
+ return http_options
+
+ class _BaseSetIamPolicy:
+ 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/{resource=projects/*/locations/*/collections/*}:setIamPolicy",
+ "body": "*",
+ },
+ ]
+ 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__ = ("_BaseCollectionServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/async_client.py
index 03e3cc96a4db..3ae4422e372f 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/async_client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/async_client.py
@@ -81,8 +81,16 @@ class CompletionServiceAsyncClient:
_DEFAULT_ENDPOINT_TEMPLATE = CompletionServiceClient._DEFAULT_ENDPOINT_TEMPLATE
_DEFAULT_UNIVERSE = CompletionServiceClient._DEFAULT_UNIVERSE
+ completion_config_path = staticmethod(
+ CompletionServiceClient.completion_config_path
+ )
+ parse_completion_config_path = staticmethod(
+ CompletionServiceClient.parse_completion_config_path
+ )
data_store_path = staticmethod(CompletionServiceClient.data_store_path)
parse_data_store_path = staticmethod(CompletionServiceClient.parse_data_store_path)
+ document_path = staticmethod(CompletionServiceClient.document_path)
+ parse_document_path = staticmethod(CompletionServiceClient.parse_document_path)
common_billing_account_path = staticmethod(
CompletionServiceClient.common_billing_account_path
)
@@ -397,6 +405,100 @@ async def sample_complete_query():
# Done; return the response.
return response
+ async def advanced_complete_query(
+ self,
+ request: Optional[
+ Union[completion_service.AdvancedCompleteQueryRequest, dict]
+ ] = None,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> completion_service.AdvancedCompleteQueryResponse:
+ r"""Completes the user input with advanced keyword
+ suggestions.
+
+ .. 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_advanced_complete_query():
+ # Create a client
+ client = discoveryengine_v1.CompletionServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.AdvancedCompleteQueryRequest(
+ completion_config="completion_config_value",
+ query="query_value",
+ )
+
+ # Make the request
+ response = await client.advanced_complete_query(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryRequest, dict]]):
+ The request object. Request message for
+ [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery]
+ 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.AdvancedCompleteQueryResponse:
+ Response message for
+ [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery]
+ method.
+
+ """
+ # 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, completion_service.AdvancedCompleteQueryRequest):
+ request = completion_service.AdvancedCompleteQueryRequest(request)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.advanced_complete_query
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("completion_config", request.completion_config),)
+ ),
+ )
+
+ # 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 import_suggestion_deny_list_entries(
self,
request: Optional[
@@ -793,7 +895,9 @@ async def sample_purge_completion_suggestions():
The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.PurgeCompletionSuggestionsResponse` Response message for
[CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1.CompletionService.PurgeCompletionSuggestions]
- method.
+ method. If the long running operation is successfully
+ done, then this message is returned by the
+ google.longrunning.Operations.response field.
"""
# Create or coerce a protobuf request object.
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/client.py
index 6d527a6f0878..7961a4722763 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/client.py
@@ -177,6 +177,28 @@ def transport(self) -> CompletionServiceTransport:
"""
return self._transport
+ @staticmethod
+ def completion_config_path(
+ project: str,
+ location: str,
+ data_store: str,
+ ) -> str:
+ """Returns a fully-qualified completion_config string."""
+ return "projects/{project}/locations/{location}/dataStores/{data_store}/completionConfig".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ )
+
+ @staticmethod
+ def parse_completion_config_path(path: str) -> Dict[str, str]:
+ """Parses a completion_config path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/completionConfig$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
@staticmethod
def data_store_path(
project: str,
@@ -199,6 +221,32 @@ def parse_data_store_path(path: str) -> Dict[str, str]:
)
return m.groupdict() if m else {}
+ @staticmethod
+ def document_path(
+ project: str,
+ location: str,
+ data_store: str,
+ branch: str,
+ document: str,
+ ) -> str:
+ """Returns a fully-qualified document string."""
+ return "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ branch=branch,
+ document=document,
+ )
+
+ @staticmethod
+ def parse_document_path(path: str) -> Dict[str, str]:
+ """Parses a document path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/branches/(?P.+?)/documents/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
@staticmethod
def common_billing_account_path(
billing_account: str,
@@ -693,6 +741,98 @@ def sample_complete_query():
# Done; return the response.
return response
+ def advanced_complete_query(
+ self,
+ request: Optional[
+ Union[completion_service.AdvancedCompleteQueryRequest, dict]
+ ] = None,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> completion_service.AdvancedCompleteQueryResponse:
+ r"""Completes the user input with advanced keyword
+ suggestions.
+
+ .. 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_advanced_complete_query():
+ # Create a client
+ client = discoveryengine_v1.CompletionServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.AdvancedCompleteQueryRequest(
+ completion_config="completion_config_value",
+ query="query_value",
+ )
+
+ # Make the request
+ response = client.advanced_complete_query(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryRequest, dict]):
+ The request object. Request message for
+ [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery]
+ 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.AdvancedCompleteQueryResponse:
+ Response message for
+ [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery]
+ method.
+
+ """
+ # 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, completion_service.AdvancedCompleteQueryRequest):
+ request = completion_service.AdvancedCompleteQueryRequest(request)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.advanced_complete_query]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("completion_config", request.completion_config),)
+ ),
+ )
+
+ # 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 import_suggestion_deny_list_entries(
self,
request: Optional[
@@ -1089,7 +1229,9 @@ def sample_purge_completion_suggestions():
The result type for the operation will be :class:`google.cloud.discoveryengine_v1.types.PurgeCompletionSuggestionsResponse` Response message for
[CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1.CompletionService.PurgeCompletionSuggestions]
- method.
+ method. If the long running operation is successfully
+ done, then this message is returned by the
+ google.longrunning.Operations.response field.
"""
# Create or coerce a protobuf request object.
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py
index fb2b45248f27..e21a065b8ad5 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/base.py
@@ -43,7 +43,13 @@
class CompletionServiceTransport(abc.ABC):
"""Abstract transport class for CompletionService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ AUTH_SCOPES = (
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud_search.query",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ )
DEFAULT_HOST: str = "discoveryengine.googleapis.com"
@@ -151,6 +157,11 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
+ self.advanced_complete_query: gapic_v1.method.wrap_method(
+ self.advanced_complete_query,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.import_suggestion_deny_list_entries: gapic_v1.method.wrap_method(
self.import_suggestion_deny_list_entries,
default_timeout=None,
@@ -214,6 +225,18 @@ def complete_query(
]:
raise NotImplementedError()
+ @property
+ def advanced_complete_query(
+ self,
+ ) -> Callable[
+ [completion_service.AdvancedCompleteQueryRequest],
+ Union[
+ completion_service.AdvancedCompleteQueryResponse,
+ Awaitable[completion_service.AdvancedCompleteQueryResponse],
+ ],
+ ]:
+ raise NotImplementedError()
+
@property
def import_suggestion_deny_list_entries(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py
index 05923f374abc..45cfbf0f7f96 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc.py
@@ -378,6 +378,36 @@ def complete_query(
)
return self._stubs["complete_query"]
+ @property
+ def advanced_complete_query(
+ self,
+ ) -> Callable[
+ [completion_service.AdvancedCompleteQueryRequest],
+ completion_service.AdvancedCompleteQueryResponse,
+ ]:
+ r"""Return a callable for the advanced complete query method over gRPC.
+
+ Completes the user input with advanced keyword
+ suggestions.
+
+ Returns:
+ Callable[[~.AdvancedCompleteQueryRequest],
+ ~.AdvancedCompleteQueryResponse]:
+ 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 "advanced_complete_query" not in self._stubs:
+ self._stubs["advanced_complete_query"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.CompletionService/AdvancedCompleteQuery",
+ request_serializer=completion_service.AdvancedCompleteQueryRequest.serialize,
+ response_deserializer=completion_service.AdvancedCompleteQueryResponse.deserialize,
+ )
+ return self._stubs["advanced_complete_query"]
+
@property
def import_suggestion_deny_list_entries(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py
index ec24602f80d4..9e4abe9436c0 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/grpc_asyncio.py
@@ -386,6 +386,36 @@ def complete_query(
)
return self._stubs["complete_query"]
+ @property
+ def advanced_complete_query(
+ self,
+ ) -> Callable[
+ [completion_service.AdvancedCompleteQueryRequest],
+ Awaitable[completion_service.AdvancedCompleteQueryResponse],
+ ]:
+ r"""Return a callable for the advanced complete query method over gRPC.
+
+ Completes the user input with advanced keyword
+ suggestions.
+
+ Returns:
+ Callable[[~.AdvancedCompleteQueryRequest],
+ Awaitable[~.AdvancedCompleteQueryResponse]]:
+ 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 "advanced_complete_query" not in self._stubs:
+ self._stubs["advanced_complete_query"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.CompletionService/AdvancedCompleteQuery",
+ request_serializer=completion_service.AdvancedCompleteQueryRequest.serialize,
+ response_deserializer=completion_service.AdvancedCompleteQueryResponse.deserialize,
+ )
+ return self._stubs["advanced_complete_query"]
+
@property
def import_suggestion_deny_list_entries(
self,
@@ -528,6 +558,11 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
+ self.advanced_complete_query: self._wrap_method(
+ self.advanced_complete_query,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.import_suggestion_deny_list_entries: self._wrap_method(
self.import_suggestion_deny_list_entries,
default_timeout=None,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py
index 4da1a241a954..513c5442d222 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest.py
@@ -78,6 +78,14 @@ class CompletionServiceRestInterceptor:
.. code-block:: python
class MyCustomCompletionServiceInterceptor(CompletionServiceRestInterceptor):
+ def pre_advanced_complete_query(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_advanced_complete_query(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
def pre_complete_query(self, request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
@@ -124,6 +132,58 @@ def post_purge_suggestion_deny_list_entries(self, response):
"""
+ def pre_advanced_complete_query(
+ self,
+ request: completion_service.AdvancedCompleteQueryRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ completion_service.AdvancedCompleteQueryRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for advanced_complete_query
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the CompletionService server.
+ """
+ return request, metadata
+
+ def post_advanced_complete_query(
+ self, response: completion_service.AdvancedCompleteQueryResponse
+ ) -> completion_service.AdvancedCompleteQueryResponse:
+ """Post-rpc interceptor for advanced_complete_query
+
+ DEPRECATED. Please use the `post_advanced_complete_query_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the CompletionService server but before
+ it is returned to user code. This `post_advanced_complete_query` interceptor runs
+ before the `post_advanced_complete_query_with_metadata` interceptor.
+ """
+ return response
+
+ def post_advanced_complete_query_with_metadata(
+ self,
+ response: completion_service.AdvancedCompleteQueryResponse,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ completion_service.AdvancedCompleteQueryResponse,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Post-rpc interceptor for advanced_complete_query
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the CompletionService server but before it is returned to user code.
+
+ We recommend only using this `post_advanced_complete_query_with_metadata`
+ interceptor in new development instead of the `post_advanced_complete_query` interceptor.
+ When both interceptors are used, this `post_advanced_complete_query_with_metadata` interceptor runs after the
+ `post_advanced_complete_query` interceptor. The (possibly modified) response returned by
+ `post_advanced_complete_query` will be passed to
+ `post_advanced_complete_query_with_metadata`.
+ """
+ return response, metadata
+
def pre_complete_query(
self,
request: completion_service.CompleteQueryRequest,
@@ -604,6 +664,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
@@ -721,6 +785,165 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
# Return the client from cache.
return self._operations_client
+ class _AdvancedCompleteQuery(
+ _BaseCompletionServiceRestTransport._BaseAdvancedCompleteQuery,
+ CompletionServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("CompletionServiceRestTransport.AdvancedCompleteQuery")
+
+ @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: completion_service.AdvancedCompleteQueryRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> completion_service.AdvancedCompleteQueryResponse:
+ r"""Call the advanced complete query method over HTTP.
+
+ Args:
+ request (~.completion_service.AdvancedCompleteQueryRequest):
+ The request object. Request message for
+ [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery]
+ 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:
+ ~.completion_service.AdvancedCompleteQueryResponse:
+ Response message for
+ [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery]
+ method.
+
+ """
+
+ http_options = _BaseCompletionServiceRestTransport._BaseAdvancedCompleteQuery._get_http_options()
+ request, metadata = self._interceptor.pre_advanced_complete_query(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseCompletionServiceRestTransport._BaseAdvancedCompleteQuery,
+ "_BaseAdvancedCompleteQuery__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.CompletionServiceClient.AdvancedCompleteQuery",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CompletionService",
+ "rpcName": "AdvancedCompleteQuery",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ CompletionServiceRestTransport._AdvancedCompleteQuery._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 = completion_service.AdvancedCompleteQueryResponse()
+ pb_resp = completion_service.AdvancedCompleteQueryResponse.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_advanced_complete_query(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_advanced_complete_query_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = (
+ completion_service.AdvancedCompleteQueryResponse.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.CompletionServiceClient.advanced_complete_query",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.CompletionService",
+ "rpcName": "AdvancedCompleteQuery",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
class _CompleteQuery(
_BaseCompletionServiceRestTransport._BaseCompleteQuery,
CompletionServiceRestStub,
@@ -1492,6 +1715,17 @@ def __call__(
)
return resp
+ @property
+ def advanced_complete_query(
+ self,
+ ) -> Callable[
+ [completion_service.AdvancedCompleteQueryRequest],
+ completion_service.AdvancedCompleteQueryResponse,
+ ]:
+ # 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._AdvancedCompleteQuery(self._session, self._host, self._interceptor) # type: ignore
+
@property
def complete_query(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest_base.py
index 9940ded2ba18..65030bc4026d 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/completion_service/transports/rest_base.py
@@ -93,6 +93,33 @@ def __init__(
api_audience=api_audience,
)
+ class _BaseAdvancedCompleteQuery:
+ 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/{completion_config=projects/*/locations/*/dataStores/*/completionConfig}:completeQuery",
+ "body": "*",
+ },
+ {
+ "method": "post",
+ "uri": "/v1/{completion_config=projects/*/locations/*/collections/*/dataStores/*/completionConfig}:completeQuery",
+ "body": "*",
+ },
+ {
+ "method": "post",
+ "uri": "/v1/{completion_config=projects/*/locations/*/collections/*/engines/*/completionConfig}:completeQuery",
+ "body": "*",
+ },
+ ]
+ return http_options
+
class _BaseCompleteQuery:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@@ -272,6 +299,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/async_client.py
index 0b89f84a1680..f3ef815fb66d 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/async_client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/async_client.py
@@ -345,7 +345,7 @@ async def sample_create_control():
control.boost_action.filter = "filter_value"
control.boost_action.data_store = "data_store_value"
control.display_name = "display_name_value"
- control.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ control.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.CreateControlRequest(
parent="parent_value",
@@ -598,7 +598,7 @@ async def sample_update_control():
control.boost_action.filter = "filter_value"
control.boost_action.data_store = "data_store_value"
control.display_name = "display_name_value"
- control.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ control.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateControlRequest(
control=control,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/client.py
index 2f0fd2bcb807..61377b3afa5b 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/client.py
@@ -688,7 +688,7 @@ def sample_create_control():
control.boost_action.filter = "filter_value"
control.boost_action.data_store = "data_store_value"
control.display_name = "display_name_value"
- control.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ control.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.CreateControlRequest(
parent="parent_value",
@@ -935,7 +935,7 @@ def sample_update_control():
control.boost_action.filter = "filter_value"
control.boost_action.data_store = "data_store_value"
control.display_name = "display_name_value"
- control.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ control.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateControlRequest(
control=control,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/base.py
index 0a23753fa09f..ca9ee14f7f38 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/base.py
@@ -41,7 +41,11 @@
class ControlServiceTransport(abc.ABC):
"""Abstract transport class for ControlService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/rest_base.py
index 6f6a71e8d175..6984bc10f289 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/control_service/transports/rest_base.py
@@ -288,6 +288,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py
index 989c2f6b014e..3e4ee932e753 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/base.py
@@ -47,7 +47,11 @@
class ConversationalSearchServiceTransport(abc.ABC):
"""Abstract transport class for ConversationalSearchService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest_base.py
index a3acd0490ed4..aae60ac781e7 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/conversational_search_service/transports/rest_base.py
@@ -525,6 +525,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/__init__.py
new file mode 100644
index 000000000000..6c7cd1ffaa1c
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_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 DataConnectorServiceAsyncClient
+from .client import DataConnectorServiceClient
+
+__all__ = (
+ "DataConnectorServiceClient",
+ "DataConnectorServiceAsyncClient",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/async_client.py
new file mode 100644
index 000000000000..6b09d2ded449
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/async_client.py
@@ -0,0 +1,1046 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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
+
+import google.api_core.operation as operation # type: ignore
+import google.api_core.operation_async as operation_async # type: ignore
+import google.protobuf.duration_pb2 as duration_pb2 # type: ignore
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.protobuf.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 google.type.datetime_pb2 as datetime_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 (
+ common,
+ data_connector,
+ data_connector_service,
+)
+from google.cloud.discoveryengine_v1.types import data_connector as gcd_data_connector
+
+from .client import DataConnectorServiceClient
+from .transports.base import DEFAULT_CLIENT_INFO, DataConnectorServiceTransport
+from .transports.grpc_asyncio import DataConnectorServiceGrpcAsyncIOTransport
+
+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 DataConnectorServiceAsyncClient:
+ """Service for data connector management."""
+
+ _client: DataConnectorServiceClient
+
+ # Copy defaults from the synchronous client for use here.
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
+ DEFAULT_ENDPOINT = DataConnectorServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = DataConnectorServiceClient.DEFAULT_MTLS_ENDPOINT
+ _DEFAULT_ENDPOINT_TEMPLATE = DataConnectorServiceClient._DEFAULT_ENDPOINT_TEMPLATE
+ _DEFAULT_UNIVERSE = DataConnectorServiceClient._DEFAULT_UNIVERSE
+
+ content_policy_path = staticmethod(DataConnectorServiceClient.content_policy_path)
+ parse_content_policy_path = staticmethod(
+ DataConnectorServiceClient.parse_content_policy_path
+ )
+ data_connector_path = staticmethod(DataConnectorServiceClient.data_connector_path)
+ parse_data_connector_path = staticmethod(
+ DataConnectorServiceClient.parse_data_connector_path
+ )
+ data_store_path = staticmethod(DataConnectorServiceClient.data_store_path)
+ parse_data_store_path = staticmethod(
+ DataConnectorServiceClient.parse_data_store_path
+ )
+ location_path = staticmethod(DataConnectorServiceClient.location_path)
+ parse_location_path = staticmethod(DataConnectorServiceClient.parse_location_path)
+ schema_path = staticmethod(DataConnectorServiceClient.schema_path)
+ parse_schema_path = staticmethod(DataConnectorServiceClient.parse_schema_path)
+ service_path = staticmethod(DataConnectorServiceClient.service_path)
+ parse_service_path = staticmethod(DataConnectorServiceClient.parse_service_path)
+ common_billing_account_path = staticmethod(
+ DataConnectorServiceClient.common_billing_account_path
+ )
+ parse_common_billing_account_path = staticmethod(
+ DataConnectorServiceClient.parse_common_billing_account_path
+ )
+ common_folder_path = staticmethod(DataConnectorServiceClient.common_folder_path)
+ parse_common_folder_path = staticmethod(
+ DataConnectorServiceClient.parse_common_folder_path
+ )
+ common_organization_path = staticmethod(
+ DataConnectorServiceClient.common_organization_path
+ )
+ parse_common_organization_path = staticmethod(
+ DataConnectorServiceClient.parse_common_organization_path
+ )
+ common_project_path = staticmethod(DataConnectorServiceClient.common_project_path)
+ parse_common_project_path = staticmethod(
+ DataConnectorServiceClient.parse_common_project_path
+ )
+ common_location_path = staticmethod(DataConnectorServiceClient.common_location_path)
+ parse_common_location_path = staticmethod(
+ DataConnectorServiceClient.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:
+ DataConnectorServiceAsyncClient: The constructed client.
+ """
+ sa_info_func = (
+ DataConnectorServiceClient.from_service_account_info.__func__ # type: ignore
+ )
+ return sa_info_func(DataConnectorServiceAsyncClient, 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:
+ DataConnectorServiceAsyncClient: The constructed client.
+ """
+ sa_file_func = (
+ DataConnectorServiceClient.from_service_account_file.__func__ # type: ignore
+ )
+ return sa_file_func(DataConnectorServiceAsyncClient, 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 DataConnectorServiceClient.get_mtls_endpoint_and_cert_source(
+ client_options
+ ) # type: ignore
+
+ @property
+ def transport(self) -> DataConnectorServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ DataConnectorServiceTransport: 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 = DataConnectorServiceClient.get_transport_class
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[ga_credentials.Credentials] = None,
+ transport: Optional[
+ Union[
+ str,
+ DataConnectorServiceTransport,
+ Callable[..., DataConnectorServiceTransport],
+ ]
+ ] = "grpc_asyncio",
+ client_options: Optional[ClientOptions] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the data connector 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,DataConnectorServiceTransport,Callable[..., DataConnectorServiceTransport]]]):
+ 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 DataConnectorServiceTransport 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 = DataConnectorServiceClient(
+ 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.DataConnectorServiceAsyncClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "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.DataConnectorService",
+ "credentialsType": None,
+ },
+ )
+
+ async def set_up_data_connector(
+ self,
+ request: Optional[
+ Union[data_connector_service.SetUpDataConnectorRequest, dict]
+ ] = None,
+ *,
+ parent: Optional[str] = None,
+ collection_id: Optional[str] = None,
+ collection_display_name: Optional[str] = None,
+ data_connector: Optional[gcd_data_connector.DataConnector] = 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
+ [Collection][google.cloud.discoveryengine.v1.Collection] and
+ sets up the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ for it. To stop a
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ after setup, use the
+ [CollectionService.DeleteCollection][google.cloud.discoveryengine.v1.CollectionService.DeleteCollection]
+ method.
+
+ .. 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_set_up_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceAsyncClient()
+
+ # Initialize request argument(s)
+ data_connector = discoveryengine_v1.DataConnector()
+ data_connector.data_source = "data_source_value"
+
+ request = discoveryengine_v1.SetUpDataConnectorRequest(
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=data_connector,
+ )
+
+ # Make the request
+ operation = await client.set_up_data_connector(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = await operation.result()
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.SetUpDataConnectorRequest, dict]]):
+ The request object. Request for
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method.
+ parent (:class:`str`):
+ Required. The parent of
+ [Collection][google.cloud.discoveryengine.v1.Collection],
+ in the format of
+ ``projects/{project}/locations/{location}``.
+
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ collection_id (:class:`str`):
+ Required. The ID to use for the
+ [Collection][google.cloud.discoveryengine.v1.Collection],
+ which will become the final component of the
+ [Collection][google.cloud.discoveryengine.v1.Collection]'s
+ resource name. A new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ is created as part of the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ setup.
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ is a singleton resource under
+ [Collection][google.cloud.discoveryengine.v1.Collection],
+ managing all
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]s
+ of the
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Should conform to
+ `RFC-1034 `__
+ standard with a length limit of 63 characters.
+ Otherwise, an ``INVALID_ARGUMENT`` error is returned.
+
+ This corresponds to the ``collection_id`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ collection_display_name (:class:`str`):
+ Required. The display name of the
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Should be human readable, used to display collections in
+ the Console Dashboard. UTF-8 encoded string with limit
+ of 1024 characters.
+
+ This corresponds to the ``collection_display_name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ data_connector (:class:`google.cloud.discoveryengine_v1.types.DataConnector`):
+ Required. The
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ to initialize in the newly created
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ This corresponds to the ``data_connector`` 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.discoveryengine_v1.types.DataConnector` Manages the connection to external data sources for all data stores grouped
+ under a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ It's a singleton resource of
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ The initialization is only supported through
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, which will create a new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ and initialize its
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ """
+ # 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,
+ collection_id,
+ collection_display_name,
+ data_connector,
+ ]
+ 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, data_connector_service.SetUpDataConnectorRequest):
+ request = data_connector_service.SetUpDataConnectorRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if parent is not None:
+ request.parent = parent
+ if collection_id is not None:
+ request.collection_id = collection_id
+ if collection_display_name is not None:
+ request.collection_display_name = collection_display_name
+ if data_connector is not None:
+ request.data_connector = data_connector
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.set_up_data_connector
+ ]
+
+ # 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,
+ gcd_data_connector.DataConnector,
+ metadata_type=data_connector_service.SetUpDataConnectorMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def get_data_connector(
+ self,
+ request: Optional[
+ Union[data_connector_service.GetDataConnectorRequest, 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]]] = (),
+ ) -> data_connector.DataConnector:
+ r"""Gets the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ is a singleton resource for each
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ .. code-block:: python
+
+ # This snippet has been automatically generated and should be regarded as a
+ # code template only.
+ # It will require modifications to work:
+ # - It may require correct/in-range values for request initialization.
+ # - It may require specifying regional endpoints when creating the service
+ # client as shown in:
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
+ from google.cloud import discoveryengine_v1
+
+ async def sample_get_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetDataConnectorRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_data_connector(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.GetDataConnectorRequest, dict]]):
+ The request object. Request for
+ [DataConnectorService.GetDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.GetDataConnector]
+ method.
+ name (:class:`str`):
+ Required. Full resource name of
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector],
+ such as
+ ``projects/{project}/locations/{location}/collections/{collection_id}/dataConnector``.
+
+ If the caller does not have permission to access the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector],
+ regardless of whether or not it exists, a
+ ``PERMISSION_DENIED`` error is returned.
+
+ If the requested
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ 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`.
+
+ Returns:
+ google.cloud.discoveryengine_v1.types.DataConnector:
+ Manages the connection to external data sources for all data stores grouped
+ under a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ It's a singleton resource of
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ The initialization is only supported through
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, which will create a new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ and initialize its
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ """
+ # 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, data_connector_service.GetDataConnectorRequest):
+ request = data_connector_service.GetDataConnectorRequest(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_data_connector
+ ]
+
+ # 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_data_connector(
+ self,
+ request: Optional[
+ Union[data_connector_service.UpdateDataConnectorRequest, dict]
+ ] = None,
+ *,
+ data_connector: Optional[gcd_data_connector.DataConnector] = 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_data_connector.DataConnector:
+ r"""Updates a
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ .. 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_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceAsyncClient()
+
+ # Initialize request argument(s)
+ data_connector = discoveryengine_v1.DataConnector()
+ data_connector.data_source = "data_source_value"
+
+ request = discoveryengine_v1.UpdateDataConnectorRequest(
+ data_connector=data_connector,
+ )
+
+ # Make the request
+ response = await client.update_data_connector(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateDataConnectorRequest, dict]]):
+ The request object. Request message for
+ [DataConnectorService.UpdateDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.UpdateDataConnector]
+ method.
+ data_connector (:class:`google.cloud.discoveryengine_v1.types.DataConnector`):
+ Required. The
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ to update.
+
+ If the caller does not have permission to update the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector],
+ regardless of whether or not it exists, a
+ ``PERMISSION_DENIED`` error is returned.
+
+ If the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ does not exist, a ``NOT_FOUND`` error is returned.
+
+ This corresponds to the ``data_connector`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
+ Indicates which fields in the provided
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ to update.
+
+ Supported field paths include:
+
+ - ``refresh_interval``
+ - ``params``
+ - ``auto_run_disabled``
+ - ``action_config``
+ - ``action_config.action_params``
+ - ``action_config.service_name``
+ - ``destination_configs``
+ - ``blocking_reasons``
+ - ``sync_mode``
+ - ``incremental_sync_disabled``
+ - ``incremental_refresh_interval``
+ - ``data_protection_policy``
+
+ Note: Support for these fields may vary depending on the
+ connector type. For example, not all connectors support
+ ``destination_configs``.
+
+ If an unsupported or unknown field path is provided, the
+ request will return an ``INVALID_ARGUMENT`` error.
+
+ 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.DataConnector:
+ Manages the connection to external data sources for all data stores grouped
+ under a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ It's a singleton resource of
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ The initialization is only supported through
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, which will create a new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ and initialize its
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ """
+ # 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 = [data_connector, 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, data_connector_service.UpdateDataConnectorRequest):
+ request = data_connector_service.UpdateDataConnectorRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if data_connector is not None:
+ request.data_connector = data_connector
+ 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_data_connector
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("data_connector.name", request.data_connector.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) -> "DataConnectorServiceAsyncClient":
+ 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__ = ("DataConnectorServiceAsyncClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/client.py
new file mode 100644
index 000000000000..e55ac4104072
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/client.py
@@ -0,0 +1,1440 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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__)
+
+import google.api_core.operation as operation # type: ignore
+import google.api_core.operation_async as operation_async # type: ignore
+import google.protobuf.duration_pb2 as duration_pb2 # type: ignore
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.protobuf.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 google.type.datetime_pb2 as datetime_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 (
+ common,
+ data_connector,
+ data_connector_service,
+)
+from google.cloud.discoveryengine_v1.types import data_connector as gcd_data_connector
+
+from .transports.base import DEFAULT_CLIENT_INFO, DataConnectorServiceTransport
+from .transports.grpc import DataConnectorServiceGrpcTransport
+from .transports.grpc_asyncio import DataConnectorServiceGrpcAsyncIOTransport
+from .transports.rest import DataConnectorServiceRestTransport
+
+
+class DataConnectorServiceClientMeta(type):
+ """Metaclass for the DataConnectorService 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[DataConnectorServiceTransport]]
+ _transport_registry["grpc"] = DataConnectorServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = DataConnectorServiceGrpcAsyncIOTransport
+ _transport_registry["rest"] = DataConnectorServiceRestTransport
+
+ def get_transport_class(
+ cls,
+ label: Optional[str] = None,
+ ) -> Type[DataConnectorServiceTransport]:
+ """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 DataConnectorServiceClient(metaclass=DataConnectorServiceClientMeta):
+ """Service for data connector management."""
+
+ # 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:
+ DataConnectorServiceClient: 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:
+ DataConnectorServiceClient: 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) -> DataConnectorServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ DataConnectorServiceTransport: The transport used by the client
+ instance.
+ """
+ return self._transport
+
+ @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_connector_path(
+ project: str,
+ location: str,
+ collection: str,
+ ) -> str:
+ """Returns a fully-qualified data_connector string."""
+ return "projects/{project}/locations/{location}/collections/{collection}/dataConnector".format(
+ project=project,
+ location=location,
+ collection=collection,
+ )
+
+ @staticmethod
+ def parse_data_connector_path(path: str) -> Dict[str, str]:
+ """Parses a data_connector path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/collections/(?P.+?)/dataConnector$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def data_store_path(
+ project: str,
+ location: str,
+ data_store: str,
+ ) -> str:
+ """Returns a fully-qualified data_store string."""
+ return "projects/{project}/locations/{location}/dataStores/{data_store}".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ )
+
+ @staticmethod
+ def parse_data_store_path(path: str) -> Dict[str, str]:
+ """Parses a data_store path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def 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_location_path(path: str) -> Dict[str, str]:
+ """Parses a location path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def schema_path(
+ project: str,
+ location: str,
+ data_store: str,
+ schema: str,
+ ) -> str:
+ """Returns a fully-qualified schema string."""
+ return "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ schema=schema,
+ )
+
+ @staticmethod
+ def parse_schema_path(path: str) -> Dict[str, str]:
+ """Parses a schema path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/schemas/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def service_path(
+ project: str,
+ location: str,
+ namespace: str,
+ service: str,
+ ) -> str:
+ """Returns a fully-qualified service string."""
+ return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(
+ project=project,
+ location=location,
+ namespace=namespace,
+ service=service,
+ )
+
+ @staticmethod
+ def parse_service_path(path: str) -> Dict[str, str]:
+ """Parses a service path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_billing_account_path(
+ billing_account: str,
+ ) -> str:
+ """Returns a fully-qualified billing_account string."""
+ return "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+
+ @staticmethod
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
+ """Parse a billing_account path into its component segments."""
+ m = re.match(r"^billingAccounts/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_folder_path(
+ folder: str,
+ ) -> str:
+ """Returns a fully-qualified folder string."""
+ return "folders/{folder}".format(
+ folder=folder,
+ )
+
+ @staticmethod
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
+ """Parse a folder path into its component segments."""
+ m = re.match(r"^folders/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_organization_path(
+ organization: str,
+ ) -> str:
+ """Returns a fully-qualified organization string."""
+ return "organizations/{organization}".format(
+ organization=organization,
+ )
+
+ @staticmethod
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
+ """Parse a organization path into its component segments."""
+ m = re.match(r"^organizations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_project_path(
+ project: str,
+ ) -> str:
+ """Returns a fully-qualified project string."""
+ return "projects/{project}".format(
+ project=project,
+ )
+
+ @staticmethod
+ def parse_common_project_path(path: str) -> Dict[str, str]:
+ """Parse a project path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_location_path(
+ project: str,
+ location: str,
+ ) -> str:
+ """Returns a fully-qualified location string."""
+ return "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+
+ @staticmethod
+ def parse_common_location_path(path: str) -> Dict[str, str]:
+ """Parse a location path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @classmethod
+ def get_mtls_endpoint_and_cert_source(
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
+ ):
+ """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,
+ DataConnectorServiceTransport,
+ Callable[..., DataConnectorServiceTransport],
+ ]
+ ] = None,
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the data connector 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,DataConnectorServiceTransport,Callable[..., DataConnectorServiceTransport]]]):
+ 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 DataConnectorServiceTransport 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 = DataConnectorServiceClient._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=DataConnectorServiceClient._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, DataConnectorServiceTransport)
+ if transport_provided:
+ # transport is a DataConnectorServiceTransport 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(DataConnectorServiceTransport, 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=DataConnectorServiceClient._DEFAULT_UNIVERSE,
+ default_mtls_endpoint=DataConnectorServiceClient.DEFAULT_MTLS_ENDPOINT,
+ default_endpoint_template=DataConnectorServiceClient._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[DataConnectorServiceTransport],
+ Callable[..., DataConnectorServiceTransport],
+ ] = (
+ DataConnectorServiceClient.get_transport_class(transport)
+ if isinstance(transport, str) or transport is None
+ else cast(Callable[..., DataConnectorServiceTransport], 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.DataConnectorServiceClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "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.DataConnectorService",
+ "credentialsType": None,
+ },
+ )
+
+ def set_up_data_connector(
+ self,
+ request: Optional[
+ Union[data_connector_service.SetUpDataConnectorRequest, dict]
+ ] = None,
+ *,
+ parent: Optional[str] = None,
+ collection_id: Optional[str] = None,
+ collection_display_name: Optional[str] = None,
+ data_connector: Optional[gcd_data_connector.DataConnector] = 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
+ [Collection][google.cloud.discoveryengine.v1.Collection] and
+ sets up the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ for it. To stop a
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ after setup, use the
+ [CollectionService.DeleteCollection][google.cloud.discoveryengine.v1.CollectionService.DeleteCollection]
+ method.
+
+ .. 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_set_up_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceClient()
+
+ # Initialize request argument(s)
+ data_connector = discoveryengine_v1.DataConnector()
+ data_connector.data_source = "data_source_value"
+
+ request = discoveryengine_v1.SetUpDataConnectorRequest(
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=data_connector,
+ )
+
+ # Make the request
+ operation = client.set_up_data_connector(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = operation.result()
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.SetUpDataConnectorRequest, dict]):
+ The request object. Request for
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method.
+ parent (str):
+ Required. The parent of
+ [Collection][google.cloud.discoveryengine.v1.Collection],
+ in the format of
+ ``projects/{project}/locations/{location}``.
+
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ collection_id (str):
+ Required. The ID to use for the
+ [Collection][google.cloud.discoveryengine.v1.Collection],
+ which will become the final component of the
+ [Collection][google.cloud.discoveryengine.v1.Collection]'s
+ resource name. A new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ is created as part of the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ setup.
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ is a singleton resource under
+ [Collection][google.cloud.discoveryengine.v1.Collection],
+ managing all
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]s
+ of the
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Should conform to
+ `RFC-1034 `__
+ standard with a length limit of 63 characters.
+ Otherwise, an ``INVALID_ARGUMENT`` error is returned.
+
+ This corresponds to the ``collection_id`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ collection_display_name (str):
+ Required. The display name of the
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Should be human readable, used to display collections in
+ the Console Dashboard. UTF-8 encoded string with limit
+ of 1024 characters.
+
+ This corresponds to the ``collection_display_name`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ data_connector (google.cloud.discoveryengine_v1.types.DataConnector):
+ Required. The
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ to initialize in the newly created
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ This corresponds to the ``data_connector`` 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.discoveryengine_v1.types.DataConnector` Manages the connection to external data sources for all data stores grouped
+ under a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ It's a singleton resource of
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ The initialization is only supported through
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, which will create a new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ and initialize its
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ """
+ # 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,
+ collection_id,
+ collection_display_name,
+ data_connector,
+ ]
+ 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, data_connector_service.SetUpDataConnectorRequest):
+ request = data_connector_service.SetUpDataConnectorRequest(request)
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if parent is not None:
+ request.parent = parent
+ if collection_id is not None:
+ request.collection_id = collection_id
+ if collection_display_name is not None:
+ request.collection_display_name = collection_display_name
+ if data_connector is not None:
+ request.data_connector = data_connector
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.set_up_data_connector]
+
+ # 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,
+ gcd_data_connector.DataConnector,
+ metadata_type=data_connector_service.SetUpDataConnectorMetadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ def get_data_connector(
+ self,
+ request: Optional[
+ Union[data_connector_service.GetDataConnectorRequest, 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]]] = (),
+ ) -> data_connector.DataConnector:
+ r"""Gets the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ is a singleton resource for each
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ .. code-block:: python
+
+ # This snippet has been automatically generated and should be regarded as a
+ # code template only.
+ # It will require modifications to work:
+ # - It may require correct/in-range values for request initialization.
+ # - It may require specifying regional endpoints when creating the service
+ # client as shown in:
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
+ from google.cloud import discoveryengine_v1
+
+ def sample_get_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetDataConnectorRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_data_connector(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.GetDataConnectorRequest, dict]):
+ The request object. Request for
+ [DataConnectorService.GetDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.GetDataConnector]
+ method.
+ name (str):
+ Required. Full resource name of
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector],
+ such as
+ ``projects/{project}/locations/{location}/collections/{collection_id}/dataConnector``.
+
+ If the caller does not have permission to access the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector],
+ regardless of whether or not it exists, a
+ ``PERMISSION_DENIED`` error is returned.
+
+ If the requested
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ 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.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each 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.DataConnector:
+ Manages the connection to external data sources for all data stores grouped
+ under a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ It's a singleton resource of
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ The initialization is only supported through
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, which will create a new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ and initialize its
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ """
+ # 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, data_connector_service.GetDataConnectorRequest):
+ request = data_connector_service.GetDataConnectorRequest(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_data_connector]
+
+ # 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_data_connector(
+ self,
+ request: Optional[
+ Union[data_connector_service.UpdateDataConnectorRequest, dict]
+ ] = None,
+ *,
+ data_connector: Optional[gcd_data_connector.DataConnector] = 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_data_connector.DataConnector:
+ r"""Updates a
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ .. 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_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceClient()
+
+ # Initialize request argument(s)
+ data_connector = discoveryengine_v1.DataConnector()
+ data_connector.data_source = "data_source_value"
+
+ request = discoveryengine_v1.UpdateDataConnectorRequest(
+ data_connector=data_connector,
+ )
+
+ # Make the request
+ response = client.update_data_connector(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.UpdateDataConnectorRequest, dict]):
+ The request object. Request message for
+ [DataConnectorService.UpdateDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.UpdateDataConnector]
+ method.
+ data_connector (google.cloud.discoveryengine_v1.types.DataConnector):
+ Required. The
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ to update.
+
+ If the caller does not have permission to update the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector],
+ regardless of whether or not it exists, a
+ ``PERMISSION_DENIED`` error is returned.
+
+ If the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ does not exist, a ``NOT_FOUND`` error is returned.
+
+ This corresponds to the ``data_connector`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
+ Indicates which fields in the provided
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ to update.
+
+ Supported field paths include:
+
+ - ``refresh_interval``
+ - ``params``
+ - ``auto_run_disabled``
+ - ``action_config``
+ - ``action_config.action_params``
+ - ``action_config.service_name``
+ - ``destination_configs``
+ - ``blocking_reasons``
+ - ``sync_mode``
+ - ``incremental_sync_disabled``
+ - ``incremental_refresh_interval``
+ - ``data_protection_policy``
+
+ Note: Support for these fields may vary depending on the
+ connector type. For example, not all connectors support
+ ``destination_configs``.
+
+ If an unsupported or unknown field path is provided, the
+ request will return an ``INVALID_ARGUMENT`` error.
+
+ 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.cloud.discoveryengine_v1.types.DataConnector:
+ Manages the connection to external data sources for all data stores grouped
+ under a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ It's a singleton resource of
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ The initialization is only supported through
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, which will create a new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ and initialize its
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ """
+ # 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 = [data_connector, 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, data_connector_service.UpdateDataConnectorRequest):
+ request = data_connector_service.UpdateDataConnectorRequest(request)
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if data_connector is not None:
+ request.data_connector = data_connector
+ 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_data_connector]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("data_connector.name", request.data_connector.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) -> "DataConnectorServiceClient":
+ 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__ = ("DataConnectorServiceClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/README.rst b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/README.rst
new file mode 100644
index 000000000000..b4263c09e2c2
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/README.rst
@@ -0,0 +1,10 @@
+
+transport inheritance structure
+_______________________________
+
+``DataConnectorServiceTransport`` is the ABC for all transports.
+
+- public child ``DataConnectorServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``).
+- public child ``DataConnectorServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``).
+- private child ``_BaseDataConnectorServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``).
+- public child ``DataConnectorServiceRestTransport`` 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/data_connector_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/__init__.py
new file mode 100644
index 000000000000..26e182739e1d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_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 DataConnectorServiceTransport
+from .grpc import DataConnectorServiceGrpcTransport
+from .grpc_asyncio import DataConnectorServiceGrpcAsyncIOTransport
+from .rest import DataConnectorServiceRestInterceptor, DataConnectorServiceRestTransport
+
+# Compile a registry of transports.
+_transport_registry = OrderedDict() # type: Dict[str, Type[DataConnectorServiceTransport]]
+_transport_registry["grpc"] = DataConnectorServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = DataConnectorServiceGrpcAsyncIOTransport
+_transport_registry["rest"] = DataConnectorServiceRestTransport
+
+__all__ = (
+ "DataConnectorServiceTransport",
+ "DataConnectorServiceGrpcTransport",
+ "DataConnectorServiceGrpcAsyncIOTransport",
+ "DataConnectorServiceRestTransport",
+ "DataConnectorServiceRestInterceptor",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/base.py
new file mode 100644
index 000000000000..2d01a2db4319
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/base.py
@@ -0,0 +1,262 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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, operations_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 data_connector, data_connector_service
+from google.cloud.discoveryengine_v1.types import data_connector as gcd_data_connector
+
+DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=package_version.__version__
+)
+DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
+
+
+class DataConnectorServiceTransport(abc.ABC):
+ """Abstract transport class for DataConnectorService."""
+
+ AUTH_SCOPES = (
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "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.set_up_data_connector: gapic_v1.method.wrap_method(
+ self.set_up_data_connector,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.get_data_connector: gapic_v1.method.wrap_method(
+ self.get_data_connector,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.update_data_connector: gapic_v1.method.wrap_method(
+ self.update_data_connector,
+ 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 operations_client(self):
+ """Return the client designed to process long-running operations."""
+ raise NotImplementedError()
+
+ @property
+ def set_up_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.SetUpDataConnectorRequest],
+ Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def get_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.GetDataConnectorRequest],
+ Union[data_connector.DataConnector, Awaitable[data_connector.DataConnector]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def update_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.UpdateDataConnectorRequest],
+ Union[
+ gcd_data_connector.DataConnector,
+ Awaitable[gcd_data_connector.DataConnector],
+ ],
+ ]:
+ 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__ = ("DataConnectorServiceTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/grpc.py
new file mode 100644
index 000000000000..094a5fd19163
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/grpc.py
@@ -0,0 +1,507 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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, operations_v1
+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 data_connector, data_connector_service
+from google.cloud.discoveryengine_v1.types import data_connector as gcd_data_connector
+
+from .base import DEFAULT_CLIENT_INFO, DataConnectorServiceTransport
+
+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.DataConnectorService",
+ "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.DataConnectorService",
+ "rpcName": client_call_details.method,
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class DataConnectorServiceGrpcTransport(DataConnectorServiceTransport):
+ """gRPC backend transport for DataConnectorService.
+
+ Service for data connector management.
+
+ 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] = {}
+ self._operations_client: Optional[operations_v1.OperationsClient] = None
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
+
+ if 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 operations_client(self) -> operations_v1.OperationsClient:
+ """Create the client designed to process long-running operations.
+
+ This property caches on the instance; repeated calls return the same
+ client.
+ """
+ # Quick check: Only create a new client if we do not already have one.
+ if self._operations_client is None:
+ self._operations_client = operations_v1.OperationsClient(
+ self._logged_channel
+ )
+
+ # Return the client from cache.
+ return self._operations_client
+
+ @property
+ def set_up_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.SetUpDataConnectorRequest], operations_pb2.Operation
+ ]:
+ r"""Return a callable for the set up data connector method over gRPC.
+
+ Creates a
+ [Collection][google.cloud.discoveryengine.v1.Collection] and
+ sets up the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ for it. To stop a
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ after setup, use the
+ [CollectionService.DeleteCollection][google.cloud.discoveryengine.v1.CollectionService.DeleteCollection]
+ method.
+
+ Returns:
+ Callable[[~.SetUpDataConnectorRequest],
+ ~.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 "set_up_data_connector" not in self._stubs:
+ self._stubs["set_up_data_connector"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataConnectorService/SetUpDataConnector",
+ request_serializer=data_connector_service.SetUpDataConnectorRequest.serialize,
+ response_deserializer=operations_pb2.Operation.FromString,
+ )
+ return self._stubs["set_up_data_connector"]
+
+ @property
+ def get_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.GetDataConnectorRequest], data_connector.DataConnector
+ ]:
+ r"""Return a callable for the get data connector method over gRPC.
+
+ Gets the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ is a singleton resource for each
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Returns:
+ Callable[[~.GetDataConnectorRequest],
+ ~.DataConnector]:
+ 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_data_connector" not in self._stubs:
+ self._stubs["get_data_connector"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataConnectorService/GetDataConnector",
+ request_serializer=data_connector_service.GetDataConnectorRequest.serialize,
+ response_deserializer=data_connector.DataConnector.deserialize,
+ )
+ return self._stubs["get_data_connector"]
+
+ @property
+ def update_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.UpdateDataConnectorRequest],
+ gcd_data_connector.DataConnector,
+ ]:
+ r"""Return a callable for the update data connector method over gRPC.
+
+ Updates a
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ Returns:
+ Callable[[~.UpdateDataConnectorRequest],
+ ~.DataConnector]:
+ 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_data_connector" not in self._stubs:
+ self._stubs["update_data_connector"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataConnectorService/UpdateDataConnector",
+ request_serializer=data_connector_service.UpdateDataConnectorRequest.serialize,
+ response_deserializer=gcd_data_connector.DataConnector.deserialize,
+ )
+ return self._stubs["update_data_connector"]
+
+ 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__ = ("DataConnectorServiceGrpcTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/grpc_asyncio.py
new file mode 100644
index 000000000000..2e163b3d7034
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/grpc_asyncio.py
@@ -0,0 +1,557 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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, operations_v1
+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 data_connector, data_connector_service
+from google.cloud.discoveryengine_v1.types import data_connector as gcd_data_connector
+
+from .base import DEFAULT_CLIENT_INFO, DataConnectorServiceTransport
+from .grpc import DataConnectorServiceGrpcTransport
+
+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.DataConnectorService",
+ "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.DataConnectorService",
+ "rpcName": str(client_call_details.method),
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class DataConnectorServiceGrpcAsyncIOTransport(DataConnectorServiceTransport):
+ """gRPC AsyncIO backend transport for DataConnectorService.
+
+ Service for data connector management.
+
+ 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] = {}
+ self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None
+
+ if api_mtls_endpoint:
+ warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
+ if client_cert_source:
+ warnings.warn("client_cert_source is deprecated", DeprecationWarning)
+
+ if 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 operations_client(self) -> operations_v1.OperationsAsyncClient:
+ """Create the client designed to process long-running operations.
+
+ This property caches on the instance; repeated calls return the same
+ client.
+ """
+ # Quick check: Only create a new client if we do not already have one.
+ if self._operations_client is None:
+ self._operations_client = operations_v1.OperationsAsyncClient(
+ self._logged_channel
+ )
+
+ # Return the client from cache.
+ return self._operations_client
+
+ @property
+ def set_up_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.SetUpDataConnectorRequest],
+ Awaitable[operations_pb2.Operation],
+ ]:
+ r"""Return a callable for the set up data connector method over gRPC.
+
+ Creates a
+ [Collection][google.cloud.discoveryengine.v1.Collection] and
+ sets up the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ for it. To stop a
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ after setup, use the
+ [CollectionService.DeleteCollection][google.cloud.discoveryengine.v1.CollectionService.DeleteCollection]
+ method.
+
+ Returns:
+ Callable[[~.SetUpDataConnectorRequest],
+ 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 "set_up_data_connector" not in self._stubs:
+ self._stubs["set_up_data_connector"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataConnectorService/SetUpDataConnector",
+ request_serializer=data_connector_service.SetUpDataConnectorRequest.serialize,
+ response_deserializer=operations_pb2.Operation.FromString,
+ )
+ return self._stubs["set_up_data_connector"]
+
+ @property
+ def get_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.GetDataConnectorRequest],
+ Awaitable[data_connector.DataConnector],
+ ]:
+ r"""Return a callable for the get data connector method over gRPC.
+
+ Gets the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ is a singleton resource for each
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Returns:
+ Callable[[~.GetDataConnectorRequest],
+ Awaitable[~.DataConnector]]:
+ 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_data_connector" not in self._stubs:
+ self._stubs["get_data_connector"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataConnectorService/GetDataConnector",
+ request_serializer=data_connector_service.GetDataConnectorRequest.serialize,
+ response_deserializer=data_connector.DataConnector.deserialize,
+ )
+ return self._stubs["get_data_connector"]
+
+ @property
+ def update_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.UpdateDataConnectorRequest],
+ Awaitable[gcd_data_connector.DataConnector],
+ ]:
+ r"""Return a callable for the update data connector method over gRPC.
+
+ Updates a
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ Returns:
+ Callable[[~.UpdateDataConnectorRequest],
+ Awaitable[~.DataConnector]]:
+ 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_data_connector" not in self._stubs:
+ self._stubs["update_data_connector"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataConnectorService/UpdateDataConnector",
+ request_serializer=data_connector_service.UpdateDataConnectorRequest.serialize,
+ response_deserializer=gcd_data_connector.DataConnector.deserialize,
+ )
+ return self._stubs["update_data_connector"]
+
+ def _prep_wrapped_messages(self, client_info):
+ """Precompute the wrapped methods, overriding the base class method to use async wrappers."""
+ self._wrapped_methods = {
+ self.set_up_data_connector: self._wrap_method(
+ self.set_up_data_connector,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.get_data_connector: self._wrap_method(
+ self.get_data_connector,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.update_data_connector: self._wrap_method(
+ self.update_data_connector,
+ 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__ = ("DataConnectorServiceGrpcAsyncIOTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/rest.py
new file mode 100644
index 000000000000..0d7b8e7dce17
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/rest.py
@@ -0,0 +1,1525 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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, operations_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 data_connector, data_connector_service
+from google.cloud.discoveryengine_v1.types import data_connector as gcd_data_connector
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .rest_base import _BaseDataConnectorServiceRestTransport
+
+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 DataConnectorServiceRestInterceptor:
+ """Interceptor for DataConnectorService.
+
+ 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 DataConnectorServiceRestTransport.
+
+ .. code-block:: python
+ class MyCustomDataConnectorServiceInterceptor(DataConnectorServiceRestInterceptor):
+ def pre_get_data_connector(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_get_data_connector(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_set_up_data_connector(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_set_up_data_connector(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_update_data_connector(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_update_data_connector(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ transport = DataConnectorServiceRestTransport(interceptor=MyCustomDataConnectorServiceInterceptor())
+ client = DataConnectorServiceClient(transport=transport)
+
+
+ """
+
+ def pre_get_data_connector(
+ self,
+ request: data_connector_service.GetDataConnectorRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ data_connector_service.GetDataConnectorRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for get_data_connector
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the DataConnectorService server.
+ """
+ return request, metadata
+
+ def post_get_data_connector(
+ self, response: data_connector.DataConnector
+ ) -> data_connector.DataConnector:
+ """Post-rpc interceptor for get_data_connector
+
+ DEPRECATED. Please use the `post_get_data_connector_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the DataConnectorService server but before
+ it is returned to user code. This `post_get_data_connector` interceptor runs
+ before the `post_get_data_connector_with_metadata` interceptor.
+ """
+ return response
+
+ def post_get_data_connector_with_metadata(
+ self,
+ response: data_connector.DataConnector,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[data_connector.DataConnector, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for get_data_connector
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the DataConnectorService server but before it is returned to user code.
+
+ We recommend only using this `post_get_data_connector_with_metadata`
+ interceptor in new development instead of the `post_get_data_connector` interceptor.
+ When both interceptors are used, this `post_get_data_connector_with_metadata` interceptor runs after the
+ `post_get_data_connector` interceptor. The (possibly modified) response returned by
+ `post_get_data_connector` will be passed to
+ `post_get_data_connector_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_set_up_data_connector(
+ self,
+ request: data_connector_service.SetUpDataConnectorRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ data_connector_service.SetUpDataConnectorRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for set_up_data_connector
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the DataConnectorService server.
+ """
+ return request, metadata
+
+ def post_set_up_data_connector(
+ self, response: operations_pb2.Operation
+ ) -> operations_pb2.Operation:
+ """Post-rpc interceptor for set_up_data_connector
+
+ DEPRECATED. Please use the `post_set_up_data_connector_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the DataConnectorService server but before
+ it is returned to user code. This `post_set_up_data_connector` interceptor runs
+ before the `post_set_up_data_connector_with_metadata` interceptor.
+ """
+ return response
+
+ def post_set_up_data_connector_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 set_up_data_connector
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the DataConnectorService server but before it is returned to user code.
+
+ We recommend only using this `post_set_up_data_connector_with_metadata`
+ interceptor in new development instead of the `post_set_up_data_connector` interceptor.
+ When both interceptors are used, this `post_set_up_data_connector_with_metadata` interceptor runs after the
+ `post_set_up_data_connector` interceptor. The (possibly modified) response returned by
+ `post_set_up_data_connector` will be passed to
+ `post_set_up_data_connector_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_update_data_connector(
+ self,
+ request: data_connector_service.UpdateDataConnectorRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ data_connector_service.UpdateDataConnectorRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for update_data_connector
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the DataConnectorService server.
+ """
+ return request, metadata
+
+ def post_update_data_connector(
+ self, response: gcd_data_connector.DataConnector
+ ) -> gcd_data_connector.DataConnector:
+ """Post-rpc interceptor for update_data_connector
+
+ DEPRECATED. Please use the `post_update_data_connector_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the DataConnectorService server but before
+ it is returned to user code. This `post_update_data_connector` interceptor runs
+ before the `post_update_data_connector_with_metadata` interceptor.
+ """
+ return response
+
+ def post_update_data_connector_with_metadata(
+ self,
+ response: gcd_data_connector.DataConnector,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ gcd_data_connector.DataConnector, Sequence[Tuple[str, Union[str, bytes]]]
+ ]:
+ """Post-rpc interceptor for update_data_connector
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the DataConnectorService server but before it is returned to user code.
+
+ We recommend only using this `post_update_data_connector_with_metadata`
+ interceptor in new development instead of the `post_update_data_connector` interceptor.
+ When both interceptors are used, this `post_update_data_connector_with_metadata` interceptor runs after the
+ `post_update_data_connector` interceptor. The (possibly modified) response returned by
+ `post_update_data_connector` will be passed to
+ `post_update_data_connector_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 DataConnectorService 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 DataConnectorService 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 DataConnectorService 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 DataConnectorService 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 DataConnectorService 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 DataConnectorService server but before
+ it is returned to user code.
+ """
+ return response
+
+
+@dataclasses.dataclass
+class DataConnectorServiceRestStub:
+ _session: AuthorizedSession
+ _host: str
+ _interceptor: DataConnectorServiceRestInterceptor
+
+
+class DataConnectorServiceRestTransport(_BaseDataConnectorServiceRestTransport):
+ """REST backend synchronous transport for DataConnectorService.
+
+ Service for data connector management.
+
+ 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[DataConnectorServiceRestInterceptor] = 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[DataConnectorServiceRestInterceptor]): 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 DataConnectorServiceRestInterceptor()
+ 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/*/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": "*",
+ },
+ ],
+ "google.longrunning.Operations.GetOperation": [
+ {
+ "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/*}",
+ },
+ ],
+ "google.longrunning.Operations.ListOperations": [
+ {
+ "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",
+ },
+ ],
+ }
+
+ 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 _GetDataConnector(
+ _BaseDataConnectorServiceRestTransport._BaseGetDataConnector,
+ DataConnectorServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("DataConnectorServiceRestTransport.GetDataConnector")
+
+ @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: data_connector_service.GetDataConnectorRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> data_connector.DataConnector:
+ r"""Call the get data connector method over HTTP.
+
+ Args:
+ request (~.data_connector_service.GetDataConnectorRequest):
+ The request object. Request for
+ [DataConnectorService.GetDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.GetDataConnector]
+ 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:
+ ~.data_connector.DataConnector:
+ Manages the connection to external data sources for all
+ data stores grouped under a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ It's a singleton resource of
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ The initialization is only supported through
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, which will create a new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ and initialize its
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ """
+
+ http_options = _BaseDataConnectorServiceRestTransport._BaseGetDataConnector._get_http_options()
+ request, metadata = self._interceptor.pre_get_data_connector(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseDataConnectorServiceRestTransport._BaseGetDataConnector,
+ "_BaseGetDataConnector__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.DataConnectorServiceClient.GetDataConnector",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "rpcName": "GetDataConnector",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ DataConnectorServiceRestTransport._GetDataConnector._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 = data_connector.DataConnector()
+ pb_resp = data_connector.DataConnector.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_get_data_connector(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_get_data_connector_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = data_connector.DataConnector.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.DataConnectorServiceClient.get_data_connector",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "rpcName": "GetDataConnector",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _SetUpDataConnector(
+ _BaseDataConnectorServiceRestTransport._BaseSetUpDataConnector,
+ DataConnectorServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("DataConnectorServiceRestTransport.SetUpDataConnector")
+
+ @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: data_connector_service.SetUpDataConnectorRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> operations_pb2.Operation:
+ r"""Call the set up data connector method over HTTP.
+
+ Args:
+ request (~.data_connector_service.SetUpDataConnectorRequest):
+ The request object. Request for
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ 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:
+ This resource represents a
+ long-running operation that is the
+ result of a network API call.
+
+ """
+
+ http_options = _BaseDataConnectorServiceRestTransport._BaseSetUpDataConnector._get_http_options()
+ request, metadata = self._interceptor.pre_set_up_data_connector(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseDataConnectorServiceRestTransport._BaseSetUpDataConnector,
+ "_BaseSetUpDataConnector__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.DataConnectorServiceClient.SetUpDataConnector",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "rpcName": "SetUpDataConnector",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ DataConnectorServiceRestTransport._SetUpDataConnector._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_set_up_data_connector(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_set_up_data_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.discoveryengine_v1.DataConnectorServiceClient.set_up_data_connector",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "rpcName": "SetUpDataConnector",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _UpdateDataConnector(
+ _BaseDataConnectorServiceRestTransport._BaseUpdateDataConnector,
+ DataConnectorServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("DataConnectorServiceRestTransport.UpdateDataConnector")
+
+ @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: data_connector_service.UpdateDataConnectorRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> gcd_data_connector.DataConnector:
+ r"""Call the update data connector method over HTTP.
+
+ Args:
+ request (~.data_connector_service.UpdateDataConnectorRequest):
+ The request object. Request message for
+ [DataConnectorService.UpdateDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.UpdateDataConnector]
+ 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:
+ ~.gcd_data_connector.DataConnector:
+ Manages the connection to external data sources for all
+ data stores grouped under a
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ It's a singleton resource of
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ The initialization is only supported through
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, which will create a new
+ [Collection][google.cloud.discoveryengine.v1.Collection]
+ and initialize its
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ """
+
+ http_options = _BaseDataConnectorServiceRestTransport._BaseUpdateDataConnector._get_http_options()
+ request, metadata = self._interceptor.pre_update_data_connector(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseDataConnectorServiceRestTransport._BaseUpdateDataConnector,
+ "_BaseUpdateDataConnector__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.DataConnectorServiceClient.UpdateDataConnector",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "rpcName": "UpdateDataConnector",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ DataConnectorServiceRestTransport._UpdateDataConnector._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 = gcd_data_connector.DataConnector()
+ pb_resp = gcd_data_connector.DataConnector.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_update_data_connector(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_update_data_connector_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = gcd_data_connector.DataConnector.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.DataConnectorServiceClient.update_data_connector",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "rpcName": "UpdateDataConnector",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ @property
+ def get_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.GetDataConnectorRequest], data_connector.DataConnector
+ ]:
+ # 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._GetDataConnector(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def set_up_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.SetUpDataConnectorRequest], 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._SetUpDataConnector(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def update_data_connector(
+ self,
+ ) -> Callable[
+ [data_connector_service.UpdateDataConnectorRequest],
+ gcd_data_connector.DataConnector,
+ ]:
+ # 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._UpdateDataConnector(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(
+ _BaseDataConnectorServiceRestTransport._BaseCancelOperation,
+ DataConnectorServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("DataConnectorServiceRestTransport.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 = _BaseDataConnectorServiceRestTransport._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(
+ _BaseDataConnectorServiceRestTransport._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.DataConnectorServiceClient.CancelOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "rpcName": "CancelOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = DataConnectorServiceRestTransport._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(
+ _BaseDataConnectorServiceRestTransport._BaseGetOperation,
+ DataConnectorServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("DataConnectorServiceRestTransport.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 = _BaseDataConnectorServiceRestTransport._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(
+ _BaseDataConnectorServiceRestTransport._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.DataConnectorServiceClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "rpcName": "GetOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = DataConnectorServiceRestTransport._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.DataConnectorServiceAsyncClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "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(
+ _BaseDataConnectorServiceRestTransport._BaseListOperations,
+ DataConnectorServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("DataConnectorServiceRestTransport.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 = _BaseDataConnectorServiceRestTransport._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(
+ _BaseDataConnectorServiceRestTransport._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.DataConnectorServiceClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "rpcName": "ListOperations",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = DataConnectorServiceRestTransport._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.DataConnectorServiceAsyncClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "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__ = ("DataConnectorServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/rest_base.py
new file mode 100644
index 000000000000..b27baba7553d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_connector_service/transports/rest_base.py
@@ -0,0 +1,331 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 data_connector, data_connector_service
+from google.cloud.discoveryengine_v1.types import data_connector as gcd_data_connector
+
+from .base import DEFAULT_CLIENT_INFO, DataConnectorServiceTransport
+
+
+class _BaseDataConnectorServiceRestTransport(DataConnectorServiceTransport):
+ """Base REST backend transport for DataConnectorService.
+
+ 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 _BaseGetDataConnector:
+ 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/*/collections/*/dataConnector}",
+ },
+ ]
+ return http_options
+
+ class _BaseSetUpDataConnector:
+ 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/*}:setUpDataConnector",
+ "body": "*",
+ },
+ {
+ "method": "post",
+ "uri": "/v1/{parent=projects/*/locations/*}:setUpDataConnectorV2",
+ "body": "data_connector",
+ },
+ ]
+ return http_options
+
+ class _BaseUpdateDataConnector:
+ 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/{data_connector.name=projects/*/locations/*/collections/*/dataConnector}",
+ "body": "data_connector",
+ },
+ ]
+ 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__ = ("_BaseDataConnectorServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/async_client.py
index 5aaceec237f4..8b364cb58487 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/async_client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/async_client.py
@@ -46,6 +46,8 @@
import google.api_core.operation as operation # type: ignore
import google.api_core.operation_async as operation_async # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
@@ -96,6 +98,10 @@ class DataStoreServiceAsyncClient:
parse_cmek_config_path = staticmethod(DataStoreServiceClient.parse_cmek_config_path)
collection_path = staticmethod(DataStoreServiceClient.collection_path)
parse_collection_path = staticmethod(DataStoreServiceClient.parse_collection_path)
+ content_policy_path = staticmethod(DataStoreServiceClient.content_policy_path)
+ parse_content_policy_path = staticmethod(
+ DataStoreServiceClient.parse_content_policy_path
+ )
crypto_keys_path = staticmethod(DataStoreServiceClient.crypto_keys_path)
parse_crypto_keys_path = staticmethod(DataStoreServiceClient.parse_crypto_keys_path)
crypto_key_versions_path = staticmethod(
@@ -118,6 +124,8 @@ class DataStoreServiceAsyncClient:
parse_identity_mapping_store_path = staticmethod(
DataStoreServiceClient.parse_identity_mapping_store_path
)
+ notebook_path = staticmethod(DataStoreServiceClient.notebook_path)
+ parse_notebook_path = staticmethod(DataStoreServiceClient.parse_notebook_path)
schema_path = staticmethod(DataStoreServiceClient.schema_path)
parse_schema_path = staticmethod(DataStoreServiceClient.parse_schema_path)
common_billing_account_path = staticmethod(
@@ -1062,6 +1070,298 @@ async def sample_update_data_store():
# Done; return the response.
return response
+ async def get_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Gets the IAM access control policy for a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ async def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.DataStoreServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]):
+ The request object. Request message for ``GetIamPolicy`` method.
+ resource (:class:`str`):
+ REQUIRED: The resource for which the
+ policy is being requested. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ if isinstance(request, dict):
+ request = iam_policy_pb2.GetIamPolicyRequest(**request)
+ elif not request:
+ request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.get_iam_policy
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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 set_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Sets the IAM access control policy for a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on a DataStore
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``
+ ``roles/discoveryengine.agentspaceAdmin``
+ ``roles/discoveryengine.viewer``
+ ``roles/discoveryengine.agentspaceViewer``
+ ``roles/discoveryengine.user``
+ ``roles/discoveryengine.agentspaceUser`` Attempting to grant any
+ other role will result in a warning in logging.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ async def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.DataStoreServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]):
+ The request object. Request message for ``SetIamPolicy`` method.
+ resource (:class:`str`):
+ REQUIRED: The resource for which the
+ policy is being specified. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ if isinstance(request, dict):
+ request = iam_policy_pb2.SetIamPolicyRequest(**request)
+ elif not request:
+ request = iam_policy_pb2.SetIamPolicyRequest(resource=resource)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.set_iam_policy
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/client.py
index 98ed5405b59e..d65b9f93ab5a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/client.py
@@ -70,6 +70,8 @@
import google.api_core.operation as operation # type: ignore
import google.api_core.operation_async as operation_async # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
@@ -231,6 +233,28 @@ def parse_collection_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 crypto_keys_path(
project: str,
@@ -347,6 +371,28 @@ def parse_identity_mapping_store_path(path: str) -> Dict[str, str]:
)
return m.groupdict() if m else {}
+ @staticmethod
+ def notebook_path(
+ project: str,
+ location: str,
+ notebook: str,
+ ) -> str:
+ """Returns a fully-qualified notebook string."""
+ return "projects/{project}/locations/{location}/notebooks/{notebook}".format(
+ project=project,
+ location=location,
+ notebook=notebook,
+ )
+
+ @staticmethod
+ def parse_notebook_path(path: str) -> Dict[str, str]:
+ """Parses a notebook path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/notebooks/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
@staticmethod
def schema_path(
project: str,
@@ -1480,6 +1526,300 @@ def sample_update_data_store():
# Done; return the response.
return response
+ def get_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Gets the IAM access control policy for a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.DataStoreServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]):
+ The request object. Request message for ``GetIamPolicy`` method.
+ resource (str):
+ REQUIRED: The resource for which the
+ policy is being requested. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each value must be of type `str`,
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
+ be of type `bytes`.
+
+ Returns:
+ google.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ if isinstance(request, dict):
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ request = iam_policy_pb2.GetIamPolicyRequest(**request)
+ elif not request:
+ # Null request, just make one.
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ if resource is not None:
+ request.resource = resource
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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 set_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Sets the IAM access control policy for a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on a DataStore
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``
+ ``roles/discoveryengine.agentspaceAdmin``
+ ``roles/discoveryengine.viewer``
+ ``roles/discoveryengine.agentspaceViewer``
+ ``roles/discoveryengine.user``
+ ``roles/discoveryengine.agentspaceUser`` Attempting to grant any
+ other role will result in a warning in logging.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.DataStoreServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]):
+ The request object. Request message for ``SetIamPolicy`` method.
+ resource (str):
+ REQUIRED: The resource for which the
+ policy is being specified. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each value must be of type `str`,
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
+ be of type `bytes`.
+
+ Returns:
+ google.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ if isinstance(request, dict):
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ request = iam_policy_pb2.SetIamPolicyRequest(**request)
+ elif not request:
+ # Null request, just make one.
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ if resource is not None:
+ request.resource = resource
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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) -> "DataStoreServiceClient":
return self
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/base.py
index b731baffe96d..c57fdcd4b040 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/base.py
@@ -18,6 +18,8 @@
import google.api_core
import google.auth # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1, operations_v1
@@ -40,7 +42,11 @@
class DataStoreServiceTransport(abc.ABC):
"""Abstract transport class for DataStoreService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
@@ -168,6 +174,16 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
+ self.get_iam_policy: gapic_v1.method.wrap_method(
+ self.get_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.set_iam_policy: gapic_v1.method.wrap_method(
+ self.set_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.cancel_operation: gapic_v1.method.wrap_method(
self.cancel_operation,
default_timeout=None,
@@ -247,6 +263,24 @@ def update_data_store(
]:
raise NotImplementedError()
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[
+ [iam_policy_pb2.GetIamPolicyRequest],
+ Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[
+ [iam_policy_pb2.SetIamPolicyRequest],
+ Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
+ ]:
+ raise NotImplementedError()
+
@property
def list_operations(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/grpc.py
index f9c5cc9430ac..b26576948b64 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/grpc.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/grpc.py
@@ -20,6 +20,8 @@
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
import google.auth # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
@@ -496,6 +498,74 @@ def update_data_store(
)
return self._stubs["update_data_store"]
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
+ r"""Return a callable for the get iam policy method over gRPC.
+
+ Gets the IAM access control policy for a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ Returns:
+ Callable[[~.GetIamPolicyRequest],
+ ~.Policy]:
+ 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_iam_policy" not in self._stubs:
+ self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataStoreService/GetIamPolicy",
+ request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["get_iam_policy"]
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
+ r"""Return a callable for the set iam policy method over gRPC.
+
+ Sets the IAM access control policy for a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on a DataStore
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``
+ ``roles/discoveryengine.agentspaceAdmin``
+ ``roles/discoveryengine.viewer``
+ ``roles/discoveryengine.agentspaceViewer``
+ ``roles/discoveryengine.user``
+ ``roles/discoveryengine.agentspaceUser`` Attempting to grant any
+ other role will result in a warning in logging.
+
+ Returns:
+ Callable[[~.SetIamPolicyRequest],
+ ~.Policy]:
+ 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 "set_iam_policy" not in self._stubs:
+ self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataStoreService/SetIamPolicy",
+ request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["set_iam_policy"]
+
def close(self):
self._logged_channel.close()
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/grpc_asyncio.py
index 431c797efb86..04e2b8437d26 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/grpc_asyncio.py
@@ -20,6 +20,8 @@
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
@@ -506,6 +508,74 @@ def update_data_store(
)
return self._stubs["update_data_store"]
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
+ r"""Return a callable for the get iam policy method over gRPC.
+
+ Gets the IAM access control policy for a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ Returns:
+ Callable[[~.GetIamPolicyRequest],
+ Awaitable[~.Policy]]:
+ 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_iam_policy" not in self._stubs:
+ self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataStoreService/GetIamPolicy",
+ request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["get_iam_policy"]
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
+ r"""Return a callable for the set iam policy method over gRPC.
+
+ Sets the IAM access control policy for a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on a DataStore
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``
+ ``roles/discoveryengine.agentspaceAdmin``
+ ``roles/discoveryengine.viewer``
+ ``roles/discoveryengine.agentspaceViewer``
+ ``roles/discoveryengine.user``
+ ``roles/discoveryengine.agentspaceUser`` Attempting to grant any
+ other role will result in a warning in logging.
+
+ Returns:
+ Callable[[~.SetIamPolicyRequest],
+ Awaitable[~.Policy]]:
+ 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 "set_iam_policy" not in self._stubs:
+ self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.DataStoreService/SetIamPolicy",
+ request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["set_iam_policy"]
+
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
@@ -534,6 +604,16 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
+ self.get_iam_policy: self._wrap_method(
+ self.get_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.set_iam_policy: self._wrap_method(
+ self.set_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.cancel_operation: self._wrap_method(
self.cancel_operation,
default_timeout=None,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest.py
index 767c28e8d12e..e1d6b8cce1d8 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest.py
@@ -19,6 +19,8 @@
import warnings
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
@@ -99,6 +101,14 @@ def post_get_data_store(self, response):
logging.log(f"Received response: {response}")
return response
+ def pre_get_iam_policy(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_get_iam_policy(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
def pre_list_data_stores(self, request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
@@ -107,6 +117,14 @@ def post_list_data_stores(self, response):
logging.log(f"Received response: {response}")
return response
+ def pre_set_iam_policy(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_set_iam_policy(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
def pre_update_data_store(self, request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
@@ -267,6 +285,52 @@ def post_get_data_store_with_metadata(
"""
return response, metadata
+ 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 DataStoreService server.
+ """
+ return request, metadata
+
+ def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
+ """Post-rpc interceptor for get_iam_policy
+
+ DEPRECATED. Please use the `post_get_iam_policy_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the DataStoreService server but before
+ it is returned to user code. This `post_get_iam_policy` interceptor runs
+ before the `post_get_iam_policy_with_metadata` interceptor.
+ """
+ return response
+
+ def post_get_iam_policy_with_metadata(
+ self,
+ response: policy_pb2.Policy,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for get_iam_policy
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the DataStoreService server but before it is returned to user code.
+
+ We recommend only using this `post_get_iam_policy_with_metadata`
+ interceptor in new development instead of the `post_get_iam_policy` interceptor.
+ When both interceptors are used, this `post_get_iam_policy_with_metadata` interceptor runs after the
+ `post_get_iam_policy` interceptor. The (possibly modified) response returned by
+ `post_get_iam_policy` will be passed to
+ `post_get_iam_policy_with_metadata`.
+ """
+ return response, metadata
+
def pre_list_data_stores(
self,
request: data_store_service.ListDataStoresRequest,
@@ -319,6 +383,52 @@ def post_list_data_stores_with_metadata(
"""
return response, metadata
+ 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 DataStoreService server.
+ """
+ return request, metadata
+
+ def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
+ """Post-rpc interceptor for set_iam_policy
+
+ DEPRECATED. Please use the `post_set_iam_policy_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the DataStoreService server but before
+ it is returned to user code. This `post_set_iam_policy` interceptor runs
+ before the `post_set_iam_policy_with_metadata` interceptor.
+ """
+ return response
+
+ def post_set_iam_policy_with_metadata(
+ self,
+ response: policy_pb2.Policy,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """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 DataStoreService server but before it is returned to user code.
+
+ We recommend only using this `post_set_iam_policy_with_metadata`
+ interceptor in new development instead of the `post_set_iam_policy` interceptor.
+ When both interceptors are used, this `post_set_iam_policy_with_metadata` interceptor runs after the
+ `post_set_iam_policy` interceptor. The (possibly modified) response returned by
+ `post_set_iam_policy` will be passed to
+ `post_set_iam_policy_with_metadata`.
+ """
+ return response, metadata
+
def pre_update_data_store(
self,
request: data_store_service.UpdateDataStoreRequest,
@@ -603,6 +713,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
@@ -1169,6 +1283,226 @@ def __call__(
)
return resp
+ class _GetIamPolicy(
+ _BaseDataStoreServiceRestTransport._BaseGetIamPolicy, DataStoreServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("DataStoreServiceRestTransport.GetIamPolicy")
+
+ @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: iam_policy_pb2.GetIamPolicyRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Call the get iam policy method over HTTP.
+
+ Args:
+ request (~.iam_policy_pb2.GetIamPolicyRequest):
+ The request object. Request message for ``GetIamPolicy`` 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:
+ ~.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which
+ specifies access controls for Google Cloud resources.
+
+ A ``Policy`` is a collection of ``bindings``. A
+ ``binding`` binds one or more ``members``, or
+ principals, to a single ``role``. Principals can be user
+ accounts, service accounts, Google groups, and domains
+ (such as G Suite). A ``role`` is a named list of
+ permissions; each ``role`` can be an IAM predefined role
+ or a user-created custom role.
+
+ For some types of Google Cloud resources, a ``binding``
+ can also specify a ``condition``, which is a logical
+ expression that allows access to a resource only if the
+ expression evaluates to ``true``. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the `IAM
+ documentation `__.
+
+ **JSON example:**
+
+ ::
+
+ {
+ "bindings": [
+ {
+ "role": "roles/resourcemanager.organizationAdmin",
+ "members": [
+ "user:mike@example.com",
+ "group:admins@example.com",
+ "domain:google.com",
+ "serviceAccount:my-project-id@appspot.gserviceaccount.com"
+ ]
+ },
+ {
+ "role": "roles/resourcemanager.organizationViewer",
+ "members": [
+ "user:eve@example.com"
+ ],
+ "condition": {
+ "title": "expirable access",
+ "description": "Does not grant access after Sep 2020",
+ "expression": "request.time <
+ timestamp('2020-10-01T00:00:00.000Z')",
+ }
+ }
+ ],
+ "etag": "BwWWja0YfJA=",
+ "version": 3
+ }
+
+ **YAML example:**
+
+ ::
+
+ bindings:
+ - members:
+ - user:mike@example.com
+ - group:admins@example.com
+ - domain:google.com
+ - serviceAccount:my-project-id@appspot.gserviceaccount.com
+ role: roles/resourcemanager.organizationAdmin
+ - members:
+ - user:eve@example.com
+ role: roles/resourcemanager.organizationViewer
+ condition:
+ title: expirable access
+ description: Does not grant access after Sep 2020
+ expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
+ etag: BwWWja0YfJA=
+ version: 3
+
+ For a description of IAM and its features, see the `IAM
+ documentation `__.
+
+ """
+
+ http_options = (
+ _BaseDataStoreServiceRestTransport._BaseGetIamPolicy._get_http_options()
+ )
+ request, metadata = self._interceptor.pre_get_iam_policy(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseDataStoreServiceRestTransport._BaseGetIamPolicy,
+ "_BaseGetIamPolicy__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 = 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.DataStoreServiceClient.GetIamPolicy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "rpcName": "GetIamPolicy",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = DataStoreServiceRestTransport._GetIamPolicy._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 = policy_pb2.Policy()
+ pb_resp = resp
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_get_iam_policy(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_get_iam_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.discoveryengine_v1.DataStoreServiceClient.get_iam_policy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "rpcName": "GetIamPolicy",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
class _ListDataStores(
_BaseDataStoreServiceRestTransport._BaseListDataStores, DataStoreServiceRestStub
):
@@ -1321,6 +1655,228 @@ def __call__(
)
return resp
+ class _SetIamPolicy(
+ _BaseDataStoreServiceRestTransport._BaseSetIamPolicy, DataStoreServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("DataStoreServiceRestTransport.SetIamPolicy")
+
+ @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: iam_policy_pb2.SetIamPolicyRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Call the set iam policy method over HTTP.
+
+ Args:
+ request (~.iam_policy_pb2.SetIamPolicyRequest):
+ The request object. Request message for ``SetIamPolicy`` 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:
+ ~.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which
+ specifies access controls for Google Cloud resources.
+
+ A ``Policy`` is a collection of ``bindings``. A
+ ``binding`` binds one or more ``members``, or
+ principals, to a single ``role``. Principals can be user
+ accounts, service accounts, Google groups, and domains
+ (such as G Suite). A ``role`` is a named list of
+ permissions; each ``role`` can be an IAM predefined role
+ or a user-created custom role.
+
+ For some types of Google Cloud resources, a ``binding``
+ can also specify a ``condition``, which is a logical
+ expression that allows access to a resource only if the
+ expression evaluates to ``true``. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the `IAM
+ documentation `__.
+
+ **JSON example:**
+
+ ::
+
+ {
+ "bindings": [
+ {
+ "role": "roles/resourcemanager.organizationAdmin",
+ "members": [
+ "user:mike@example.com",
+ "group:admins@example.com",
+ "domain:google.com",
+ "serviceAccount:my-project-id@appspot.gserviceaccount.com"
+ ]
+ },
+ {
+ "role": "roles/resourcemanager.organizationViewer",
+ "members": [
+ "user:eve@example.com"
+ ],
+ "condition": {
+ "title": "expirable access",
+ "description": "Does not grant access after Sep 2020",
+ "expression": "request.time <
+ timestamp('2020-10-01T00:00:00.000Z')",
+ }
+ }
+ ],
+ "etag": "BwWWja0YfJA=",
+ "version": 3
+ }
+
+ **YAML example:**
+
+ ::
+
+ bindings:
+ - members:
+ - user:mike@example.com
+ - group:admins@example.com
+ - domain:google.com
+ - serviceAccount:my-project-id@appspot.gserviceaccount.com
+ role: roles/resourcemanager.organizationAdmin
+ - members:
+ - user:eve@example.com
+ role: roles/resourcemanager.organizationViewer
+ condition:
+ title: expirable access
+ description: Does not grant access after Sep 2020
+ expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
+ etag: BwWWja0YfJA=
+ version: 3
+
+ For a description of IAM and its features, see the `IAM
+ documentation `__.
+
+ """
+
+ http_options = (
+ _BaseDataStoreServiceRestTransport._BaseSetIamPolicy._get_http_options()
+ )
+ request, metadata = self._interceptor.pre_set_iam_policy(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseDataStoreServiceRestTransport._BaseSetIamPolicy,
+ "_BaseSetIamPolicy__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 = 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.DataStoreServiceClient.SetIamPolicy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "rpcName": "SetIamPolicy",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = DataStoreServiceRestTransport._SetIamPolicy._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 = policy_pb2.Policy()
+ pb_resp = resp
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_set_iam_policy(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_set_iam_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.discoveryengine_v1.DataStoreServiceClient.set_iam_policy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "rpcName": "SetIamPolicy",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
class _UpdateDataStore(
_BaseDataStoreServiceRestTransport._BaseUpdateDataStore,
DataStoreServiceRestStub,
@@ -1501,6 +2057,14 @@ def get_data_store(
# In C++ this would require a dynamic_cast
return self._GetDataStore(self._session, self._host, self._interceptor) # type: ignore
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
+ # 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._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
+
@property
def list_data_stores(
self,
@@ -1512,6 +2076,14 @@ def list_data_stores(
# In C++ this would require a dynamic_cast
return self._ListDataStores(self._session, self._host, self._interceptor) # type: ignore
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
+ # 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._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
+
@property
def update_data_store(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest_base.py
index 63d92d4909b0..3677500d2a41 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/data_store_service/transports/rest_base.py
@@ -17,6 +17,8 @@
import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
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
@@ -154,6 +156,26 @@ def _get_http_options():
]
return http_options
+ class _BaseGetIamPolicy:
+ 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/{resource=projects/*/locations/*/collections/*/dataStores/*}:getIamPolicy",
+ },
+ {
+ "method": "get",
+ "uri": "/v1/{resource=projects/*/locations/*/dataStores/*}:getIamPolicy",
+ },
+ ]
+ return http_options
+
class _BaseListDataStores:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@@ -174,6 +196,28 @@ def _get_http_options():
]
return http_options
+ class _BaseSetIamPolicy:
+ 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/{resource=projects/*/locations/*/collections/*/dataStores/*}:setIamPolicy",
+ "body": "*",
+ },
+ {
+ "method": "post",
+ "uri": "/v1/{resource=projects/*/locations/*/dataStores/*}:setIamPolicy",
+ "body": "*",
+ },
+ ]
+ return http_options
+
class _BaseUpdateDataStore:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@@ -265,6 +309,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/base.py
index 0a5803c2e7d9..4f5f5d44dca0 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/base.py
@@ -46,7 +46,11 @@
class DocumentServiceTransport(abc.ABC):
"""Abstract transport class for DocumentService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py
index 4acffbc2e57b..ad1a4f2c6c11 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest.py
@@ -736,6 +736,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest_base.py
index 2d7f33d4349b..8a6caef07d49 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/document_service/transports/rest_base.py
@@ -337,6 +337,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/async_client.py
index a4adf0888c7c..8bb2a68701d5 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/async_client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/async_client.py
@@ -46,6 +46,8 @@
import google.api_core.operation as operation # type: ignore
import google.api_core.operation_async as operation_async # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
@@ -53,7 +55,14 @@
from google.longrunning import operations_pb2 # type: ignore
from google.cloud.discoveryengine_v1.services.engine_service import pagers
-from google.cloud.discoveryengine_v1.types import common, engine, engine_service
+from google.cloud.discoveryengine_v1.types import (
+ agent_gateway_setting,
+ cmek_config_service,
+ common,
+ engine,
+ engine_service,
+ logging,
+)
from google.cloud.discoveryengine_v1.types import engine as gcd_engine
from .client import EngineServiceClient
@@ -84,8 +93,22 @@ class EngineServiceAsyncClient:
_DEFAULT_ENDPOINT_TEMPLATE = EngineServiceClient._DEFAULT_ENDPOINT_TEMPLATE
_DEFAULT_UNIVERSE = EngineServiceClient._DEFAULT_UNIVERSE
+ agent_gateway_path = staticmethod(EngineServiceClient.agent_gateway_path)
+ parse_agent_gateway_path = staticmethod(
+ EngineServiceClient.parse_agent_gateway_path
+ )
+ cmek_config_path = staticmethod(EngineServiceClient.cmek_config_path)
+ parse_cmek_config_path = staticmethod(EngineServiceClient.parse_cmek_config_path)
collection_path = staticmethod(EngineServiceClient.collection_path)
parse_collection_path = staticmethod(EngineServiceClient.parse_collection_path)
+ crypto_keys_path = staticmethod(EngineServiceClient.crypto_keys_path)
+ parse_crypto_keys_path = staticmethod(EngineServiceClient.parse_crypto_keys_path)
+ crypto_key_versions_path = staticmethod(
+ EngineServiceClient.crypto_key_versions_path
+ )
+ parse_crypto_key_versions_path = staticmethod(
+ EngineServiceClient.parse_crypto_key_versions_path
+ )
engine_path = staticmethod(EngineServiceClient.engine_path)
parse_engine_path = staticmethod(EngineServiceClient.parse_engine_path)
common_billing_account_path = staticmethod(
@@ -317,7 +340,7 @@ async def create_engine(
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> operation_async.AsyncOperation:
- r"""Creates a [Engine][google.cloud.discoveryengine.v1.Engine].
+ r"""Creates an [Engine][google.cloud.discoveryengine.v1.Engine].
.. code-block:: python
@@ -337,7 +360,7 @@ async def sample_create_engine():
# Initialize request argument(s)
engine = discoveryengine_v1.Engine()
engine.display_name = "display_name_value"
- engine.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ engine.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.CreateEngineRequest(
parent="parent_value",
@@ -476,7 +499,7 @@ async def delete_engine(
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> operation_async.AsyncOperation:
- r"""Deletes a [Engine][google.cloud.discoveryengine.v1.Engine].
+ r"""Deletes an [Engine][google.cloud.discoveryengine.v1.Engine].
.. code-block:: python
@@ -641,7 +664,7 @@ async def sample_update_engine():
# Initialize request argument(s)
engine = discoveryengine_v1.Engine()
engine.display_name = "display_name_value"
- engine.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ engine.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateEngineRequest(
engine=engine,
@@ -761,7 +784,7 @@ async def get_engine(
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> engine.Engine:
- r"""Gets a [Engine][google.cloud.discoveryengine.v1.Engine].
+ r"""Gets an [Engine][google.cloud.discoveryengine.v1.Engine].
.. code-block:: python
@@ -995,6 +1018,298 @@ async def sample_list_engines():
# Done; return the response.
return response
+ async def get_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Gets the IAM access control policy for an
+ [Engine][google.cloud.discoveryengine.v1.Engine]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ async def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.EngineServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]]):
+ The request object. Request message for ``GetIamPolicy`` method.
+ resource (:class:`str`):
+ REQUIRED: The resource for which the
+ policy is being requested. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ if isinstance(request, dict):
+ request = iam_policy_pb2.GetIamPolicyRequest(**request)
+ elif not request:
+ request = iam_policy_pb2.GetIamPolicyRequest(resource=resource)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.get_iam_policy
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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 set_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Sets the IAM access control policy for an
+ [Engine][google.cloud.discoveryengine.v1.Engine]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on an Engine
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``,
+ ``roles/discoveryengine.agentspaceAdmin``,
+ ``roles/discoveryengine.user``,
+ ``roles/discoveryengine.agentspaceUser``,
+ ``roles/discoveryengine.viewer``,
+ ``roles/discoveryengine.agentspaceViewer``. Attempting to grant
+ any other role will result in a warning in logging.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ async def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.EngineServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]]):
+ The request object. Request message for ``SetIamPolicy`` method.
+ resource (:class:`str`):
+ REQUIRED: The resource for which the
+ policy is being specified. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` 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.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ if isinstance(request, dict):
+ request = iam_policy_pb2.SetIamPolicyRequest(**request)
+ elif not request:
+ request = iam_policy_pb2.SetIamPolicyRequest(resource=resource)
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.set_iam_policy
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/client.py
index bd365c7907ec..0ac66f837674 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/client.py
@@ -70,6 +70,8 @@
import google.api_core.operation as operation # type: ignore
import google.api_core.operation_async as operation_async # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
@@ -77,7 +79,14 @@
from google.longrunning import operations_pb2 # type: ignore
from google.cloud.discoveryengine_v1.services.engine_service import pagers
-from google.cloud.discoveryengine_v1.types import common, engine, engine_service
+from google.cloud.discoveryengine_v1.types import (
+ agent_gateway_setting,
+ cmek_config_service,
+ common,
+ engine,
+ engine_service,
+ logging,
+)
from google.cloud.discoveryengine_v1.types import engine as gcd_engine
from .transports.base import DEFAULT_CLIENT_INFO, EngineServiceTransport
@@ -180,6 +189,47 @@ def transport(self) -> EngineServiceTransport:
"""
return self._transport
+ @staticmethod
+ def agent_gateway_path(
+ project: str,
+ location: str,
+ agent_gateway: str,
+ ) -> str:
+ """Returns a fully-qualified agent_gateway string."""
+ return "projects/{project}/locations/{location}/agentGateways/{agent_gateway}".format(
+ project=project,
+ location=location,
+ agent_gateway=agent_gateway,
+ )
+
+ @staticmethod
+ def parse_agent_gateway_path(path: str) -> Dict[str, str]:
+ """Parses a agent_gateway path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/agentGateways/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def cmek_config_path(
+ project: str,
+ location: str,
+ ) -> str:
+ """Returns a fully-qualified cmek_config string."""
+ return "projects/{project}/locations/{location}/cmekConfig".format(
+ project=project,
+ location=location,
+ )
+
+ @staticmethod
+ def parse_cmek_config_path(path: str) -> Dict[str, str]:
+ """Parses a cmek_config path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/cmekConfig$", path
+ )
+ return m.groupdict() if m else {}
+
@staticmethod
def collection_path(
project: str,
@@ -204,6 +254,56 @@ def parse_collection_path(path: str) -> Dict[str, str]:
)
return m.groupdict() if m else {}
+ @staticmethod
+ def crypto_keys_path(
+ project: str,
+ location: str,
+ key_ring: str,
+ crypto_key: str,
+ ) -> str:
+ """Returns a fully-qualified crypto_keys string."""
+ return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(
+ project=project,
+ location=location,
+ key_ring=key_ring,
+ crypto_key=crypto_key,
+ )
+
+ @staticmethod
+ def parse_crypto_keys_path(path: str) -> Dict[str, str]:
+ """Parses a crypto_keys path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def crypto_key_versions_path(
+ project: str,
+ location: str,
+ key_ring: str,
+ crypto_key: str,
+ crypto_key_version: str,
+ ) -> str:
+ """Returns a fully-qualified crypto_key_versions string."""
+ return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(
+ project=project,
+ location=location,
+ key_ring=key_ring,
+ crypto_key=crypto_key,
+ crypto_key_version=crypto_key_version,
+ )
+
+ @staticmethod
+ def parse_crypto_key_versions_path(path: str) -> Dict[str, str]:
+ """Parses a crypto_key_versions path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
@staticmethod
def engine_path(
project: str,
@@ -638,7 +738,7 @@ def create_engine(
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> operation.Operation:
- r"""Creates a [Engine][google.cloud.discoveryengine.v1.Engine].
+ r"""Creates an [Engine][google.cloud.discoveryengine.v1.Engine].
.. code-block:: python
@@ -658,7 +758,7 @@ def sample_create_engine():
# Initialize request argument(s)
engine = discoveryengine_v1.Engine()
engine.display_name = "display_name_value"
- engine.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ engine.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.CreateEngineRequest(
parent="parent_value",
@@ -794,7 +894,7 @@ def delete_engine(
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> operation.Operation:
- r"""Deletes a [Engine][google.cloud.discoveryengine.v1.Engine].
+ r"""Deletes an [Engine][google.cloud.discoveryengine.v1.Engine].
.. code-block:: python
@@ -956,7 +1056,7 @@ def sample_update_engine():
# Initialize request argument(s)
engine = discoveryengine_v1.Engine()
engine.display_name = "display_name_value"
- engine.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ engine.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateEngineRequest(
engine=engine,
@@ -1073,7 +1173,7 @@ def get_engine(
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> engine.Engine:
- r"""Gets a [Engine][google.cloud.discoveryengine.v1.Engine].
+ r"""Gets an [Engine][google.cloud.discoveryengine.v1.Engine].
.. code-block:: python
@@ -1301,6 +1401,300 @@ def sample_list_engines():
# Done; return the response.
return response
+ def get_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.GetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Gets the IAM access control policy for an
+ [Engine][google.cloud.discoveryengine.v1.Engine]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.EngineServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.iam.v1.iam_policy_pb2.GetIamPolicyRequest, dict]):
+ The request object. Request message for ``GetIamPolicy`` method.
+ resource (str):
+ REQUIRED: The resource for which the
+ policy is being requested. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each value must be of type `str`,
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
+ be of type `bytes`.
+
+ Returns:
+ google.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ if isinstance(request, dict):
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ request = iam_policy_pb2.GetIamPolicyRequest(**request)
+ elif not request:
+ # Null request, just make one.
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ if resource is not None:
+ request.resource = resource
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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 set_iam_policy(
+ self,
+ request: Optional[Union[iam_policy_pb2.SetIamPolicyRequest, dict]] = None,
+ *,
+ resource: Optional[str] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Sets the IAM access control policy for an
+ [Engine][google.cloud.discoveryengine.v1.Engine]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on an Engine
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``,
+ ``roles/discoveryengine.agentspaceAdmin``,
+ ``roles/discoveryengine.user``,
+ ``roles/discoveryengine.agentspaceUser``,
+ ``roles/discoveryengine.viewer``,
+ ``roles/discoveryengine.agentspaceViewer``. Attempting to grant
+ any other role will result in a warning in logging.
+
+ .. 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
+ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+ def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.EngineServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.iam.v1.iam_policy_pb2.SetIamPolicyRequest, dict]):
+ The request object. Request message for ``SetIamPolicy`` method.
+ resource (str):
+ REQUIRED: The resource for which the
+ policy is being specified. See the
+ operation documentation for the
+ appropriate value for this field.
+
+ This corresponds to the ``resource`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each value must be of type `str`,
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
+ be of type `bytes`.
+
+ Returns:
+ google.iam.v1.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which specifies access
+ controls for Google Cloud resources.
+
+ A Policy is a collection of bindings. A binding binds
+ one or more members, or principals, to a single role.
+ Principals can be user accounts, service accounts,
+ Google groups, and domains (such as G Suite). A role
+ is a named list of permissions; each role can be an
+ IAM predefined role or a user-created custom role.
+
+ For some types of Google Cloud resources, a binding
+ can also specify a condition, which is a logical
+ expression that allows access to a resource only if
+ the expression evaluates to true. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the [IAM
+ documentation](https://cloud.google.com/iam/help/conditions/resource-policies).
+
+ **JSON example:**
+
+ :literal:`` { "bindings": [ { "role": "roles/resourcemanager.organizationAdmin", "members": [ "user:mike@example.com", "group:admins@example.com", "domain:google.com", "serviceAccount:my-project-id@appspot.gserviceaccount.com" ] }, { "role": "roles/resourcemanager.organizationViewer", "members": [ "user:eve@example.com" ], "condition": { "title": "expirable access", "description": "Does not grant access after Sep 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", } } ], "etag": "BwWWja0YfJA=", "version": 3 }`\ \`
+
+ **YAML example:**
+
+ :literal:`` bindings: - members: - user:mike@example.com - group:admins@example.com - domain:google.com - serviceAccount:my-project-id@appspot.gserviceaccount.com role: roles/resourcemanager.organizationAdmin - members: - user:eve@example.com role: roles/resourcemanager.organizationViewer condition: title: expirable access description: Does not grant access after Sep 2020 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') etag: BwWWja0YfJA= version: 3`\ \`
+
+ For a description of IAM and its features, see the
+ [IAM
+ documentation](https://cloud.google.com/iam/docs/).
+
+ """
+ # 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 = [resource]
+ has_flattened_params = (
+ len([param for param in flattened_params if param is not None]) > 0
+ )
+ if request is not None and has_flattened_params:
+ raise ValueError(
+ "If the `request` argument is set, then none of "
+ "the individual field arguments should be set."
+ )
+
+ if isinstance(request, dict):
+ # - The request isn't a proto-plus wrapped type,
+ # so it must be constructed via keyword expansion.
+ request = iam_policy_pb2.SetIamPolicyRequest(**request)
+ elif not request:
+ # Null request, just make one.
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ if resource is not None:
+ request.resource = resource
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
+ )
+
+ # 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) -> "EngineServiceClient":
return self
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/base.py
index bd08952aa27e..1cc16de3bd1d 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/base.py
@@ -18,6 +18,8 @@
import google.api_core
import google.auth # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1, operations_v1
@@ -40,7 +42,11 @@
class EngineServiceTransport(abc.ABC):
"""Abstract transport class for EngineService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
@@ -168,6 +174,16 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
+ self.get_iam_policy: gapic_v1.method.wrap_method(
+ self.get_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.set_iam_policy: gapic_v1.method.wrap_method(
+ self.set_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.cancel_operation: gapic_v1.method.wrap_method(
self.cancel_operation,
default_timeout=None,
@@ -247,6 +263,24 @@ def list_engines(
]:
raise NotImplementedError()
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[
+ [iam_policy_pb2.GetIamPolicyRequest],
+ Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[
+ [iam_policy_pb2.SetIamPolicyRequest],
+ Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]],
+ ]:
+ raise NotImplementedError()
+
@property
def list_operations(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/grpc.py
index 24d4c1994ddb..e87ace8e8f8e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/grpc.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/grpc.py
@@ -20,6 +20,8 @@
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
import google.auth # type: ignore
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
@@ -352,7 +354,7 @@ def create_engine(
) -> Callable[[engine_service.CreateEngineRequest], operations_pb2.Operation]:
r"""Return a callable for the create engine method over gRPC.
- Creates a [Engine][google.cloud.discoveryengine.v1.Engine].
+ Creates an [Engine][google.cloud.discoveryengine.v1.Engine].
Returns:
Callable[[~.CreateEngineRequest],
@@ -378,7 +380,7 @@ def delete_engine(
) -> Callable[[engine_service.DeleteEngineRequest], operations_pb2.Operation]:
r"""Return a callable for the delete engine method over gRPC.
- Deletes a [Engine][google.cloud.discoveryengine.v1.Engine].
+ Deletes an [Engine][google.cloud.discoveryengine.v1.Engine].
Returns:
Callable[[~.DeleteEngineRequest],
@@ -428,7 +430,7 @@ def update_engine(
def get_engine(self) -> Callable[[engine_service.GetEngineRequest], engine.Engine]:
r"""Return a callable for the get engine method over gRPC.
- Gets a [Engine][google.cloud.discoveryengine.v1.Engine].
+ Gets an [Engine][google.cloud.discoveryengine.v1.Engine].
Returns:
Callable[[~.GetEngineRequest],
@@ -477,6 +479,74 @@ def list_engines(
)
return self._stubs["list_engines"]
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
+ r"""Return a callable for the get iam policy method over gRPC.
+
+ Gets the IAM access control policy for an
+ [Engine][google.cloud.discoveryengine.v1.Engine]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ Returns:
+ Callable[[~.GetIamPolicyRequest],
+ ~.Policy]:
+ 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_iam_policy" not in self._stubs:
+ self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.EngineService/GetIamPolicy",
+ request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["get_iam_policy"]
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
+ r"""Return a callable for the set iam policy method over gRPC.
+
+ Sets the IAM access control policy for an
+ [Engine][google.cloud.discoveryengine.v1.Engine]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on an Engine
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``,
+ ``roles/discoveryengine.agentspaceAdmin``,
+ ``roles/discoveryengine.user``,
+ ``roles/discoveryengine.agentspaceUser``,
+ ``roles/discoveryengine.viewer``,
+ ``roles/discoveryengine.agentspaceViewer``. Attempting to grant
+ any other role will result in a warning in logging.
+
+ Returns:
+ Callable[[~.SetIamPolicyRequest],
+ ~.Policy]:
+ 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 "set_iam_policy" not in self._stubs:
+ self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.EngineService/SetIamPolicy",
+ request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["set_iam_policy"]
+
def close(self):
self._logged_channel.close()
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/grpc_asyncio.py
index 45749d736454..f3e8c6e0611d 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/grpc_asyncio.py
@@ -20,6 +20,8 @@
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
@@ -362,7 +364,7 @@ def create_engine(
]:
r"""Return a callable for the create engine method over gRPC.
- Creates a [Engine][google.cloud.discoveryengine.v1.Engine].
+ Creates an [Engine][google.cloud.discoveryengine.v1.Engine].
Returns:
Callable[[~.CreateEngineRequest],
@@ -390,7 +392,7 @@ def delete_engine(
]:
r"""Return a callable for the delete engine method over gRPC.
- Deletes a [Engine][google.cloud.discoveryengine.v1.Engine].
+ Deletes an [Engine][google.cloud.discoveryengine.v1.Engine].
Returns:
Callable[[~.DeleteEngineRequest],
@@ -442,7 +444,7 @@ def get_engine(
) -> Callable[[engine_service.GetEngineRequest], Awaitable[engine.Engine]]:
r"""Return a callable for the get engine method over gRPC.
- Gets a [Engine][google.cloud.discoveryengine.v1.Engine].
+ Gets an [Engine][google.cloud.discoveryengine.v1.Engine].
Returns:
Callable[[~.GetEngineRequest],
@@ -492,6 +494,74 @@ def list_engines(
)
return self._stubs["list_engines"]
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
+ r"""Return a callable for the get iam policy method over gRPC.
+
+ Gets the IAM access control policy for an
+ [Engine][google.cloud.discoveryengine.v1.Engine]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+ An empty policy is returned if the resource exists but does not
+ have a policy set on it.
+
+ Returns:
+ Callable[[~.GetIamPolicyRequest],
+ Awaitable[~.Policy]]:
+ 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_iam_policy" not in self._stubs:
+ self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.EngineService/GetIamPolicy",
+ request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["get_iam_policy"]
+
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]:
+ r"""Return a callable for the set iam policy method over gRPC.
+
+ Sets the IAM access control policy for an
+ [Engine][google.cloud.discoveryengine.v1.Engine]. A
+ ``NOT_FOUND`` error is returned if the resource does not exist.
+
+ **Important:** When setting a policy directly on an Engine
+ resource, the only recommended roles in the bindings are:
+ ``roles/discoveryengine.admin``,
+ ``roles/discoveryengine.agentspaceAdmin``,
+ ``roles/discoveryengine.user``,
+ ``roles/discoveryengine.agentspaceUser``,
+ ``roles/discoveryengine.viewer``,
+ ``roles/discoveryengine.agentspaceViewer``. Attempting to grant
+ any other role will result in a warning in logging.
+
+ Returns:
+ Callable[[~.SetIamPolicyRequest],
+ Awaitable[~.Policy]]:
+ 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 "set_iam_policy" not in self._stubs:
+ self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.EngineService/SetIamPolicy",
+ request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
+ response_deserializer=policy_pb2.Policy.FromString,
+ )
+ return self._stubs["set_iam_policy"]
+
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
@@ -520,6 +590,16 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
+ self.get_iam_policy: self._wrap_method(
+ self.get_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.set_iam_policy: self._wrap_method(
+ self.set_iam_policy,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.cancel_operation: self._wrap_method(
self.cancel_operation,
default_timeout=None,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest.py
index 8951e74bce15..5aaf36ddf71a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest.py
@@ -19,6 +19,8 @@
import warnings
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1, operations_v1, rest_helpers, rest_streaming
@@ -99,6 +101,14 @@ def post_get_engine(self, response):
logging.log(f"Received response: {response}")
return response
+ def pre_get_iam_policy(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_get_iam_policy(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
def pre_list_engines(self, request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
@@ -107,6 +117,14 @@ def post_list_engines(self, response):
logging.log(f"Received response: {response}")
return response
+ def pre_set_iam_policy(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_set_iam_policy(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
def pre_update_engine(self, request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
@@ -261,6 +279,52 @@ def post_get_engine_with_metadata(
"""
return response, metadata
+ 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 EngineService server.
+ """
+ return request, metadata
+
+ def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
+ """Post-rpc interceptor for get_iam_policy
+
+ DEPRECATED. Please use the `post_get_iam_policy_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the EngineService server but before
+ it is returned to user code. This `post_get_iam_policy` interceptor runs
+ before the `post_get_iam_policy_with_metadata` interceptor.
+ """
+ return response
+
+ def post_get_iam_policy_with_metadata(
+ self,
+ response: policy_pb2.Policy,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for get_iam_policy
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the EngineService server but before it is returned to user code.
+
+ We recommend only using this `post_get_iam_policy_with_metadata`
+ interceptor in new development instead of the `post_get_iam_policy` interceptor.
+ When both interceptors are used, this `post_get_iam_policy_with_metadata` interceptor runs after the
+ `post_get_iam_policy` interceptor. The (possibly modified) response returned by
+ `post_get_iam_policy` will be passed to
+ `post_get_iam_policy_with_metadata`.
+ """
+ return response, metadata
+
def pre_list_engines(
self,
request: engine_service.ListEnginesRequest,
@@ -311,6 +375,52 @@ def post_list_engines_with_metadata(
"""
return response, metadata
+ 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 EngineService server.
+ """
+ return request, metadata
+
+ def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy:
+ """Post-rpc interceptor for set_iam_policy
+
+ DEPRECATED. Please use the `post_set_iam_policy_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the EngineService server but before
+ it is returned to user code. This `post_set_iam_policy` interceptor runs
+ before the `post_set_iam_policy_with_metadata` interceptor.
+ """
+ return response
+
+ def post_set_iam_policy_with_metadata(
+ self,
+ response: policy_pb2.Policy,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[policy_pb2.Policy, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """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 EngineService server but before it is returned to user code.
+
+ We recommend only using this `post_set_iam_policy_with_metadata`
+ interceptor in new development instead of the `post_set_iam_policy` interceptor.
+ When both interceptors are used, this `post_set_iam_policy_with_metadata` interceptor runs after the
+ `post_set_iam_policy` interceptor. The (possibly modified) response returned by
+ `post_set_iam_policy` will be passed to
+ `post_set_iam_policy_with_metadata`.
+ """
+ return response, metadata
+
def pre_update_engine(
self,
request: engine_service.UpdateEngineRequest,
@@ -591,6 +701,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
@@ -1156,6 +1270,226 @@ def __call__(
)
return resp
+ class _GetIamPolicy(
+ _BaseEngineServiceRestTransport._BaseGetIamPolicy, EngineServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("EngineServiceRestTransport.GetIamPolicy")
+
+ @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: iam_policy_pb2.GetIamPolicyRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Call the get iam policy method over HTTP.
+
+ Args:
+ request (~.iam_policy_pb2.GetIamPolicyRequest):
+ The request object. Request message for ``GetIamPolicy`` 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:
+ ~.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which
+ specifies access controls for Google Cloud resources.
+
+ A ``Policy`` is a collection of ``bindings``. A
+ ``binding`` binds one or more ``members``, or
+ principals, to a single ``role``. Principals can be user
+ accounts, service accounts, Google groups, and domains
+ (such as G Suite). A ``role`` is a named list of
+ permissions; each ``role`` can be an IAM predefined role
+ or a user-created custom role.
+
+ For some types of Google Cloud resources, a ``binding``
+ can also specify a ``condition``, which is a logical
+ expression that allows access to a resource only if the
+ expression evaluates to ``true``. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the `IAM
+ documentation `__.
+
+ **JSON example:**
+
+ ::
+
+ {
+ "bindings": [
+ {
+ "role": "roles/resourcemanager.organizationAdmin",
+ "members": [
+ "user:mike@example.com",
+ "group:admins@example.com",
+ "domain:google.com",
+ "serviceAccount:my-project-id@appspot.gserviceaccount.com"
+ ]
+ },
+ {
+ "role": "roles/resourcemanager.organizationViewer",
+ "members": [
+ "user:eve@example.com"
+ ],
+ "condition": {
+ "title": "expirable access",
+ "description": "Does not grant access after Sep 2020",
+ "expression": "request.time <
+ timestamp('2020-10-01T00:00:00.000Z')",
+ }
+ }
+ ],
+ "etag": "BwWWja0YfJA=",
+ "version": 3
+ }
+
+ **YAML example:**
+
+ ::
+
+ bindings:
+ - members:
+ - user:mike@example.com
+ - group:admins@example.com
+ - domain:google.com
+ - serviceAccount:my-project-id@appspot.gserviceaccount.com
+ role: roles/resourcemanager.organizationAdmin
+ - members:
+ - user:eve@example.com
+ role: roles/resourcemanager.organizationViewer
+ condition:
+ title: expirable access
+ description: Does not grant access after Sep 2020
+ expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
+ etag: BwWWja0YfJA=
+ version: 3
+
+ For a description of IAM and its features, see the `IAM
+ documentation `__.
+
+ """
+
+ http_options = (
+ _BaseEngineServiceRestTransport._BaseGetIamPolicy._get_http_options()
+ )
+ request, metadata = self._interceptor.pre_get_iam_policy(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseEngineServiceRestTransport._BaseGetIamPolicy,
+ "_BaseGetIamPolicy__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 = 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.EngineServiceClient.GetIamPolicy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.EngineService",
+ "rpcName": "GetIamPolicy",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = EngineServiceRestTransport._GetIamPolicy._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 = policy_pb2.Policy()
+ pb_resp = resp
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_get_iam_policy(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_get_iam_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.discoveryengine_v1.EngineServiceClient.get_iam_policy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.EngineService",
+ "rpcName": "GetIamPolicy",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
class _ListEngines(
_BaseEngineServiceRestTransport._BaseListEngines, EngineServiceRestStub
):
@@ -1308,6 +1642,228 @@ def __call__(
)
return resp
+ class _SetIamPolicy(
+ _BaseEngineServiceRestTransport._BaseSetIamPolicy, EngineServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("EngineServiceRestTransport.SetIamPolicy")
+
+ @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: iam_policy_pb2.SetIamPolicyRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> policy_pb2.Policy:
+ r"""Call the set iam policy method over HTTP.
+
+ Args:
+ request (~.iam_policy_pb2.SetIamPolicyRequest):
+ The request object. Request message for ``SetIamPolicy`` 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:
+ ~.policy_pb2.Policy:
+ An Identity and Access Management (IAM) policy, which
+ specifies access controls for Google Cloud resources.
+
+ A ``Policy`` is a collection of ``bindings``. A
+ ``binding`` binds one or more ``members``, or
+ principals, to a single ``role``. Principals can be user
+ accounts, service accounts, Google groups, and domains
+ (such as G Suite). A ``role`` is a named list of
+ permissions; each ``role`` can be an IAM predefined role
+ or a user-created custom role.
+
+ For some types of Google Cloud resources, a ``binding``
+ can also specify a ``condition``, which is a logical
+ expression that allows access to a resource only if the
+ expression evaluates to ``true``. A condition can add
+ constraints based on attributes of the request, the
+ resource, or both. To learn which resources support
+ conditions in their IAM policies, see the `IAM
+ documentation `__.
+
+ **JSON example:**
+
+ ::
+
+ {
+ "bindings": [
+ {
+ "role": "roles/resourcemanager.organizationAdmin",
+ "members": [
+ "user:mike@example.com",
+ "group:admins@example.com",
+ "domain:google.com",
+ "serviceAccount:my-project-id@appspot.gserviceaccount.com"
+ ]
+ },
+ {
+ "role": "roles/resourcemanager.organizationViewer",
+ "members": [
+ "user:eve@example.com"
+ ],
+ "condition": {
+ "title": "expirable access",
+ "description": "Does not grant access after Sep 2020",
+ "expression": "request.time <
+ timestamp('2020-10-01T00:00:00.000Z')",
+ }
+ }
+ ],
+ "etag": "BwWWja0YfJA=",
+ "version": 3
+ }
+
+ **YAML example:**
+
+ ::
+
+ bindings:
+ - members:
+ - user:mike@example.com
+ - group:admins@example.com
+ - domain:google.com
+ - serviceAccount:my-project-id@appspot.gserviceaccount.com
+ role: roles/resourcemanager.organizationAdmin
+ - members:
+ - user:eve@example.com
+ role: roles/resourcemanager.organizationViewer
+ condition:
+ title: expirable access
+ description: Does not grant access after Sep 2020
+ expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
+ etag: BwWWja0YfJA=
+ version: 3
+
+ For a description of IAM and its features, see the `IAM
+ documentation `__.
+
+ """
+
+ http_options = (
+ _BaseEngineServiceRestTransport._BaseSetIamPolicy._get_http_options()
+ )
+ request, metadata = self._interceptor.pre_set_iam_policy(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseEngineServiceRestTransport._BaseSetIamPolicy,
+ "_BaseSetIamPolicy__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 = 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.EngineServiceClient.SetIamPolicy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.EngineService",
+ "rpcName": "SetIamPolicy",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = EngineServiceRestTransport._SetIamPolicy._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 = policy_pb2.Policy()
+ pb_resp = resp
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_set_iam_policy(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_set_iam_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.discoveryengine_v1.EngineServiceClient.set_iam_policy",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.EngineService",
+ "rpcName": "SetIamPolicy",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
class _UpdateEngine(
_BaseEngineServiceRestTransport._BaseUpdateEngine, EngineServiceRestStub
):
@@ -1482,6 +2038,14 @@ def get_engine(self) -> Callable[[engine_service.GetEngineRequest], engine.Engin
# In C++ this would require a dynamic_cast
return self._GetEngine(self._session, self._host, self._interceptor) # type: ignore
+ @property
+ def get_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
+ # 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._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
+
@property
def list_engines(
self,
@@ -1492,6 +2056,14 @@ def list_engines(
# In C++ this would require a dynamic_cast
return self._ListEngines(self._session, self._host, self._interceptor) # type: ignore
+ @property
+ def set_iam_policy(
+ self,
+ ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
+ # 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._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore
+
@property
def update_engine(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest_base.py
index 405b75f9d122..dafee1e8543f 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/engine_service/transports/rest_base.py
@@ -17,6 +17,8 @@
import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
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
@@ -141,6 +143,22 @@ def _get_http_options():
]
return http_options
+ class _BaseGetIamPolicy:
+ 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/{resource=projects/*/locations/*/collections/*/engines/*}:getIamPolicy",
+ },
+ ]
+ return http_options
+
class _BaseListEngines:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@@ -157,6 +175,23 @@ def _get_http_options():
]
return http_options
+ class _BaseSetIamPolicy:
+ 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/{resource=projects/*/locations/*/collections/*/engines/*}:setIamPolicy",
+ "body": "*",
+ },
+ ]
+ return http_options
+
class _BaseUpdateEngine:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@@ -243,6 +278,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/base.py
index be1de7b004b2..e446244279b8 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/base.py
@@ -39,7 +39,11 @@
class GroundedGenerationServiceTransport(abc.ABC):
"""Abstract transport class for GroundedGenerationService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/rest_base.py
index 8a3470b4ff43..b288c0a43ed0 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/grounded_generation_service/transports/rest_base.py
@@ -196,6 +196,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/base.py
index db3d0f289a52..b4333a0e7ba3 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/base.py
@@ -45,7 +45,11 @@
class IdentityMappingStoreServiceTransport(abc.ABC):
"""Abstract transport class for IdentityMappingStoreService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/rest.py
index 3a43966bd331..fb091ef0f94f 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/rest.py
@@ -732,6 +732,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/rest_base.py
index 191cbb987e8d..84f2aef2594e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/identity_mapping_store_service/transports/rest_base.py
@@ -283,6 +283,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/__init__.py
new file mode 100644
index 000000000000..9ba338d13e9d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_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 LicenseConfigServiceAsyncClient
+from .client import LicenseConfigServiceClient
+
+__all__ = (
+ "LicenseConfigServiceClient",
+ "LicenseConfigServiceAsyncClient",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/async_client.py
new file mode 100644
index 000000000000..171ec55cb6b7
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/async_client.py
@@ -0,0 +1,1402 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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
+
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
+import google.type.date_pb2 as date_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.services.license_config_service import pagers
+from google.cloud.discoveryengine_v1.types import (
+ common,
+ license_config,
+ license_config_service,
+)
+from google.cloud.discoveryengine_v1.types import license_config as gcd_license_config
+
+from .client import LicenseConfigServiceClient
+from .transports.base import DEFAULT_CLIENT_INFO, LicenseConfigServiceTransport
+from .transports.grpc_asyncio import LicenseConfigServiceGrpcAsyncIOTransport
+
+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 LicenseConfigServiceAsyncClient:
+ """Service for managing license config related resources."""
+
+ _client: LicenseConfigServiceClient
+
+ # Copy defaults from the synchronous client for use here.
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
+ DEFAULT_ENDPOINT = LicenseConfigServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = LicenseConfigServiceClient.DEFAULT_MTLS_ENDPOINT
+ _DEFAULT_ENDPOINT_TEMPLATE = LicenseConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE
+ _DEFAULT_UNIVERSE = LicenseConfigServiceClient._DEFAULT_UNIVERSE
+
+ billing_account_license_config_path = staticmethod(
+ LicenseConfigServiceClient.billing_account_license_config_path
+ )
+ parse_billing_account_license_config_path = staticmethod(
+ LicenseConfigServiceClient.parse_billing_account_license_config_path
+ )
+ license_config_path = staticmethod(LicenseConfigServiceClient.license_config_path)
+ parse_license_config_path = staticmethod(
+ LicenseConfigServiceClient.parse_license_config_path
+ )
+ location_path = staticmethod(LicenseConfigServiceClient.location_path)
+ parse_location_path = staticmethod(LicenseConfigServiceClient.parse_location_path)
+ common_billing_account_path = staticmethod(
+ LicenseConfigServiceClient.common_billing_account_path
+ )
+ parse_common_billing_account_path = staticmethod(
+ LicenseConfigServiceClient.parse_common_billing_account_path
+ )
+ common_folder_path = staticmethod(LicenseConfigServiceClient.common_folder_path)
+ parse_common_folder_path = staticmethod(
+ LicenseConfigServiceClient.parse_common_folder_path
+ )
+ common_organization_path = staticmethod(
+ LicenseConfigServiceClient.common_organization_path
+ )
+ parse_common_organization_path = staticmethod(
+ LicenseConfigServiceClient.parse_common_organization_path
+ )
+ common_project_path = staticmethod(LicenseConfigServiceClient.common_project_path)
+ parse_common_project_path = staticmethod(
+ LicenseConfigServiceClient.parse_common_project_path
+ )
+ common_location_path = staticmethod(LicenseConfigServiceClient.common_location_path)
+ parse_common_location_path = staticmethod(
+ LicenseConfigServiceClient.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:
+ LicenseConfigServiceAsyncClient: The constructed client.
+ """
+ sa_info_func = (
+ LicenseConfigServiceClient.from_service_account_info.__func__ # type: ignore
+ )
+ return sa_info_func(LicenseConfigServiceAsyncClient, 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:
+ LicenseConfigServiceAsyncClient: The constructed client.
+ """
+ sa_file_func = (
+ LicenseConfigServiceClient.from_service_account_file.__func__ # type: ignore
+ )
+ return sa_file_func(LicenseConfigServiceAsyncClient, 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 LicenseConfigServiceClient.get_mtls_endpoint_and_cert_source(
+ client_options
+ ) # type: ignore
+
+ @property
+ def transport(self) -> LicenseConfigServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ LicenseConfigServiceTransport: 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 = LicenseConfigServiceClient.get_transport_class
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[ga_credentials.Credentials] = None,
+ transport: Optional[
+ Union[
+ str,
+ LicenseConfigServiceTransport,
+ Callable[..., LicenseConfigServiceTransport],
+ ]
+ ] = "grpc_asyncio",
+ client_options: Optional[ClientOptions] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the license 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,LicenseConfigServiceTransport,Callable[..., LicenseConfigServiceTransport]]]):
+ 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 LicenseConfigServiceTransport 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 = LicenseConfigServiceClient(
+ 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.LicenseConfigServiceAsyncClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "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.LicenseConfigService",
+ "credentialsType": None,
+ },
+ )
+
+ async def create_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.CreateLicenseConfigRequest, dict]
+ ] = None,
+ *,
+ parent: Optional[str] = None,
+ license_config: Optional[gcd_license_config.LicenseConfig] = None,
+ license_config_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]]] = (),
+ ) -> gcd_license_config.LicenseConfig:
+ r"""Creates a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ This method should only be used for creating NotebookLm licenses
+ or Gemini Enterprise free trial licenses.
+
+ .. 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_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ license_config = discoveryengine_v1.LicenseConfig()
+ license_config.license_count = 1387
+ license_config.subscription_tier = "SUBSCRIPTION_TIER_EDU_GOV_EMERGING"
+ license_config.subscription_term = "SUBSCRIPTION_TERM_CUSTOM"
+
+ request = discoveryengine_v1.CreateLicenseConfigRequest(
+ parent="parent_value",
+ license_config=license_config,
+ )
+
+ # Make the request
+ response = await client.create_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.CreateLicenseConfigRequest, dict]]):
+ The request object. Request message for
+ [LicenseConfigService.CreateLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.CreateLicenseConfig]
+ method.
+ parent (:class:`str`):
+ Required. The parent resource name, such as
+ ``projects/{project}/locations/{location}``.
+
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_config (:class:`google.cloud.discoveryengine_v1.types.LicenseConfig`):
+ Required. The
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ to create.
+
+ This corresponds to the ``license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_config_id (:class:`str`):
+ Optional. The ID to use for the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig],
+ which will become the final component of the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]'s
+ resource name. We are using the tier (product edition)
+ name as the license config id such as ``search`` or
+ ``search_and_assistant``.
+
+ This corresponds to the ``license_config_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.discoveryengine_v1.types.LicenseConfig:
+ Information about users' licenses.
+ """
+ # 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, license_config, license_config_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, license_config_service.CreateLicenseConfigRequest):
+ request = license_config_service.CreateLicenseConfigRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if parent is not None:
+ request.parent = parent
+ if license_config is not None:
+ request.license_config = license_config
+ if license_config_id is not None:
+ request.license_config_id = license_config_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_license_config
+ ]
+
+ # 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 update_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.UpdateLicenseConfigRequest, dict]
+ ] = None,
+ *,
+ license_config: Optional[gcd_license_config.LicenseConfig] = 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_license_config.LicenseConfig:
+ r"""Updates the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+
+ .. 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_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ license_config = discoveryengine_v1.LicenseConfig()
+ license_config.license_count = 1387
+ license_config.subscription_tier = "SUBSCRIPTION_TIER_EDU_GOV_EMERGING"
+ license_config.subscription_term = "SUBSCRIPTION_TERM_CUSTOM"
+
+ request = discoveryengine_v1.UpdateLicenseConfigRequest(
+ license_config=license_config,
+ )
+
+ # Make the request
+ response = await client.update_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateLicenseConfigRequest, dict]]):
+ The request object. Request message for
+ [LicenseConfigService.UpdateLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.UpdateLicenseConfig]
+ method.
+ license_config (:class:`google.cloud.discoveryengine_v1.types.LicenseConfig`):
+ Required. The
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ to update.
+
+ This corresponds to the ``license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
+ Optional. Indicates which fields in the provided
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ to update.
+
+ If an unsupported or unknown field is provided, an
+ INVALID_ARGUMENT error is returned.
+
+ 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.LicenseConfig:
+ Information about users' licenses.
+ """
+ # 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 = [license_config, 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, license_config_service.UpdateLicenseConfigRequest):
+ request = license_config_service.UpdateLicenseConfigRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if license_config is not None:
+ request.license_config = license_config
+ 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_license_config
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("license_config.name", request.license_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_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.GetLicenseConfigRequest, 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]]] = (),
+ ) -> license_config.LicenseConfig:
+ r"""Gets a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig].
+
+ .. 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_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetLicenseConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.GetLicenseConfigRequest, dict]]):
+ The request object. Request message for
+ [LicenseConfigService.GetLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.GetLicenseConfig]
+ method.
+ name (:class:`str`):
+ Required. Full resource name of
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig],
+ such as
+ ``projects/{project}/locations/{location}/licenseConfigs/*``.
+
+ If the caller does not have permission to access the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig],
+ regardless of whether or not it exists, a
+ PERMISSION_DENIED error is returned.
+
+ If the requested
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ 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`.
+
+ Returns:
+ google.cloud.discoveryengine_v1.types.LicenseConfig:
+ Information about users' licenses.
+ """
+ # 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, license_config_service.GetLicenseConfigRequest):
+ request = license_config_service.GetLicenseConfigRequest(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_license_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_license_configs(
+ self,
+ request: Optional[
+ Union[license_config_service.ListLicenseConfigsRequest, 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.ListLicenseConfigsAsyncPager:
+ r"""Lists all the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]s
+ associated with the project.
+
+ .. code-block:: python
+
+ # This snippet has been automatically generated and should be regarded as a
+ # code template only.
+ # It will require modifications to work:
+ # - It may require correct/in-range values for request initialization.
+ # - It may require specifying regional endpoints when creating the service
+ # client as shown in:
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
+ from google.cloud import discoveryengine_v1
+
+ async def sample_list_license_configs():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListLicenseConfigsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_license_configs(request=request)
+
+ # Handle the response
+ async for response in page_result:
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.ListLicenseConfigsRequest, dict]]):
+ The request object. Request message for
+ [LicenseConfigService.ListLicenseConfigs][google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs]
+ method.
+ parent (:class:`str`):
+ Required. The parent branch resource name, such as
+ ``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.discoveryengine_v1.services.license_config_service.pagers.ListLicenseConfigsAsyncPager:
+ Response message for
+ [LicenseConfigService.ListLicenseConfigs][google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs]
+ 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, license_config_service.ListLicenseConfigsRequest):
+ request = license_config_service.ListLicenseConfigsRequest(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_license_configs
+ ]
+
+ # 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.ListLicenseConfigsAsyncPager(
+ method=rpc,
+ request=request,
+ response=response,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ async def distribute_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.DistributeLicenseConfigRequest, dict]
+ ] = None,
+ *,
+ billing_account_license_config: Optional[str] = None,
+ project_number: Optional[int] = None,
+ location: Optional[str] = None,
+ license_count: Optional[int] = None,
+ license_config_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]]] = (),
+ ) -> license_config_service.DistributeLicenseConfigResponse:
+ r"""Distributes a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ from billing account level to project level.
+
+ .. 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_distribute_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DistributeLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ )
+
+ # Make the request
+ response = await client.distribute_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.DistributeLicenseConfigRequest, dict]]):
+ The request object. Request message for
+ [LicenseConfigService.DistributeLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig]
+ method.
+ billing_account_license_config (:class:`str`):
+ Required. Full resource name of
+ [BillingAccountLicenseConfig][].
+
+ Format:
+ ``billingAccounts/{billing_account}/billingAccountLicenseConfigs/{billing_account_license_config_id}``.
+
+ This corresponds to the ``billing_account_license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ project_number (:class:`int`):
+ Required. The target GCP project
+ number to distribute the license config
+ to.
+
+ This corresponds to the ``project_number`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ location (:class:`str`):
+ Required. The target GCP project
+ region to distribute the license config
+ to.
+
+ This corresponds to the ``location`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_count (:class:`int`):
+ Required. The number of licenses to
+ distribute.
+
+ This corresponds to the ``license_count`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_config_id (:class:`str`):
+ Optional. Distribute seats to this
+ license config instead of creating a new
+ one. If not specified, a new license
+ config will be created from the billing
+ account license config.
+
+ This corresponds to the ``license_config_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.discoveryengine_v1.types.DistributeLicenseConfigResponse:
+ Response message for
+ [LicenseConfigService.DistributeLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig]
+ method.
+
+ """
+ # 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 = [
+ billing_account_license_config,
+ project_number,
+ location,
+ license_count,
+ license_config_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, license_config_service.DistributeLicenseConfigRequest
+ ):
+ request = license_config_service.DistributeLicenseConfigRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if billing_account_license_config is not None:
+ request.billing_account_license_config = billing_account_license_config
+ if project_number is not None:
+ request.project_number = project_number
+ if location is not None:
+ request.location = location
+ if license_count is not None:
+ request.license_count = license_count
+ if license_config_id is not None:
+ request.license_config_id = license_config_id
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.distribute_license_config
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (
+ (
+ "billing_account_license_config",
+ request.billing_account_license_config,
+ ),
+ )
+ ),
+ )
+
+ # 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 retract_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.RetractLicenseConfigRequest, dict]
+ ] = None,
+ *,
+ billing_account_license_config: Optional[str] = None,
+ license_config: Optional[str] = None,
+ full_retract: Optional[bool] = None,
+ license_count: Optional[int] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> license_config_service.RetractLicenseConfigResponse:
+ r"""This method is called from the billing account side to retract
+ the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ from the given project back to the billing account.
+
+ .. 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_retract_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.RetractLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ )
+
+ # Make the request
+ response = await client.retract_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.RetractLicenseConfigRequest, dict]]):
+ The request object. Request message for
+ [LicenseConfigService.RetractLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig]
+ method.
+ billing_account_license_config (:class:`str`):
+ Required. Full resource name of
+ [BillingAccountLicenseConfig][].
+
+ Format:
+ ``billingAccounts/{billing_account}/billingAccountLicenseConfigs/{billing_account_license_config_id}``.
+
+ This corresponds to the ``billing_account_license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_config (:class:`str`):
+ Required. Full resource name of
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig].
+
+ Format:
+ ``projects/{project}/locations/{location}/licenseConfigs/{license_config_id}``.
+
+ This corresponds to the ``license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ full_retract (:class:`bool`):
+ Optional. If set to true, retract the
+ entire license config. Otherwise,
+ retract the specified license count.
+
+ This corresponds to the ``full_retract`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_count (:class:`int`):
+ Optional. The number of licenses to retract. Only used
+ when full_retract is false.
+
+ This corresponds to the ``license_count`` 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.RetractLicenseConfigResponse:
+ Response message for
+ [LicenseConfigService.RetractLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig]
+ method.
+
+ """
+ # 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 = [
+ billing_account_license_config,
+ license_config,
+ full_retract,
+ license_count,
+ ]
+ 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, license_config_service.RetractLicenseConfigRequest):
+ request = license_config_service.RetractLicenseConfigRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if billing_account_license_config is not None:
+ request.billing_account_license_config = billing_account_license_config
+ if license_config is not None:
+ request.license_config = license_config
+ if full_retract is not None:
+ request.full_retract = full_retract
+ if license_count is not None:
+ request.license_count = license_count
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._client._transport._wrapped_methods[
+ self._client._transport.retract_license_config
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (
+ (
+ "billing_account_license_config",
+ request.billing_account_license_config,
+ ),
+ )
+ ),
+ )
+
+ # 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) -> "LicenseConfigServiceAsyncClient":
+ 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__ = ("LicenseConfigServiceAsyncClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/client.py
new file mode 100644
index 000000000000..712ba4e78ae6
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/client.py
@@ -0,0 +1,1723 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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__)
+
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
+import google.type.date_pb2 as date_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.services.license_config_service import pagers
+from google.cloud.discoveryengine_v1.types import (
+ common,
+ license_config,
+ license_config_service,
+)
+from google.cloud.discoveryengine_v1.types import license_config as gcd_license_config
+
+from .transports.base import DEFAULT_CLIENT_INFO, LicenseConfigServiceTransport
+from .transports.grpc import LicenseConfigServiceGrpcTransport
+from .transports.grpc_asyncio import LicenseConfigServiceGrpcAsyncIOTransport
+from .transports.rest import LicenseConfigServiceRestTransport
+
+
+class LicenseConfigServiceClientMeta(type):
+ """Metaclass for the LicenseConfigService 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[LicenseConfigServiceTransport]]
+ _transport_registry["grpc"] = LicenseConfigServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = LicenseConfigServiceGrpcAsyncIOTransport
+ _transport_registry["rest"] = LicenseConfigServiceRestTransport
+
+ def get_transport_class(
+ cls,
+ label: Optional[str] = None,
+ ) -> Type[LicenseConfigServiceTransport]:
+ """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 LicenseConfigServiceClient(metaclass=LicenseConfigServiceClientMeta):
+ """Service for managing license config related resources."""
+
+ # 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:
+ LicenseConfigServiceClient: 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:
+ LicenseConfigServiceClient: 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) -> LicenseConfigServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ LicenseConfigServiceTransport: The transport used by the client
+ instance.
+ """
+ return self._transport
+
+ @staticmethod
+ def billing_account_license_config_path(
+ billing_account: str,
+ billing_account_license_config: str,
+ ) -> str:
+ """Returns a fully-qualified billing_account_license_config string."""
+ return "billingAccounts/{billing_account}/billingAccountLicenseConfigs/{billing_account_license_config}".format(
+ billing_account=billing_account,
+ billing_account_license_config=billing_account_license_config,
+ )
+
+ @staticmethod
+ def parse_billing_account_license_config_path(path: str) -> Dict[str, str]:
+ """Parses a billing_account_license_config path into its component segments."""
+ m = re.match(
+ r"^billingAccounts/(?P.+?)/billingAccountLicenseConfigs/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def license_config_path(
+ project: str,
+ location: str,
+ license_config: str,
+ ) -> str:
+ """Returns a fully-qualified license_config string."""
+ return "projects/{project}/locations/{location}/licenseConfigs/{license_config}".format(
+ project=project,
+ location=location,
+ license_config=license_config,
+ )
+
+ @staticmethod
+ def parse_license_config_path(path: str) -> Dict[str, str]:
+ """Parses a license_config path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/licenseConfigs/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def 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_location_path(path: str) -> Dict[str, str]:
+ """Parses a location path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_billing_account_path(
+ billing_account: str,
+ ) -> str:
+ """Returns a fully-qualified billing_account string."""
+ return "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+
+ @staticmethod
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
+ """Parse a billing_account path into its component segments."""
+ m = re.match(r"^billingAccounts/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_folder_path(
+ folder: str,
+ ) -> str:
+ """Returns a fully-qualified folder string."""
+ return "folders/{folder}".format(
+ folder=folder,
+ )
+
+ @staticmethod
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
+ """Parse a folder path into its component segments."""
+ m = re.match(r"^folders/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_organization_path(
+ organization: str,
+ ) -> str:
+ """Returns a fully-qualified organization string."""
+ return "organizations/{organization}".format(
+ organization=organization,
+ )
+
+ @staticmethod
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
+ """Parse a organization path into its component segments."""
+ m = re.match(r"^organizations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_project_path(
+ project: str,
+ ) -> str:
+ """Returns a fully-qualified project string."""
+ return "projects/{project}".format(
+ project=project,
+ )
+
+ @staticmethod
+ def parse_common_project_path(path: str) -> Dict[str, str]:
+ """Parse a project path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_location_path(
+ project: str,
+ location: str,
+ ) -> str:
+ """Returns a fully-qualified location string."""
+ return "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+
+ @staticmethod
+ def parse_common_location_path(path: str) -> Dict[str, str]:
+ """Parse a location path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @classmethod
+ def get_mtls_endpoint_and_cert_source(
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
+ ):
+ """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,
+ LicenseConfigServiceTransport,
+ Callable[..., LicenseConfigServiceTransport],
+ ]
+ ] = None,
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the license 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,LicenseConfigServiceTransport,Callable[..., LicenseConfigServiceTransport]]]):
+ 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 LicenseConfigServiceTransport 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 = LicenseConfigServiceClient._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=LicenseConfigServiceClient._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, LicenseConfigServiceTransport)
+ if transport_provided:
+ # transport is a LicenseConfigServiceTransport 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(LicenseConfigServiceTransport, 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=LicenseConfigServiceClient._DEFAULT_UNIVERSE,
+ default_mtls_endpoint=LicenseConfigServiceClient.DEFAULT_MTLS_ENDPOINT,
+ default_endpoint_template=LicenseConfigServiceClient._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[LicenseConfigServiceTransport],
+ Callable[..., LicenseConfigServiceTransport],
+ ] = (
+ LicenseConfigServiceClient.get_transport_class(transport)
+ if isinstance(transport, str) or transport is None
+ else cast(Callable[..., LicenseConfigServiceTransport], 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.LicenseConfigServiceClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "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.LicenseConfigService",
+ "credentialsType": None,
+ },
+ )
+
+ def create_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.CreateLicenseConfigRequest, dict]
+ ] = None,
+ *,
+ parent: Optional[str] = None,
+ license_config: Optional[gcd_license_config.LicenseConfig] = None,
+ license_config_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]]] = (),
+ ) -> gcd_license_config.LicenseConfig:
+ r"""Creates a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ This method should only be used for creating NotebookLm licenses
+ or Gemini Enterprise free trial licenses.
+
+ .. 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_create_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ license_config = discoveryengine_v1.LicenseConfig()
+ license_config.license_count = 1387
+ license_config.subscription_tier = "SUBSCRIPTION_TIER_EDU_GOV_EMERGING"
+ license_config.subscription_term = "SUBSCRIPTION_TERM_CUSTOM"
+
+ request = discoveryengine_v1.CreateLicenseConfigRequest(
+ parent="parent_value",
+ license_config=license_config,
+ )
+
+ # Make the request
+ response = client.create_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.CreateLicenseConfigRequest, dict]):
+ The request object. Request message for
+ [LicenseConfigService.CreateLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.CreateLicenseConfig]
+ method.
+ parent (str):
+ Required. The parent resource name, such as
+ ``projects/{project}/locations/{location}``.
+
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_config (google.cloud.discoveryengine_v1.types.LicenseConfig):
+ Required. The
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ to create.
+
+ This corresponds to the ``license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_config_id (str):
+ Optional. The ID to use for the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig],
+ which will become the final component of the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]'s
+ resource name. We are using the tier (product edition)
+ name as the license config id such as ``search`` or
+ ``search_and_assistant``.
+
+ This corresponds to the ``license_config_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.discoveryengine_v1.types.LicenseConfig:
+ Information about users' licenses.
+ """
+ # 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, license_config, license_config_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, license_config_service.CreateLicenseConfigRequest):
+ request = license_config_service.CreateLicenseConfigRequest(request)
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if parent is not None:
+ request.parent = parent
+ if license_config is not None:
+ request.license_config = license_config
+ if license_config_id is not None:
+ request.license_config_id = license_config_id
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.create_license_config]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Validate the universe domain.
+ self._validate_universe_domain()
+
+ # Send the request.
+ response = rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ def update_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.UpdateLicenseConfigRequest, dict]
+ ] = None,
+ *,
+ license_config: Optional[gcd_license_config.LicenseConfig] = 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_license_config.LicenseConfig:
+ r"""Updates the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+
+ .. 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_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ license_config = discoveryengine_v1.LicenseConfig()
+ license_config.license_count = 1387
+ license_config.subscription_tier = "SUBSCRIPTION_TIER_EDU_GOV_EMERGING"
+ license_config.subscription_term = "SUBSCRIPTION_TERM_CUSTOM"
+
+ request = discoveryengine_v1.UpdateLicenseConfigRequest(
+ license_config=license_config,
+ )
+
+ # Make the request
+ response = client.update_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.UpdateLicenseConfigRequest, dict]):
+ The request object. Request message for
+ [LicenseConfigService.UpdateLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.UpdateLicenseConfig]
+ method.
+ license_config (google.cloud.discoveryengine_v1.types.LicenseConfig):
+ Required. The
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ to update.
+
+ This corresponds to the ``license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
+ Optional. Indicates which fields in the provided
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ to update.
+
+ If an unsupported or unknown field is provided, an
+ INVALID_ARGUMENT error is returned.
+
+ 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.cloud.discoveryengine_v1.types.LicenseConfig:
+ Information about users' licenses.
+ """
+ # 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 = [license_config, 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, license_config_service.UpdateLicenseConfigRequest):
+ request = license_config_service.UpdateLicenseConfigRequest(request)
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if license_config is not None:
+ request.license_config = license_config
+ 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_license_config]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("license_config.name", request.license_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_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.GetLicenseConfigRequest, 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]]] = (),
+ ) -> license_config.LicenseConfig:
+ r"""Gets a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig].
+
+ .. 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_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetLicenseConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.GetLicenseConfigRequest, dict]):
+ The request object. Request message for
+ [LicenseConfigService.GetLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.GetLicenseConfig]
+ method.
+ name (str):
+ Required. Full resource name of
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig],
+ such as
+ ``projects/{project}/locations/{location}/licenseConfigs/*``.
+
+ If the caller does not have permission to access the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig],
+ regardless of whether or not it exists, a
+ PERMISSION_DENIED error is returned.
+
+ If the requested
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ 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.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each 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.LicenseConfig:
+ Information about users' licenses.
+ """
+ # 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, license_config_service.GetLicenseConfigRequest):
+ request = license_config_service.GetLicenseConfigRequest(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_license_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 list_license_configs(
+ self,
+ request: Optional[
+ Union[license_config_service.ListLicenseConfigsRequest, 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.ListLicenseConfigsPager:
+ r"""Lists all the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]s
+ associated with the project.
+
+ .. code-block:: python
+
+ # This snippet has been automatically generated and should be regarded as a
+ # code template only.
+ # It will require modifications to work:
+ # - It may require correct/in-range values for request initialization.
+ # - It may require specifying regional endpoints when creating the service
+ # client as shown in:
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
+ from google.cloud import discoveryengine_v1
+
+ def sample_list_license_configs():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListLicenseConfigsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_license_configs(request=request)
+
+ # Handle the response
+ for response in page_result:
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.ListLicenseConfigsRequest, dict]):
+ The request object. Request message for
+ [LicenseConfigService.ListLicenseConfigs][google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs]
+ method.
+ parent (str):
+ Required. The parent branch resource name, such as
+ ``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.discoveryengine_v1.services.license_config_service.pagers.ListLicenseConfigsPager:
+ Response message for
+ [LicenseConfigService.ListLicenseConfigs][google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs]
+ 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, license_config_service.ListLicenseConfigsRequest):
+ request = license_config_service.ListLicenseConfigsRequest(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_license_configs]
+
+ # 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.ListLicenseConfigsPager(
+ method=rpc,
+ request=request,
+ response=response,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ def distribute_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.DistributeLicenseConfigRequest, dict]
+ ] = None,
+ *,
+ billing_account_license_config: Optional[str] = None,
+ project_number: Optional[int] = None,
+ location: Optional[str] = None,
+ license_count: Optional[int] = None,
+ license_config_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]]] = (),
+ ) -> license_config_service.DistributeLicenseConfigResponse:
+ r"""Distributes a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ from billing account level to project level.
+
+ .. 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_distribute_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DistributeLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ )
+
+ # Make the request
+ response = client.distribute_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.DistributeLicenseConfigRequest, dict]):
+ The request object. Request message for
+ [LicenseConfigService.DistributeLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig]
+ method.
+ billing_account_license_config (str):
+ Required. Full resource name of
+ [BillingAccountLicenseConfig][].
+
+ Format:
+ ``billingAccounts/{billing_account}/billingAccountLicenseConfigs/{billing_account_license_config_id}``.
+
+ This corresponds to the ``billing_account_license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ project_number (int):
+ Required. The target GCP project
+ number to distribute the license config
+ to.
+
+ This corresponds to the ``project_number`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ location (str):
+ Required. The target GCP project
+ region to distribute the license config
+ to.
+
+ This corresponds to the ``location`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_count (int):
+ Required. The number of licenses to
+ distribute.
+
+ This corresponds to the ``license_count`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_config_id (str):
+ Optional. Distribute seats to this
+ license config instead of creating a new
+ one. If not specified, a new license
+ config will be created from the billing
+ account license config.
+
+ This corresponds to the ``license_config_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.discoveryengine_v1.types.DistributeLicenseConfigResponse:
+ Response message for
+ [LicenseConfigService.DistributeLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig]
+ method.
+
+ """
+ # 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 = [
+ billing_account_license_config,
+ project_number,
+ location,
+ license_count,
+ license_config_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, license_config_service.DistributeLicenseConfigRequest
+ ):
+ request = license_config_service.DistributeLicenseConfigRequest(request)
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if billing_account_license_config is not None:
+ request.billing_account_license_config = billing_account_license_config
+ if project_number is not None:
+ request.project_number = project_number
+ if location is not None:
+ request.location = location
+ if license_count is not None:
+ request.license_count = license_count
+ if license_config_id is not None:
+ request.license_config_id = license_config_id
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[
+ self._transport.distribute_license_config
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (
+ (
+ "billing_account_license_config",
+ request.billing_account_license_config,
+ ),
+ )
+ ),
+ )
+
+ # 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 retract_license_config(
+ self,
+ request: Optional[
+ Union[license_config_service.RetractLicenseConfigRequest, dict]
+ ] = None,
+ *,
+ billing_account_license_config: Optional[str] = None,
+ license_config: Optional[str] = None,
+ full_retract: Optional[bool] = None,
+ license_count: Optional[int] = None,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Union[float, object] = gapic_v1.method.DEFAULT,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> license_config_service.RetractLicenseConfigResponse:
+ r"""This method is called from the billing account side to retract
+ the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ from the given project back to the billing account.
+
+ .. 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_retract_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.RetractLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ )
+
+ # Make the request
+ response = client.retract_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.RetractLicenseConfigRequest, dict]):
+ The request object. Request message for
+ [LicenseConfigService.RetractLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig]
+ method.
+ billing_account_license_config (str):
+ Required. Full resource name of
+ [BillingAccountLicenseConfig][].
+
+ Format:
+ ``billingAccounts/{billing_account}/billingAccountLicenseConfigs/{billing_account_license_config_id}``.
+
+ This corresponds to the ``billing_account_license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_config (str):
+ Required. Full resource name of
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig].
+
+ Format:
+ ``projects/{project}/locations/{location}/licenseConfigs/{license_config_id}``.
+
+ This corresponds to the ``license_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ full_retract (bool):
+ Optional. If set to true, retract the
+ entire license config. Otherwise,
+ retract the specified license count.
+
+ This corresponds to the ``full_retract`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ license_count (int):
+ Optional. The number of licenses to retract. Only used
+ when full_retract is false.
+
+ This corresponds to the ``license_count`` 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.RetractLicenseConfigResponse:
+ Response message for
+ [LicenseConfigService.RetractLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig]
+ method.
+
+ """
+ # 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 = [
+ billing_account_license_config,
+ license_config,
+ full_retract,
+ license_count,
+ ]
+ 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, license_config_service.RetractLicenseConfigRequest):
+ request = license_config_service.RetractLicenseConfigRequest(request)
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if billing_account_license_config is not None:
+ request.billing_account_license_config = billing_account_license_config
+ if license_config is not None:
+ request.license_config = license_config
+ if full_retract is not None:
+ request.full_retract = full_retract
+ if license_count is not None:
+ request.license_count = license_count
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.retract_license_config]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (
+ (
+ "billing_account_license_config",
+ request.billing_account_license_config,
+ ),
+ )
+ ),
+ )
+
+ # 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) -> "LicenseConfigServiceClient":
+ 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__ = ("LicenseConfigServiceClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/pagers.py
new file mode 100644
index 000000000000..08a55bf769c8
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/pagers.py
@@ -0,0 +1,201 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import (
+ Any,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+ Optional,
+ Sequence,
+ Tuple,
+ Union,
+)
+
+from google.api_core import gapic_v1
+from google.api_core import retry as retries
+from google.api_core import retry_async as retries_async
+
+try:
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
+ OptionalAsyncRetry = Union[
+ retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
+ ]
+except AttributeError: # pragma: NO COVER
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
+
+from google.cloud.discoveryengine_v1.types import license_config, license_config_service
+
+
+class ListLicenseConfigsPager:
+ """A pager for iterating through ``list_license_configs`` requests.
+
+ This class thinly wraps an initial
+ :class:`google.cloud.discoveryengine_v1.types.ListLicenseConfigsResponse` object, and
+ provides an ``__iter__`` method to iterate through its
+ ``license_configs`` field.
+
+ If there are more pages, the ``__iter__`` method will make additional
+ ``ListLicenseConfigs`` requests and continue to iterate
+ through the ``license_configs`` field on the
+ corresponding responses.
+
+ All the usual :class:`google.cloud.discoveryengine_v1.types.ListLicenseConfigsResponse`
+ 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[..., license_config_service.ListLicenseConfigsResponse],
+ request: license_config_service.ListLicenseConfigsRequest,
+ response: license_config_service.ListLicenseConfigsResponse,
+ *,
+ 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.discoveryengine_v1.types.ListLicenseConfigsRequest):
+ The initial request object.
+ response (google.cloud.discoveryengine_v1.types.ListLicenseConfigsResponse):
+ 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 = license_config_service.ListLicenseConfigsRequest(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[license_config_service.ListLicenseConfigsResponse]:
+ 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[license_config.LicenseConfig]:
+ for page in self.pages:
+ yield from page.license_configs
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
+class ListLicenseConfigsAsyncPager:
+ """A pager for iterating through ``list_license_configs`` requests.
+
+ This class thinly wraps an initial
+ :class:`google.cloud.discoveryengine_v1.types.ListLicenseConfigsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``license_configs`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListLicenseConfigs`` requests and continue to iterate
+ through the ``license_configs`` field on the
+ corresponding responses.
+
+ All the usual :class:`google.cloud.discoveryengine_v1.types.ListLicenseConfigsResponse`
+ 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[license_config_service.ListLicenseConfigsResponse]
+ ],
+ request: license_config_service.ListLicenseConfigsRequest,
+ response: license_config_service.ListLicenseConfigsResponse,
+ *,
+ 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.discoveryengine_v1.types.ListLicenseConfigsRequest):
+ The initial request object.
+ response (google.cloud.discoveryengine_v1.types.ListLicenseConfigsResponse):
+ 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 = license_config_service.ListLicenseConfigsRequest(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[license_config_service.ListLicenseConfigsResponse]:
+ 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[license_config.LicenseConfig]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.license_configs:
+ 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-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/README.rst b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/README.rst
new file mode 100644
index 000000000000..fbcd87e2e227
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/README.rst
@@ -0,0 +1,10 @@
+
+transport inheritance structure
+_______________________________
+
+``LicenseConfigServiceTransport`` is the ABC for all transports.
+
+- public child ``LicenseConfigServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``).
+- public child ``LicenseConfigServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``).
+- private child ``_BaseLicenseConfigServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``).
+- public child ``LicenseConfigServiceRestTransport`` 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/license_config_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/__init__.py
new file mode 100644
index 000000000000..6dd724f78fda
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_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 LicenseConfigServiceTransport
+from .grpc import LicenseConfigServiceGrpcTransport
+from .grpc_asyncio import LicenseConfigServiceGrpcAsyncIOTransport
+from .rest import LicenseConfigServiceRestInterceptor, LicenseConfigServiceRestTransport
+
+# Compile a registry of transports.
+_transport_registry = OrderedDict() # type: Dict[str, Type[LicenseConfigServiceTransport]]
+_transport_registry["grpc"] = LicenseConfigServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = LicenseConfigServiceGrpcAsyncIOTransport
+_transport_registry["rest"] = LicenseConfigServiceRestTransport
+
+__all__ = (
+ "LicenseConfigServiceTransport",
+ "LicenseConfigServiceGrpcTransport",
+ "LicenseConfigServiceGrpcAsyncIOTransport",
+ "LicenseConfigServiceRestTransport",
+ "LicenseConfigServiceRestInterceptor",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/base.py
new file mode 100644
index 000000000000..4f584a0152c5
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/base.py
@@ -0,0 +1,310 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 license_config, license_config_service
+from google.cloud.discoveryengine_v1.types import license_config as gcd_license_config
+
+DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=package_version.__version__
+)
+DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
+
+
+class LicenseConfigServiceTransport(abc.ABC):
+ """Abstract transport class for LicenseConfigService."""
+
+ 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.create_license_config: gapic_v1.method.wrap_method(
+ self.create_license_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.update_license_config: gapic_v1.method.wrap_method(
+ self.update_license_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.get_license_config: gapic_v1.method.wrap_method(
+ self.get_license_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.list_license_configs: gapic_v1.method.wrap_method(
+ self.list_license_configs,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.distribute_license_config: gapic_v1.method.wrap_method(
+ self.distribute_license_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.retract_license_config: gapic_v1.method.wrap_method(
+ self.retract_license_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 create_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.CreateLicenseConfigRequest],
+ Union[
+ gcd_license_config.LicenseConfig,
+ Awaitable[gcd_license_config.LicenseConfig],
+ ],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def update_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.UpdateLicenseConfigRequest],
+ Union[
+ gcd_license_config.LicenseConfig,
+ Awaitable[gcd_license_config.LicenseConfig],
+ ],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def get_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.GetLicenseConfigRequest],
+ Union[license_config.LicenseConfig, Awaitable[license_config.LicenseConfig]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def list_license_configs(
+ self,
+ ) -> Callable[
+ [license_config_service.ListLicenseConfigsRequest],
+ Union[
+ license_config_service.ListLicenseConfigsResponse,
+ Awaitable[license_config_service.ListLicenseConfigsResponse],
+ ],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def distribute_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.DistributeLicenseConfigRequest],
+ Union[
+ license_config_service.DistributeLicenseConfigResponse,
+ Awaitable[license_config_service.DistributeLicenseConfigResponse],
+ ],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def retract_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.RetractLicenseConfigRequest],
+ Union[
+ license_config_service.RetractLicenseConfigResponse,
+ Awaitable[license_config_service.RetractLicenseConfigResponse],
+ ],
+ ]:
+ 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__ = ("LicenseConfigServiceTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/grpc.py
new file mode 100644
index 000000000000..2dcc7670c759
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/grpc.py
@@ -0,0 +1,577 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 license_config, license_config_service
+from google.cloud.discoveryengine_v1.types import license_config as gcd_license_config
+
+from .base import DEFAULT_CLIENT_INFO, LicenseConfigServiceTransport
+
+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.LicenseConfigService",
+ "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.LicenseConfigService",
+ "rpcName": client_call_details.method,
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class LicenseConfigServiceGrpcTransport(LicenseConfigServiceTransport):
+ """gRPC backend transport for LicenseConfigService.
+
+ Service for managing license config related resources.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends 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 create_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.CreateLicenseConfigRequest],
+ gcd_license_config.LicenseConfig,
+ ]:
+ r"""Return a callable for the create license config method over gRPC.
+
+ Creates a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ This method should only be used for creating NotebookLm licenses
+ or Gemini Enterprise free trial licenses.
+
+ Returns:
+ Callable[[~.CreateLicenseConfigRequest],
+ ~.LicenseConfig]:
+ 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_license_config" not in self._stubs:
+ self._stubs["create_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/CreateLicenseConfig",
+ request_serializer=license_config_service.CreateLicenseConfigRequest.serialize,
+ response_deserializer=gcd_license_config.LicenseConfig.deserialize,
+ )
+ return self._stubs["create_license_config"]
+
+ @property
+ def update_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.UpdateLicenseConfigRequest],
+ gcd_license_config.LicenseConfig,
+ ]:
+ r"""Return a callable for the update license config method over gRPC.
+
+ Updates the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+
+ Returns:
+ Callable[[~.UpdateLicenseConfigRequest],
+ ~.LicenseConfig]:
+ 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_license_config" not in self._stubs:
+ self._stubs["update_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/UpdateLicenseConfig",
+ request_serializer=license_config_service.UpdateLicenseConfigRequest.serialize,
+ response_deserializer=gcd_license_config.LicenseConfig.deserialize,
+ )
+ return self._stubs["update_license_config"]
+
+ @property
+ def get_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.GetLicenseConfigRequest], license_config.LicenseConfig
+ ]:
+ r"""Return a callable for the get license config method over gRPC.
+
+ Gets a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig].
+
+ Returns:
+ Callable[[~.GetLicenseConfigRequest],
+ ~.LicenseConfig]:
+ 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_license_config" not in self._stubs:
+ self._stubs["get_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/GetLicenseConfig",
+ request_serializer=license_config_service.GetLicenseConfigRequest.serialize,
+ response_deserializer=license_config.LicenseConfig.deserialize,
+ )
+ return self._stubs["get_license_config"]
+
+ @property
+ def list_license_configs(
+ self,
+ ) -> Callable[
+ [license_config_service.ListLicenseConfigsRequest],
+ license_config_service.ListLicenseConfigsResponse,
+ ]:
+ r"""Return a callable for the list license configs method over gRPC.
+
+ Lists all the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]s
+ associated with the project.
+
+ Returns:
+ Callable[[~.ListLicenseConfigsRequest],
+ ~.ListLicenseConfigsResponse]:
+ 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_license_configs" not in self._stubs:
+ self._stubs["list_license_configs"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/ListLicenseConfigs",
+ request_serializer=license_config_service.ListLicenseConfigsRequest.serialize,
+ response_deserializer=license_config_service.ListLicenseConfigsResponse.deserialize,
+ )
+ return self._stubs["list_license_configs"]
+
+ @property
+ def distribute_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.DistributeLicenseConfigRequest],
+ license_config_service.DistributeLicenseConfigResponse,
+ ]:
+ r"""Return a callable for the distribute license config method over gRPC.
+
+ Distributes a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ from billing account level to project level.
+
+ Returns:
+ Callable[[~.DistributeLicenseConfigRequest],
+ ~.DistributeLicenseConfigResponse]:
+ 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 "distribute_license_config" not in self._stubs:
+ self._stubs["distribute_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/DistributeLicenseConfig",
+ request_serializer=license_config_service.DistributeLicenseConfigRequest.serialize,
+ response_deserializer=license_config_service.DistributeLicenseConfigResponse.deserialize,
+ )
+ return self._stubs["distribute_license_config"]
+
+ @property
+ def retract_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.RetractLicenseConfigRequest],
+ license_config_service.RetractLicenseConfigResponse,
+ ]:
+ r"""Return a callable for the retract license config method over gRPC.
+
+ This method is called from the billing account side to retract
+ the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ from the given project back to the billing account.
+
+ Returns:
+ Callable[[~.RetractLicenseConfigRequest],
+ ~.RetractLicenseConfigResponse]:
+ 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 "retract_license_config" not in self._stubs:
+ self._stubs["retract_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/RetractLicenseConfig",
+ request_serializer=license_config_service.RetractLicenseConfigRequest.serialize,
+ response_deserializer=license_config_service.RetractLicenseConfigResponse.deserialize,
+ )
+ return self._stubs["retract_license_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__ = ("LicenseConfigServiceGrpcTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/grpc_asyncio.py
new file mode 100644
index 000000000000..9d918b17ab79
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/grpc_asyncio.py
@@ -0,0 +1,641 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 license_config, license_config_service
+from google.cloud.discoveryengine_v1.types import license_config as gcd_license_config
+
+from .base import DEFAULT_CLIENT_INFO, LicenseConfigServiceTransport
+from .grpc import LicenseConfigServiceGrpcTransport
+
+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.LicenseConfigService",
+ "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.LicenseConfigService",
+ "rpcName": str(client_call_details.method),
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class LicenseConfigServiceGrpcAsyncIOTransport(LicenseConfigServiceTransport):
+ """gRPC AsyncIO backend transport for LicenseConfigService.
+
+ Service for managing license config related resources.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends 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 create_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.CreateLicenseConfigRequest],
+ Awaitable[gcd_license_config.LicenseConfig],
+ ]:
+ r"""Return a callable for the create license config method over gRPC.
+
+ Creates a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ This method should only be used for creating NotebookLm licenses
+ or Gemini Enterprise free trial licenses.
+
+ Returns:
+ Callable[[~.CreateLicenseConfigRequest],
+ Awaitable[~.LicenseConfig]]:
+ 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_license_config" not in self._stubs:
+ self._stubs["create_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/CreateLicenseConfig",
+ request_serializer=license_config_service.CreateLicenseConfigRequest.serialize,
+ response_deserializer=gcd_license_config.LicenseConfig.deserialize,
+ )
+ return self._stubs["create_license_config"]
+
+ @property
+ def update_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.UpdateLicenseConfigRequest],
+ Awaitable[gcd_license_config.LicenseConfig],
+ ]:
+ r"""Return a callable for the update license config method over gRPC.
+
+ Updates the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+
+ Returns:
+ Callable[[~.UpdateLicenseConfigRequest],
+ Awaitable[~.LicenseConfig]]:
+ 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_license_config" not in self._stubs:
+ self._stubs["update_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/UpdateLicenseConfig",
+ request_serializer=license_config_service.UpdateLicenseConfigRequest.serialize,
+ response_deserializer=gcd_license_config.LicenseConfig.deserialize,
+ )
+ return self._stubs["update_license_config"]
+
+ @property
+ def get_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.GetLicenseConfigRequest],
+ Awaitable[license_config.LicenseConfig],
+ ]:
+ r"""Return a callable for the get license config method over gRPC.
+
+ Gets a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig].
+
+ Returns:
+ Callable[[~.GetLicenseConfigRequest],
+ Awaitable[~.LicenseConfig]]:
+ 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_license_config" not in self._stubs:
+ self._stubs["get_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/GetLicenseConfig",
+ request_serializer=license_config_service.GetLicenseConfigRequest.serialize,
+ response_deserializer=license_config.LicenseConfig.deserialize,
+ )
+ return self._stubs["get_license_config"]
+
+ @property
+ def list_license_configs(
+ self,
+ ) -> Callable[
+ [license_config_service.ListLicenseConfigsRequest],
+ Awaitable[license_config_service.ListLicenseConfigsResponse],
+ ]:
+ r"""Return a callable for the list license configs method over gRPC.
+
+ Lists all the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]s
+ associated with the project.
+
+ Returns:
+ Callable[[~.ListLicenseConfigsRequest],
+ Awaitable[~.ListLicenseConfigsResponse]]:
+ 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_license_configs" not in self._stubs:
+ self._stubs["list_license_configs"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/ListLicenseConfigs",
+ request_serializer=license_config_service.ListLicenseConfigsRequest.serialize,
+ response_deserializer=license_config_service.ListLicenseConfigsResponse.deserialize,
+ )
+ return self._stubs["list_license_configs"]
+
+ @property
+ def distribute_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.DistributeLicenseConfigRequest],
+ Awaitable[license_config_service.DistributeLicenseConfigResponse],
+ ]:
+ r"""Return a callable for the distribute license config method over gRPC.
+
+ Distributes a
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ from billing account level to project level.
+
+ Returns:
+ Callable[[~.DistributeLicenseConfigRequest],
+ Awaitable[~.DistributeLicenseConfigResponse]]:
+ 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 "distribute_license_config" not in self._stubs:
+ self._stubs["distribute_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/DistributeLicenseConfig",
+ request_serializer=license_config_service.DistributeLicenseConfigRequest.serialize,
+ response_deserializer=license_config_service.DistributeLicenseConfigResponse.deserialize,
+ )
+ return self._stubs["distribute_license_config"]
+
+ @property
+ def retract_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.RetractLicenseConfigRequest],
+ Awaitable[license_config_service.RetractLicenseConfigResponse],
+ ]:
+ r"""Return a callable for the retract license config method over gRPC.
+
+ This method is called from the billing account side to retract
+ the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ from the given project back to the billing account.
+
+ Returns:
+ Callable[[~.RetractLicenseConfigRequest],
+ Awaitable[~.RetractLicenseConfigResponse]]:
+ 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 "retract_license_config" not in self._stubs:
+ self._stubs["retract_license_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.LicenseConfigService/RetractLicenseConfig",
+ request_serializer=license_config_service.RetractLicenseConfigRequest.serialize,
+ response_deserializer=license_config_service.RetractLicenseConfigResponse.deserialize,
+ )
+ return self._stubs["retract_license_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.create_license_config: self._wrap_method(
+ self.create_license_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.update_license_config: self._wrap_method(
+ self.update_license_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.get_license_config: self._wrap_method(
+ self.get_license_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.list_license_configs: self._wrap_method(
+ self.list_license_configs,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.distribute_license_config: self._wrap_method(
+ self.distribute_license_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.retract_license_config: self._wrap_method(
+ self.retract_license_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__ = ("LicenseConfigServiceGrpcAsyncIOTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/rest.py
new file mode 100644
index 000000000000..3a4a4387cb81
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/rest.py
@@ -0,0 +1,2008 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 license_config, license_config_service
+from google.cloud.discoveryengine_v1.types import license_config as gcd_license_config
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .rest_base import _BaseLicenseConfigServiceRestTransport
+
+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 LicenseConfigServiceRestInterceptor:
+ """Interceptor for LicenseConfigService.
+
+ 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 LicenseConfigServiceRestTransport.
+
+ .. code-block:: python
+ class MyCustomLicenseConfigServiceInterceptor(LicenseConfigServiceRestInterceptor):
+ def pre_create_license_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_create_license_config(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_distribute_license_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_distribute_license_config(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_get_license_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_get_license_config(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_list_license_configs(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_list_license_configs(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_retract_license_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_retract_license_config(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_update_license_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_update_license_config(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ transport = LicenseConfigServiceRestTransport(interceptor=MyCustomLicenseConfigServiceInterceptor())
+ client = LicenseConfigServiceClient(transport=transport)
+
+
+ """
+
+ def pre_create_license_config(
+ self,
+ request: license_config_service.CreateLicenseConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ license_config_service.CreateLicenseConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for create_license_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the LicenseConfigService server.
+ """
+ return request, metadata
+
+ def post_create_license_config(
+ self, response: gcd_license_config.LicenseConfig
+ ) -> gcd_license_config.LicenseConfig:
+ """Post-rpc interceptor for create_license_config
+
+ DEPRECATED. Please use the `post_create_license_config_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the LicenseConfigService server but before
+ it is returned to user code. This `post_create_license_config` interceptor runs
+ before the `post_create_license_config_with_metadata` interceptor.
+ """
+ return response
+
+ def post_create_license_config_with_metadata(
+ self,
+ response: gcd_license_config.LicenseConfig,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ gcd_license_config.LicenseConfig, Sequence[Tuple[str, Union[str, bytes]]]
+ ]:
+ """Post-rpc interceptor for create_license_config
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the LicenseConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_create_license_config_with_metadata`
+ interceptor in new development instead of the `post_create_license_config` interceptor.
+ When both interceptors are used, this `post_create_license_config_with_metadata` interceptor runs after the
+ `post_create_license_config` interceptor. The (possibly modified) response returned by
+ `post_create_license_config` will be passed to
+ `post_create_license_config_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_distribute_license_config(
+ self,
+ request: license_config_service.DistributeLicenseConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ license_config_service.DistributeLicenseConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for distribute_license_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the LicenseConfigService server.
+ """
+ return request, metadata
+
+ def post_distribute_license_config(
+ self, response: license_config_service.DistributeLicenseConfigResponse
+ ) -> license_config_service.DistributeLicenseConfigResponse:
+ """Post-rpc interceptor for distribute_license_config
+
+ DEPRECATED. Please use the `post_distribute_license_config_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the LicenseConfigService server but before
+ it is returned to user code. This `post_distribute_license_config` interceptor runs
+ before the `post_distribute_license_config_with_metadata` interceptor.
+ """
+ return response
+
+ def post_distribute_license_config_with_metadata(
+ self,
+ response: license_config_service.DistributeLicenseConfigResponse,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ license_config_service.DistributeLicenseConfigResponse,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Post-rpc interceptor for distribute_license_config
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the LicenseConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_distribute_license_config_with_metadata`
+ interceptor in new development instead of the `post_distribute_license_config` interceptor.
+ When both interceptors are used, this `post_distribute_license_config_with_metadata` interceptor runs after the
+ `post_distribute_license_config` interceptor. The (possibly modified) response returned by
+ `post_distribute_license_config` will be passed to
+ `post_distribute_license_config_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_get_license_config(
+ self,
+ request: license_config_service.GetLicenseConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ license_config_service.GetLicenseConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for get_license_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the LicenseConfigService server.
+ """
+ return request, metadata
+
+ def post_get_license_config(
+ self, response: license_config.LicenseConfig
+ ) -> license_config.LicenseConfig:
+ """Post-rpc interceptor for get_license_config
+
+ DEPRECATED. Please use the `post_get_license_config_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the LicenseConfigService server but before
+ it is returned to user code. This `post_get_license_config` interceptor runs
+ before the `post_get_license_config_with_metadata` interceptor.
+ """
+ return response
+
+ def post_get_license_config_with_metadata(
+ self,
+ response: license_config.LicenseConfig,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[license_config.LicenseConfig, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for get_license_config
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the LicenseConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_get_license_config_with_metadata`
+ interceptor in new development instead of the `post_get_license_config` interceptor.
+ When both interceptors are used, this `post_get_license_config_with_metadata` interceptor runs after the
+ `post_get_license_config` interceptor. The (possibly modified) response returned by
+ `post_get_license_config` will be passed to
+ `post_get_license_config_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_list_license_configs(
+ self,
+ request: license_config_service.ListLicenseConfigsRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ license_config_service.ListLicenseConfigsRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for list_license_configs
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the LicenseConfigService server.
+ """
+ return request, metadata
+
+ def post_list_license_configs(
+ self, response: license_config_service.ListLicenseConfigsResponse
+ ) -> license_config_service.ListLicenseConfigsResponse:
+ """Post-rpc interceptor for list_license_configs
+
+ DEPRECATED. Please use the `post_list_license_configs_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the LicenseConfigService server but before
+ it is returned to user code. This `post_list_license_configs` interceptor runs
+ before the `post_list_license_configs_with_metadata` interceptor.
+ """
+ return response
+
+ def post_list_license_configs_with_metadata(
+ self,
+ response: license_config_service.ListLicenseConfigsResponse,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ license_config_service.ListLicenseConfigsResponse,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Post-rpc interceptor for list_license_configs
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the LicenseConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_list_license_configs_with_metadata`
+ interceptor in new development instead of the `post_list_license_configs` interceptor.
+ When both interceptors are used, this `post_list_license_configs_with_metadata` interceptor runs after the
+ `post_list_license_configs` interceptor. The (possibly modified) response returned by
+ `post_list_license_configs` will be passed to
+ `post_list_license_configs_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_retract_license_config(
+ self,
+ request: license_config_service.RetractLicenseConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ license_config_service.RetractLicenseConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for retract_license_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the LicenseConfigService server.
+ """
+ return request, metadata
+
+ def post_retract_license_config(
+ self, response: license_config_service.RetractLicenseConfigResponse
+ ) -> license_config_service.RetractLicenseConfigResponse:
+ """Post-rpc interceptor for retract_license_config
+
+ DEPRECATED. Please use the `post_retract_license_config_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the LicenseConfigService server but before
+ it is returned to user code. This `post_retract_license_config` interceptor runs
+ before the `post_retract_license_config_with_metadata` interceptor.
+ """
+ return response
+
+ def post_retract_license_config_with_metadata(
+ self,
+ response: license_config_service.RetractLicenseConfigResponse,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ license_config_service.RetractLicenseConfigResponse,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Post-rpc interceptor for retract_license_config
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the LicenseConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_retract_license_config_with_metadata`
+ interceptor in new development instead of the `post_retract_license_config` interceptor.
+ When both interceptors are used, this `post_retract_license_config_with_metadata` interceptor runs after the
+ `post_retract_license_config` interceptor. The (possibly modified) response returned by
+ `post_retract_license_config` will be passed to
+ `post_retract_license_config_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_update_license_config(
+ self,
+ request: license_config_service.UpdateLicenseConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ license_config_service.UpdateLicenseConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for update_license_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the LicenseConfigService server.
+ """
+ return request, metadata
+
+ def post_update_license_config(
+ self, response: gcd_license_config.LicenseConfig
+ ) -> gcd_license_config.LicenseConfig:
+ """Post-rpc interceptor for update_license_config
+
+ DEPRECATED. Please use the `post_update_license_config_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the LicenseConfigService server but before
+ it is returned to user code. This `post_update_license_config` interceptor runs
+ before the `post_update_license_config_with_metadata` interceptor.
+ """
+ return response
+
+ def post_update_license_config_with_metadata(
+ self,
+ response: gcd_license_config.LicenseConfig,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ gcd_license_config.LicenseConfig, Sequence[Tuple[str, Union[str, bytes]]]
+ ]:
+ """Post-rpc interceptor for update_license_config
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the LicenseConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_update_license_config_with_metadata`
+ interceptor in new development instead of the `post_update_license_config` interceptor.
+ When both interceptors are used, this `post_update_license_config_with_metadata` interceptor runs after the
+ `post_update_license_config` interceptor. The (possibly modified) response returned by
+ `post_update_license_config` will be passed to
+ `post_update_license_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 LicenseConfigService 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 LicenseConfigService 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 LicenseConfigService 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 LicenseConfigService 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 LicenseConfigService 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 LicenseConfigService server but before
+ it is returned to user code.
+ """
+ return response
+
+
+@dataclasses.dataclass
+class LicenseConfigServiceRestStub:
+ _session: AuthorizedSession
+ _host: str
+ _interceptor: LicenseConfigServiceRestInterceptor
+
+
+class LicenseConfigServiceRestTransport(_BaseLicenseConfigServiceRestTransport):
+ """REST backend synchronous transport for LicenseConfigService.
+
+ Service for managing license config related resources.
+
+ This class defines the same methods as the primary client, so the
+ primary client can load the underlying transport implementation
+ and call it.
+
+ It sends JSON representations of protocol buffers over HTTP/1.1
+ """
+
+ def __init__(
+ self,
+ *,
+ host: str = "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[LicenseConfigServiceRestInterceptor] = 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[LicenseConfigServiceRestInterceptor]): 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 LicenseConfigServiceRestInterceptor()
+ self._prep_wrapped_messages(client_info)
+
+ class _CreateLicenseConfig(
+ _BaseLicenseConfigServiceRestTransport._BaseCreateLicenseConfig,
+ LicenseConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("LicenseConfigServiceRestTransport.CreateLicenseConfig")
+
+ @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: license_config_service.CreateLicenseConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> gcd_license_config.LicenseConfig:
+ r"""Call the create license config method over HTTP.
+
+ Args:
+ request (~.license_config_service.CreateLicenseConfigRequest):
+ The request object. Request message for
+ [LicenseConfigService.CreateLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.CreateLicenseConfig]
+ 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:
+ ~.gcd_license_config.LicenseConfig:
+ Information about users' licenses.
+ """
+
+ http_options = _BaseLicenseConfigServiceRestTransport._BaseCreateLicenseConfig._get_http_options()
+ request, metadata = self._interceptor.pre_create_license_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseLicenseConfigServiceRestTransport._BaseCreateLicenseConfig,
+ "_BaseCreateLicenseConfig__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.LicenseConfigServiceClient.CreateLicenseConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "CreateLicenseConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ LicenseConfigServiceRestTransport._CreateLicenseConfig._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 = gcd_license_config.LicenseConfig()
+ pb_resp = gcd_license_config.LicenseConfig.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_create_license_config(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_create_license_config_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = gcd_license_config.LicenseConfig.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.LicenseConfigServiceClient.create_license_config",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "CreateLicenseConfig",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _DistributeLicenseConfig(
+ _BaseLicenseConfigServiceRestTransport._BaseDistributeLicenseConfig,
+ LicenseConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("LicenseConfigServiceRestTransport.DistributeLicenseConfig")
+
+ @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: license_config_service.DistributeLicenseConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> license_config_service.DistributeLicenseConfigResponse:
+ r"""Call the distribute license config method over HTTP.
+
+ Args:
+ request (~.license_config_service.DistributeLicenseConfigRequest):
+ The request object. Request message for
+ [LicenseConfigService.DistributeLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig]
+ 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:
+ ~.license_config_service.DistributeLicenseConfigResponse:
+ Response message for
+ [LicenseConfigService.DistributeLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig]
+ method.
+
+ """
+
+ http_options = _BaseLicenseConfigServiceRestTransport._BaseDistributeLicenseConfig._get_http_options()
+ request, metadata = self._interceptor.pre_distribute_license_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseLicenseConfigServiceRestTransport._BaseDistributeLicenseConfig,
+ "_BaseDistributeLicenseConfig__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.LicenseConfigServiceClient.DistributeLicenseConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "DistributeLicenseConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = LicenseConfigServiceRestTransport._DistributeLicenseConfig._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 = license_config_service.DistributeLicenseConfigResponse()
+ pb_resp = license_config_service.DistributeLicenseConfigResponse.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_distribute_license_config(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_distribute_license_config_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = (
+ license_config_service.DistributeLicenseConfigResponse.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.LicenseConfigServiceClient.distribute_license_config",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "DistributeLicenseConfig",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _GetLicenseConfig(
+ _BaseLicenseConfigServiceRestTransport._BaseGetLicenseConfig,
+ LicenseConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("LicenseConfigServiceRestTransport.GetLicenseConfig")
+
+ @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: license_config_service.GetLicenseConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> license_config.LicenseConfig:
+ r"""Call the get license config method over HTTP.
+
+ Args:
+ request (~.license_config_service.GetLicenseConfigRequest):
+ The request object. Request message for
+ [LicenseConfigService.GetLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.GetLicenseConfig]
+ 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:
+ ~.license_config.LicenseConfig:
+ Information about users' licenses.
+ """
+
+ http_options = _BaseLicenseConfigServiceRestTransport._BaseGetLicenseConfig._get_http_options()
+ request, metadata = self._interceptor.pre_get_license_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseLicenseConfigServiceRestTransport._BaseGetLicenseConfig,
+ "_BaseGetLicenseConfig__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.LicenseConfigServiceClient.GetLicenseConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "GetLicenseConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ LicenseConfigServiceRestTransport._GetLicenseConfig._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 = license_config.LicenseConfig()
+ pb_resp = license_config.LicenseConfig.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_get_license_config(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_get_license_config_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = license_config.LicenseConfig.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.LicenseConfigServiceClient.get_license_config",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "GetLicenseConfig",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _ListLicenseConfigs(
+ _BaseLicenseConfigServiceRestTransport._BaseListLicenseConfigs,
+ LicenseConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("LicenseConfigServiceRestTransport.ListLicenseConfigs")
+
+ @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: license_config_service.ListLicenseConfigsRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> license_config_service.ListLicenseConfigsResponse:
+ r"""Call the list license configs method over HTTP.
+
+ Args:
+ request (~.license_config_service.ListLicenseConfigsRequest):
+ The request object. Request message for
+ [LicenseConfigService.ListLicenseConfigs][google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs]
+ 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:
+ ~.license_config_service.ListLicenseConfigsResponse:
+ Response message for
+ [LicenseConfigService.ListLicenseConfigs][google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs]
+ method.
+
+ """
+
+ http_options = _BaseLicenseConfigServiceRestTransport._BaseListLicenseConfigs._get_http_options()
+ request, metadata = self._interceptor.pre_list_license_configs(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseLicenseConfigServiceRestTransport._BaseListLicenseConfigs,
+ "_BaseListLicenseConfigs__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.LicenseConfigServiceClient.ListLicenseConfigs",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "ListLicenseConfigs",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ LicenseConfigServiceRestTransport._ListLicenseConfigs._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 = license_config_service.ListLicenseConfigsResponse()
+ pb_resp = license_config_service.ListLicenseConfigsResponse.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_list_license_configs(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_list_license_configs_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = (
+ license_config_service.ListLicenseConfigsResponse.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.LicenseConfigServiceClient.list_license_configs",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "ListLicenseConfigs",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _RetractLicenseConfig(
+ _BaseLicenseConfigServiceRestTransport._BaseRetractLicenseConfig,
+ LicenseConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("LicenseConfigServiceRestTransport.RetractLicenseConfig")
+
+ @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: license_config_service.RetractLicenseConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> license_config_service.RetractLicenseConfigResponse:
+ r"""Call the retract license config method over HTTP.
+
+ Args:
+ request (~.license_config_service.RetractLicenseConfigRequest):
+ The request object. Request message for
+ [LicenseConfigService.RetractLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig]
+ 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:
+ ~.license_config_service.RetractLicenseConfigResponse:
+ Response message for
+ [LicenseConfigService.RetractLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig]
+ method.
+
+ """
+
+ http_options = _BaseLicenseConfigServiceRestTransport._BaseRetractLicenseConfig._get_http_options()
+ request, metadata = self._interceptor.pre_retract_license_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseLicenseConfigServiceRestTransport._BaseRetractLicenseConfig,
+ "_BaseRetractLicenseConfig__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.LicenseConfigServiceClient.RetractLicenseConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "RetractLicenseConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ LicenseConfigServiceRestTransport._RetractLicenseConfig._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 = license_config_service.RetractLicenseConfigResponse()
+ pb_resp = license_config_service.RetractLicenseConfigResponse.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_retract_license_config(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_retract_license_config_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = (
+ license_config_service.RetractLicenseConfigResponse.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.LicenseConfigServiceClient.retract_license_config",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "RetractLicenseConfig",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _UpdateLicenseConfig(
+ _BaseLicenseConfigServiceRestTransport._BaseUpdateLicenseConfig,
+ LicenseConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("LicenseConfigServiceRestTransport.UpdateLicenseConfig")
+
+ @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: license_config_service.UpdateLicenseConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> gcd_license_config.LicenseConfig:
+ r"""Call the update license config method over HTTP.
+
+ Args:
+ request (~.license_config_service.UpdateLicenseConfigRequest):
+ The request object. Request message for
+ [LicenseConfigService.UpdateLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.UpdateLicenseConfig]
+ 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:
+ ~.gcd_license_config.LicenseConfig:
+ Information about users' licenses.
+ """
+
+ http_options = _BaseLicenseConfigServiceRestTransport._BaseUpdateLicenseConfig._get_http_options()
+ request, metadata = self._interceptor.pre_update_license_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseLicenseConfigServiceRestTransport._BaseUpdateLicenseConfig,
+ "_BaseUpdateLicenseConfig__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.LicenseConfigServiceClient.UpdateLicenseConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "UpdateLicenseConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ LicenseConfigServiceRestTransport._UpdateLicenseConfig._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 = gcd_license_config.LicenseConfig()
+ pb_resp = gcd_license_config.LicenseConfig.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_update_license_config(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_update_license_config_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = gcd_license_config.LicenseConfig.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.LicenseConfigServiceClient.update_license_config",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "UpdateLicenseConfig",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ @property
+ def create_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.CreateLicenseConfigRequest],
+ gcd_license_config.LicenseConfig,
+ ]:
+ # 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._CreateLicenseConfig(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def distribute_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.DistributeLicenseConfigRequest],
+ license_config_service.DistributeLicenseConfigResponse,
+ ]:
+ # 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._DistributeLicenseConfig(
+ self._session, self._host, self._interceptor
+ ) # type: ignore
+
+ @property
+ def get_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.GetLicenseConfigRequest], license_config.LicenseConfig
+ ]:
+ # 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._GetLicenseConfig(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def list_license_configs(
+ self,
+ ) -> Callable[
+ [license_config_service.ListLicenseConfigsRequest],
+ license_config_service.ListLicenseConfigsResponse,
+ ]:
+ # 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._ListLicenseConfigs(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def retract_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.RetractLicenseConfigRequest],
+ license_config_service.RetractLicenseConfigResponse,
+ ]:
+ # 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._RetractLicenseConfig(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def update_license_config(
+ self,
+ ) -> Callable[
+ [license_config_service.UpdateLicenseConfigRequest],
+ gcd_license_config.LicenseConfig,
+ ]:
+ # 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._UpdateLicenseConfig(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(
+ _BaseLicenseConfigServiceRestTransport._BaseCancelOperation,
+ LicenseConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("LicenseConfigServiceRestTransport.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 = _BaseLicenseConfigServiceRestTransport._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(
+ _BaseLicenseConfigServiceRestTransport._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.LicenseConfigServiceClient.CancelOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "CancelOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = LicenseConfigServiceRestTransport._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(
+ _BaseLicenseConfigServiceRestTransport._BaseGetOperation,
+ LicenseConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("LicenseConfigServiceRestTransport.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 = _BaseLicenseConfigServiceRestTransport._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(
+ _BaseLicenseConfigServiceRestTransport._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.LicenseConfigServiceClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "GetOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = LicenseConfigServiceRestTransport._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.LicenseConfigServiceAsyncClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "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(
+ _BaseLicenseConfigServiceRestTransport._BaseListOperations,
+ LicenseConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("LicenseConfigServiceRestTransport.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 = _BaseLicenseConfigServiceRestTransport._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(
+ _BaseLicenseConfigServiceRestTransport._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.LicenseConfigServiceClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "rpcName": "ListOperations",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = LicenseConfigServiceRestTransport._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.LicenseConfigServiceAsyncClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "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__ = ("LicenseConfigServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/rest_base.py
new file mode 100644
index 000000000000..68d03ed78f73
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/license_config_service/transports/rest_base.py
@@ -0,0 +1,376 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 license_config, license_config_service
+from google.cloud.discoveryengine_v1.types import license_config as gcd_license_config
+
+from .base import DEFAULT_CLIENT_INFO, LicenseConfigServiceTransport
+
+
+class _BaseLicenseConfigServiceRestTransport(LicenseConfigServiceTransport):
+ """Base REST backend transport for LicenseConfigService.
+
+ 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 _BaseCreateLicenseConfig:
+ 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/*}/licenseConfigs",
+ "body": "license_config",
+ },
+ ]
+ return http_options
+
+ class _BaseDistributeLicenseConfig:
+ 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/{billing_account_license_config=billingAccounts/*/billingAccountLicenseConfigs/*}:distributeLicenseConfig",
+ "body": "*",
+ },
+ ]
+ return http_options
+
+ class _BaseGetLicenseConfig:
+ 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/*/licenseConfigs/*}",
+ },
+ ]
+ return http_options
+
+ class _BaseListLicenseConfigs:
+ 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/*}/licenseConfigs",
+ },
+ ]
+ return http_options
+
+ class _BaseRetractLicenseConfig:
+ 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/{billing_account_license_config=billingAccounts/*/billingAccountLicenseConfigs/*}:retractLicenseConfig",
+ "body": "*",
+ },
+ ]
+ return http_options
+
+ class _BaseUpdateLicenseConfig:
+ 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/{license_config.name=projects/*/locations/*/licenseConfigs/*}",
+ "body": "license_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__ = ("_BaseLicenseConfigServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/async_client.py
index c1b3cc4445f2..a8a7a028547e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/async_client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/async_client.py
@@ -79,8 +79,14 @@ class ProjectServiceAsyncClient:
_DEFAULT_ENDPOINT_TEMPLATE = ProjectServiceClient._DEFAULT_ENDPOINT_TEMPLATE
_DEFAULT_UNIVERSE = ProjectServiceClient._DEFAULT_UNIVERSE
+ content_policy_path = staticmethod(ProjectServiceClient.content_policy_path)
+ parse_content_policy_path = staticmethod(
+ ProjectServiceClient.parse_content_policy_path
+ )
project_path = staticmethod(ProjectServiceClient.project_path)
parse_project_path = staticmethod(ProjectServiceClient.parse_project_path)
+ template_path = staticmethod(ProjectServiceClient.template_path)
+ parse_template_path = staticmethod(ProjectServiceClient.parse_template_path)
common_billing_account_path = staticmethod(
ProjectServiceClient.common_billing_account_path
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/client.py
index b820fb1a4f21..bb46b889f1cb 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/client.py
@@ -175,6 +175,28 @@ def transport(self) -> ProjectServiceTransport:
"""
return self._transport
+ @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 project_path(
project: str,
@@ -190,6 +212,28 @@ def parse_project_path(path: str) -> Dict[str, str]:
m = re.match(r"^projects/(?P.+?)$", path)
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.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
@staticmethod
def common_billing_account_path(
billing_account: str,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/base.py
index 34cffebc64e9..6ec5a3acb3e4 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/base.py
@@ -39,7 +39,11 @@
class ProjectServiceTransport(abc.ABC):
"""Abstract transport class for ProjectService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest.py
index 70d236af9334..c3fdc9329eed 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest.py
@@ -370,6 +370,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest_base.py
index 8914809bc1d3..74cdc3852573 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/project_service/transports/rest_base.py
@@ -103,6 +103,11 @@ def _get_http_options():
"uri": "/v1/{name=projects/*}:provision",
"body": "*",
},
+ {
+ "method": "post",
+ "uri": "/v1/{name=projects/*/locations/*}:provision",
+ "body": "*",
+ },
]
return http_options
@@ -175,6 +180,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/base.py
index 04a09a322880..753a86e64030 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/base.py
@@ -39,7 +39,11 @@
class RankServiceTransport(abc.ABC):
"""Abstract transport class for RankService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/rest_base.py
index bb5388eeebba..f9d4fe557073 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/rank_service/transports/rest_base.py
@@ -175,6 +175,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/base.py
index adb93bdef526..1883e8d9656e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/base.py
@@ -39,7 +39,11 @@
class RecommendationServiceTransport(abc.ABC):
"""Abstract transport class for RecommendationService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/rest_base.py
index 3636c2c17f6c..335601251f61 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/recommendation_service/transports/rest_base.py
@@ -185,6 +185,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py
index 7287b18c4ea0..21d6369d73ba 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/base.py
@@ -39,7 +39,11 @@
class SchemaServiceTransport(abc.ABC):
"""Abstract transport class for SchemaService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py
index 574276feef15..f2f2b4625854 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest.py
@@ -592,6 +592,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest_base.py
index d6af3671e332..093819f30c9f 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/schema_service/transports/rest_base.py
@@ -264,6 +264,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/rest_base.py
index 2f525f178772..73aed2996e9e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_service/transports/rest_base.py
@@ -212,6 +212,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/base.py
index 2ddd8c8e73b4..b01b6b4849aa 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/base.py
@@ -39,7 +39,11 @@
class SearchTuningServiceTransport(abc.ABC):
"""Abstract transport class for SearchTuningService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest.py
index c4d21c732e67..92d22400c6a1 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest.py
@@ -430,6 +430,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest_base.py
index bed6e8b595d6..b14a9dc39817 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/search_tuning_service/transports/rest_base.py
@@ -191,6 +191,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/async_client.py
index e2051db3b80d..0fae1057cd13 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/async_client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/async_client.py
@@ -49,7 +49,12 @@
from google.cloud.location import locations_pb2 # type: ignore
from google.longrunning import operations_pb2 # type: ignore
-from google.cloud.discoveryengine_v1.types import common, serving_config_service
+from google.cloud.discoveryengine_v1.services.serving_config_service import pagers
+from google.cloud.discoveryengine_v1.types import (
+ common,
+ serving_config,
+ serving_config_service,
+)
from google.cloud.discoveryengine_v1.types import serving_config as gcd_serving_config
from .client import ServingConfigServiceClient
@@ -308,6 +313,268 @@ def __init__(
},
)
+ async def create_serving_config(
+ self,
+ request: Optional[
+ Union[serving_config_service.CreateServingConfigRequest, dict]
+ ] = None,
+ *,
+ parent: Optional[str] = None,
+ serving_config: Optional[gcd_serving_config.ServingConfig] = None,
+ serving_config_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]]] = (),
+ ) -> gcd_serving_config.ServingConfig:
+ r"""Creates a ServingConfig.
+
+ Note: The Google Cloud console works only with the default
+ serving config. Additional ServingConfigs can be created and
+ managed only via the API.
+
+ A maximum of 100
+ [ServingConfig][google.cloud.discoveryengine.v1.ServingConfig]s
+ are allowed in an
+ [Engine][google.cloud.discoveryengine.v1.Engine], otherwise a
+ RESOURCE_EXHAUSTED error is returned.
+
+ .. 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_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ serving_config = discoveryengine_v1.ServingConfig()
+ serving_config.media_config.content_watched_percentage_threshold = 0.3811
+ serving_config.display_name = "display_name_value"
+ serving_config.solution_type = "SOLUTION_TYPE_AI_MODE"
+
+ request = discoveryengine_v1.CreateServingConfigRequest(
+ parent="parent_value",
+ serving_config=serving_config,
+ serving_config_id="serving_config_id_value",
+ )
+
+ # Make the request
+ response = await client.create_serving_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.CreateServingConfigRequest, dict]]):
+ The request object. Request for CreateServingConfig
+ method.
+ parent (:class:`str`):
+ Required. Full resource name of parent. 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.
+ serving_config (:class:`google.cloud.discoveryengine_v1.types.ServingConfig`):
+ Required. The ServingConfig to
+ create.
+
+ This corresponds to the ``serving_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ serving_config_id (:class:`str`):
+ Required. The ID to use for the ServingConfig, which
+ will become the final component of the ServingConfig's
+ resource name.
+
+ This value should be 4-63 characters, and valid
+ characters are /[a-zA-Z0-9][a-zA-Z0-9\_-]+/.
+
+ This corresponds to the ``serving_config_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.discoveryengine_v1.types.ServingConfig:
+ Configures metadata that is used to
+ generate serving time results (e.g.
+ search results or recommendation
+ predictions). The ServingConfig is
+ passed in the search and predict request
+ and generates results.
+
+ """
+ # 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, serving_config, serving_config_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, serving_config_service.CreateServingConfigRequest):
+ request = serving_config_service.CreateServingConfigRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if parent is not None:
+ request.parent = parent
+ if serving_config is not None:
+ request.serving_config = serving_config
+ if serving_config_id is not None:
+ request.serving_config_id = serving_config_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_serving_config
+ ]
+
+ # 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_serving_config(
+ self,
+ request: Optional[
+ Union[serving_config_service.DeleteServingConfigRequest, 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 a ServingConfig.
+
+ Returns a NOT_FOUND error if the ServingConfig does not exist.
+
+ .. 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_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteServingConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ await client.delete_serving_config(request=request)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.DeleteServingConfigRequest, dict]]):
+ The request object. Request for DeleteServingConfig
+ method.
+ name (:class:`str`):
+ Required. The resource name of the ServingConfig to
+ delete. Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_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`.
+ """
+ # 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, serving_config_service.DeleteServingConfigRequest):
+ request = serving_config_service.DeleteServingConfigRequest(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_serving_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.
+ await rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
async def update_serving_config(
self,
request: Optional[
@@ -343,7 +610,7 @@ async def sample_update_serving_config():
serving_config = discoveryengine_v1.ServingConfig()
serving_config.media_config.content_watched_percentage_threshold = 0.3811
serving_config.display_name = "display_name_value"
- serving_config.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ serving_config.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateServingConfigRequest(
serving_config=serving_config,
@@ -449,6 +716,255 @@ async def sample_update_serving_config():
# Done; return the response.
return response
+ async def get_serving_config(
+ self,
+ request: Optional[
+ Union[serving_config_service.GetServingConfigRequest, 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]]] = (),
+ ) -> serving_config.ServingConfig:
+ r"""Gets a ServingConfig.
+
+ Returns a NotFound error if the ServingConfig does not
+ exist.
+
+ .. 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_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetServingConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_serving_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.GetServingConfigRequest, dict]]):
+ The request object. Request for GetServingConfig method.
+ name (:class:`str`):
+ Required. The resource name of the ServingConfig to get.
+ Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_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.discoveryengine_v1.types.ServingConfig:
+ Configures metadata that is used to
+ generate serving time results (e.g.
+ search results or recommendation
+ predictions). The ServingConfig is
+ passed in the search and predict request
+ and generates results.
+
+ """
+ # 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, serving_config_service.GetServingConfigRequest):
+ request = serving_config_service.GetServingConfigRequest(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_serving_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_serving_configs(
+ self,
+ request: Optional[
+ Union[serving_config_service.ListServingConfigsRequest, 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.ListServingConfigsAsyncPager:
+ r"""Lists all ServingConfigs linked to this dataStore.
+
+ .. 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_serving_configs():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListServingConfigsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_serving_configs(request=request)
+
+ # Handle the response
+ async for response in page_result:
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.ListServingConfigsRequest, dict]]):
+ The request object. Request for ListServingConfigs
+ method.
+ parent (:class:`str`):
+ Required. Full resource name of the parent resource.
+ 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.serving_config_service.pagers.ListServingConfigsAsyncPager:
+ Response for ListServingConfigs
+ 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, serving_config_service.ListServingConfigsRequest):
+ request = serving_config_service.ListServingConfigsRequest(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_serving_configs
+ ]
+
+ # 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.ListServingConfigsAsyncPager(
+ 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/serving_config_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/client.py
index d4e80fa1abfb..20ba07d43f2a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/client.py
@@ -73,7 +73,12 @@
from google.cloud.location import locations_pb2 # type: ignore
from google.longrunning import operations_pb2 # type: ignore
-from google.cloud.discoveryengine_v1.types import common, serving_config_service
+from google.cloud.discoveryengine_v1.services.serving_config_service import pagers
+from google.cloud.discoveryengine_v1.types import (
+ common,
+ serving_config,
+ serving_config_service,
+)
from google.cloud.discoveryengine_v1.types import serving_config as gcd_serving_config
from .transports.base import DEFAULT_CLIENT_INFO, ServingConfigServiceTransport
@@ -604,6 +609,262 @@ def __init__(
},
)
+ def create_serving_config(
+ self,
+ request: Optional[
+ Union[serving_config_service.CreateServingConfigRequest, dict]
+ ] = None,
+ *,
+ parent: Optional[str] = None,
+ serving_config: Optional[gcd_serving_config.ServingConfig] = None,
+ serving_config_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]]] = (),
+ ) -> gcd_serving_config.ServingConfig:
+ r"""Creates a ServingConfig.
+
+ Note: The Google Cloud console works only with the default
+ serving config. Additional ServingConfigs can be created and
+ managed only via the API.
+
+ A maximum of 100
+ [ServingConfig][google.cloud.discoveryengine.v1.ServingConfig]s
+ are allowed in an
+ [Engine][google.cloud.discoveryengine.v1.Engine], otherwise a
+ RESOURCE_EXHAUSTED error is returned.
+
+ .. 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_create_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceClient()
+
+ # Initialize request argument(s)
+ serving_config = discoveryengine_v1.ServingConfig()
+ serving_config.media_config.content_watched_percentage_threshold = 0.3811
+ serving_config.display_name = "display_name_value"
+ serving_config.solution_type = "SOLUTION_TYPE_AI_MODE"
+
+ request = discoveryengine_v1.CreateServingConfigRequest(
+ parent="parent_value",
+ serving_config=serving_config,
+ serving_config_id="serving_config_id_value",
+ )
+
+ # Make the request
+ response = client.create_serving_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.CreateServingConfigRequest, dict]):
+ The request object. Request for CreateServingConfig
+ method.
+ parent (str):
+ Required. Full resource name of parent. 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.
+ serving_config (google.cloud.discoveryengine_v1.types.ServingConfig):
+ Required. The ServingConfig to
+ create.
+
+ This corresponds to the ``serving_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ serving_config_id (str):
+ Required. The ID to use for the ServingConfig, which
+ will become the final component of the ServingConfig's
+ resource name.
+
+ This value should be 4-63 characters, and valid
+ characters are /[a-zA-Z0-9][a-zA-Z0-9\_-]+/.
+
+ This corresponds to the ``serving_config_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.discoveryengine_v1.types.ServingConfig:
+ Configures metadata that is used to
+ generate serving time results (e.g.
+ search results or recommendation
+ predictions). The ServingConfig is
+ passed in the search and predict request
+ and generates results.
+
+ """
+ # 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, serving_config, serving_config_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, serving_config_service.CreateServingConfigRequest):
+ request = serving_config_service.CreateServingConfigRequest(request)
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if parent is not None:
+ request.parent = parent
+ if serving_config is not None:
+ request.serving_config = serving_config
+ if serving_config_id is not None:
+ request.serving_config_id = serving_config_id
+
+ # Wrap the RPC method; this adds retry and timeout information,
+ # and friendly error handling.
+ rpc = self._transport._wrapped_methods[self._transport.create_serving_config]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Validate the universe domain.
+ self._validate_universe_domain()
+
+ # Send the request.
+ response = rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
+ def delete_serving_config(
+ self,
+ request: Optional[
+ Union[serving_config_service.DeleteServingConfigRequest, 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 a ServingConfig.
+
+ Returns a NOT_FOUND error if the ServingConfig does not exist.
+
+ .. 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_delete_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteServingConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ client.delete_serving_config(request=request)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.DeleteServingConfigRequest, dict]):
+ The request object. Request for DeleteServingConfig
+ method.
+ name (str):
+ Required. The resource name of the ServingConfig to
+ delete. Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_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`.
+ """
+ # 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, serving_config_service.DeleteServingConfigRequest):
+ request = serving_config_service.DeleteServingConfigRequest(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_serving_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.
+ rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
def update_serving_config(
self,
request: Optional[
@@ -639,7 +900,7 @@ def sample_update_serving_config():
serving_config = discoveryengine_v1.ServingConfig()
serving_config.media_config.content_watched_percentage_threshold = 0.3811
serving_config.display_name = "display_name_value"
- serving_config.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ serving_config.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateServingConfigRequest(
serving_config=serving_config,
@@ -742,6 +1003,249 @@ def sample_update_serving_config():
# Done; return the response.
return response
+ def get_serving_config(
+ self,
+ request: Optional[
+ Union[serving_config_service.GetServingConfigRequest, 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]]] = (),
+ ) -> serving_config.ServingConfig:
+ r"""Gets a ServingConfig.
+
+ Returns a NotFound error if the ServingConfig does not
+ exist.
+
+ .. 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_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetServingConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_serving_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.GetServingConfigRequest, dict]):
+ The request object. Request for GetServingConfig method.
+ name (str):
+ Required. The resource name of the ServingConfig to get.
+ Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_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.discoveryengine_v1.types.ServingConfig:
+ Configures metadata that is used to
+ generate serving time results (e.g.
+ search results or recommendation
+ predictions). The ServingConfig is
+ passed in the search and predict request
+ and generates results.
+
+ """
+ # 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, serving_config_service.GetServingConfigRequest):
+ request = serving_config_service.GetServingConfigRequest(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_serving_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 list_serving_configs(
+ self,
+ request: Optional[
+ Union[serving_config_service.ListServingConfigsRequest, 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.ListServingConfigsPager:
+ r"""Lists all ServingConfigs linked to this dataStore.
+
+ .. 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_list_serving_configs():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListServingConfigsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_serving_configs(request=request)
+
+ # Handle the response
+ for response in page_result:
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.ListServingConfigsRequest, dict]):
+ The request object. Request for ListServingConfigs
+ method.
+ parent (str):
+ Required. Full resource name of the parent resource.
+ 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.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each 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.serving_config_service.pagers.ListServingConfigsPager:
+ Response for ListServingConfigs
+ 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, serving_config_service.ListServingConfigsRequest):
+ request = serving_config_service.ListServingConfigsRequest(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_serving_configs]
+
+ # 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.ListServingConfigsPager(
+ method=rpc,
+ request=request,
+ response=response,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
def __enter__(self) -> "ServingConfigServiceClient":
return self
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/pagers.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/pagers.py
new file mode 100644
index 000000000000..cd38614a38fe
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/pagers.py
@@ -0,0 +1,201 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from typing import (
+ Any,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Iterator,
+ Optional,
+ Sequence,
+ Tuple,
+ Union,
+)
+
+from google.api_core import gapic_v1
+from google.api_core import retry as retries
+from google.api_core import retry_async as retries_async
+
+try:
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
+ OptionalAsyncRetry = Union[
+ retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None
+ ]
+except AttributeError: # pragma: NO COVER
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+ OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore
+
+from google.cloud.discoveryengine_v1.types import serving_config, serving_config_service
+
+
+class ListServingConfigsPager:
+ """A pager for iterating through ``list_serving_configs`` requests.
+
+ This class thinly wraps an initial
+ :class:`google.cloud.discoveryengine_v1.types.ListServingConfigsResponse` object, and
+ provides an ``__iter__`` method to iterate through its
+ ``serving_configs`` field.
+
+ If there are more pages, the ``__iter__`` method will make additional
+ ``ListServingConfigs`` requests and continue to iterate
+ through the ``serving_configs`` field on the
+ corresponding responses.
+
+ All the usual :class:`google.cloud.discoveryengine_v1.types.ListServingConfigsResponse`
+ 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[..., serving_config_service.ListServingConfigsResponse],
+ request: serving_config_service.ListServingConfigsRequest,
+ response: serving_config_service.ListServingConfigsResponse,
+ *,
+ 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.discoveryengine_v1.types.ListServingConfigsRequest):
+ The initial request object.
+ response (google.cloud.discoveryengine_v1.types.ListServingConfigsResponse):
+ 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 = serving_config_service.ListServingConfigsRequest(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[serving_config_service.ListServingConfigsResponse]:
+ 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[serving_config.ServingConfig]:
+ for page in self.pages:
+ yield from page.serving_configs
+
+ def __repr__(self) -> str:
+ return "{0}<{1!r}>".format(self.__class__.__name__, self._response)
+
+
+class ListServingConfigsAsyncPager:
+ """A pager for iterating through ``list_serving_configs`` requests.
+
+ This class thinly wraps an initial
+ :class:`google.cloud.discoveryengine_v1.types.ListServingConfigsResponse` object, and
+ provides an ``__aiter__`` method to iterate through its
+ ``serving_configs`` field.
+
+ If there are more pages, the ``__aiter__`` method will make additional
+ ``ListServingConfigs`` requests and continue to iterate
+ through the ``serving_configs`` field on the
+ corresponding responses.
+
+ All the usual :class:`google.cloud.discoveryengine_v1.types.ListServingConfigsResponse`
+ 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[serving_config_service.ListServingConfigsResponse]
+ ],
+ request: serving_config_service.ListServingConfigsRequest,
+ response: serving_config_service.ListServingConfigsResponse,
+ *,
+ 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.discoveryengine_v1.types.ListServingConfigsRequest):
+ The initial request object.
+ response (google.cloud.discoveryengine_v1.types.ListServingConfigsResponse):
+ 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 = serving_config_service.ListServingConfigsRequest(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[serving_config_service.ListServingConfigsResponse]:
+ 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[serving_config.ServingConfig]:
+ async def async_generator():
+ async for page in self.pages:
+ for response in page.serving_configs:
+ 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-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/base.py
index d3b4ba834ef4..e02b1a5a1434 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/base.py
@@ -19,6 +19,7 @@
import google.api_core
import google.auth # type: ignore
import google.protobuf
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
@@ -28,8 +29,8 @@
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 serving_config, serving_config_service
from google.cloud.discoveryengine_v1.types import serving_config as gcd_serving_config
-from google.cloud.discoveryengine_v1.types import serving_config_service
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=package_version.__version__
@@ -40,7 +41,11 @@
class ServingConfigServiceTransport(abc.ABC):
"""Abstract transport class for ServingConfigService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
@@ -143,11 +148,31 @@ def host(self):
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
+ self.create_serving_config: gapic_v1.method.wrap_method(
+ self.create_serving_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.delete_serving_config: gapic_v1.method.wrap_method(
+ self.delete_serving_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.update_serving_config: gapic_v1.method.wrap_method(
self.update_serving_config,
default_timeout=None,
client_info=client_info,
),
+ self.get_serving_config: gapic_v1.method.wrap_method(
+ self.get_serving_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.list_serving_configs: gapic_v1.method.wrap_method(
+ self.list_serving_configs,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.cancel_operation: gapic_v1.method.wrap_method(
self.cancel_operation,
default_timeout=None,
@@ -174,6 +199,27 @@ def close(self):
"""
raise NotImplementedError()
+ @property
+ def create_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.CreateServingConfigRequest],
+ Union[
+ gcd_serving_config.ServingConfig,
+ Awaitable[gcd_serving_config.ServingConfig],
+ ],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def delete_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.DeleteServingConfigRequest],
+ Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
+ ]:
+ raise NotImplementedError()
+
@property
def update_serving_config(
self,
@@ -186,6 +232,27 @@ def update_serving_config(
]:
raise NotImplementedError()
+ @property
+ def get_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.GetServingConfigRequest],
+ Union[serving_config.ServingConfig, Awaitable[serving_config.ServingConfig]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def list_serving_configs(
+ self,
+ ) -> Callable[
+ [serving_config_service.ListServingConfigsRequest],
+ Union[
+ serving_config_service.ListServingConfigsResponse,
+ Awaitable[serving_config_service.ListServingConfigsResponse],
+ ],
+ ]:
+ raise NotImplementedError()
+
@property
def list_operations(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/grpc.py
index 6252073b2297..d6ab0c392acf 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/grpc.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/grpc.py
@@ -20,6 +20,7 @@
from typing import Callable, Dict, Optional, Sequence, Tuple, Union
import google.auth # type: ignore
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
@@ -30,8 +31,8 @@
from google.longrunning import operations_pb2 # type: ignore
from google.protobuf.json_format import MessageToJson
+from google.cloud.discoveryengine_v1.types import serving_config, serving_config_service
from google.cloud.discoveryengine_v1.types import serving_config as gcd_serving_config
-from google.cloud.discoveryengine_v1.types import serving_config_service
from .base import DEFAULT_CLIENT_INFO, ServingConfigServiceTransport
@@ -329,6 +330,73 @@ def grpc_channel(self) -> grpc.Channel:
"""Return the channel designed to connect to this service."""
return self._grpc_channel
+ @property
+ def create_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.CreateServingConfigRequest],
+ gcd_serving_config.ServingConfig,
+ ]:
+ r"""Return a callable for the create serving config method over gRPC.
+
+ Creates a ServingConfig.
+
+ Note: The Google Cloud console works only with the default
+ serving config. Additional ServingConfigs can be created and
+ managed only via the API.
+
+ A maximum of 100
+ [ServingConfig][google.cloud.discoveryengine.v1.ServingConfig]s
+ are allowed in an
+ [Engine][google.cloud.discoveryengine.v1.Engine], otherwise a
+ RESOURCE_EXHAUSTED error is returned.
+
+ Returns:
+ Callable[[~.CreateServingConfigRequest],
+ ~.ServingConfig]:
+ 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_serving_config" not in self._stubs:
+ self._stubs["create_serving_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.ServingConfigService/CreateServingConfig",
+ request_serializer=serving_config_service.CreateServingConfigRequest.serialize,
+ response_deserializer=gcd_serving_config.ServingConfig.deserialize,
+ )
+ return self._stubs["create_serving_config"]
+
+ @property
+ def delete_serving_config(
+ self,
+ ) -> Callable[[serving_config_service.DeleteServingConfigRequest], empty_pb2.Empty]:
+ r"""Return a callable for the delete serving config method over gRPC.
+
+ Deletes a ServingConfig.
+
+ Returns a NOT_FOUND error if the ServingConfig does not exist.
+
+ Returns:
+ Callable[[~.DeleteServingConfigRequest],
+ ~.Empty]:
+ 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_serving_config" not in self._stubs:
+ self._stubs["delete_serving_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.ServingConfigService/DeleteServingConfig",
+ request_serializer=serving_config_service.DeleteServingConfigRequest.serialize,
+ response_deserializer=empty_pb2.Empty.FromString,
+ )
+ return self._stubs["delete_serving_config"]
+
@property
def update_serving_config(
self,
@@ -360,6 +428,66 @@ def update_serving_config(
)
return self._stubs["update_serving_config"]
+ @property
+ def get_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.GetServingConfigRequest], serving_config.ServingConfig
+ ]:
+ r"""Return a callable for the get serving config method over gRPC.
+
+ Gets a ServingConfig.
+
+ Returns a NotFound error if the ServingConfig does not
+ exist.
+
+ Returns:
+ Callable[[~.GetServingConfigRequest],
+ ~.ServingConfig]:
+ 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_serving_config" not in self._stubs:
+ self._stubs["get_serving_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.ServingConfigService/GetServingConfig",
+ request_serializer=serving_config_service.GetServingConfigRequest.serialize,
+ response_deserializer=serving_config.ServingConfig.deserialize,
+ )
+ return self._stubs["get_serving_config"]
+
+ @property
+ def list_serving_configs(
+ self,
+ ) -> Callable[
+ [serving_config_service.ListServingConfigsRequest],
+ serving_config_service.ListServingConfigsResponse,
+ ]:
+ r"""Return a callable for the list serving configs method over gRPC.
+
+ Lists all ServingConfigs linked to this dataStore.
+
+ Returns:
+ Callable[[~.ListServingConfigsRequest],
+ ~.ListServingConfigsResponse]:
+ 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_serving_configs" not in self._stubs:
+ self._stubs["list_serving_configs"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.ServingConfigService/ListServingConfigs",
+ request_serializer=serving_config_service.ListServingConfigsRequest.serialize,
+ response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize,
+ )
+ return self._stubs["list_serving_configs"]
+
def close(self):
self._logged_channel.close()
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/grpc_asyncio.py
index 10d0c8e99a73..10ed7bea7536 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/grpc_asyncio.py
@@ -20,6 +20,7 @@
import warnings
from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
import google.protobuf.message
import grpc # type: ignore
import proto # type: ignore
@@ -33,8 +34,8 @@
from google.protobuf.json_format import MessageToJson
from grpc.experimental import aio # type: ignore
+from google.cloud.discoveryengine_v1.types import serving_config, serving_config_service
from google.cloud.discoveryengine_v1.types import serving_config as gcd_serving_config
-from google.cloud.discoveryengine_v1.types import serving_config_service
from .base import DEFAULT_CLIENT_INFO, ServingConfigServiceTransport
from .grpc import ServingConfigServiceGrpcTransport
@@ -337,6 +338,75 @@ def grpc_channel(self) -> aio.Channel:
# Return the channel from cache.
return self._grpc_channel
+ @property
+ def create_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.CreateServingConfigRequest],
+ Awaitable[gcd_serving_config.ServingConfig],
+ ]:
+ r"""Return a callable for the create serving config method over gRPC.
+
+ Creates a ServingConfig.
+
+ Note: The Google Cloud console works only with the default
+ serving config. Additional ServingConfigs can be created and
+ managed only via the API.
+
+ A maximum of 100
+ [ServingConfig][google.cloud.discoveryengine.v1.ServingConfig]s
+ are allowed in an
+ [Engine][google.cloud.discoveryengine.v1.Engine], otherwise a
+ RESOURCE_EXHAUSTED error is returned.
+
+ Returns:
+ Callable[[~.CreateServingConfigRequest],
+ Awaitable[~.ServingConfig]]:
+ 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_serving_config" not in self._stubs:
+ self._stubs["create_serving_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.ServingConfigService/CreateServingConfig",
+ request_serializer=serving_config_service.CreateServingConfigRequest.serialize,
+ response_deserializer=gcd_serving_config.ServingConfig.deserialize,
+ )
+ return self._stubs["create_serving_config"]
+
+ @property
+ def delete_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.DeleteServingConfigRequest], Awaitable[empty_pb2.Empty]
+ ]:
+ r"""Return a callable for the delete serving config method over gRPC.
+
+ Deletes a ServingConfig.
+
+ Returns a NOT_FOUND error if the ServingConfig does not exist.
+
+ Returns:
+ Callable[[~.DeleteServingConfigRequest],
+ Awaitable[~.Empty]]:
+ 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_serving_config" not in self._stubs:
+ self._stubs["delete_serving_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.ServingConfigService/DeleteServingConfig",
+ request_serializer=serving_config_service.DeleteServingConfigRequest.serialize,
+ response_deserializer=empty_pb2.Empty.FromString,
+ )
+ return self._stubs["delete_serving_config"]
+
@property
def update_serving_config(
self,
@@ -368,14 +438,95 @@ def update_serving_config(
)
return self._stubs["update_serving_config"]
+ @property
+ def get_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.GetServingConfigRequest],
+ Awaitable[serving_config.ServingConfig],
+ ]:
+ r"""Return a callable for the get serving config method over gRPC.
+
+ Gets a ServingConfig.
+
+ Returns a NotFound error if the ServingConfig does not
+ exist.
+
+ Returns:
+ Callable[[~.GetServingConfigRequest],
+ Awaitable[~.ServingConfig]]:
+ 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_serving_config" not in self._stubs:
+ self._stubs["get_serving_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.ServingConfigService/GetServingConfig",
+ request_serializer=serving_config_service.GetServingConfigRequest.serialize,
+ response_deserializer=serving_config.ServingConfig.deserialize,
+ )
+ return self._stubs["get_serving_config"]
+
+ @property
+ def list_serving_configs(
+ self,
+ ) -> Callable[
+ [serving_config_service.ListServingConfigsRequest],
+ Awaitable[serving_config_service.ListServingConfigsResponse],
+ ]:
+ r"""Return a callable for the list serving configs method over gRPC.
+
+ Lists all ServingConfigs linked to this dataStore.
+
+ Returns:
+ Callable[[~.ListServingConfigsRequest],
+ Awaitable[~.ListServingConfigsResponse]]:
+ 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_serving_configs" not in self._stubs:
+ self._stubs["list_serving_configs"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.ServingConfigService/ListServingConfigs",
+ request_serializer=serving_config_service.ListServingConfigsRequest.serialize,
+ response_deserializer=serving_config_service.ListServingConfigsResponse.deserialize,
+ )
+ return self._stubs["list_serving_configs"]
+
def _prep_wrapped_messages(self, client_info):
"""Precompute the wrapped methods, overriding the base class method to use async wrappers."""
self._wrapped_methods = {
+ self.create_serving_config: self._wrap_method(
+ self.create_serving_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.delete_serving_config: self._wrap_method(
+ self.delete_serving_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.update_serving_config: self._wrap_method(
self.update_serving_config,
default_timeout=None,
client_info=client_info,
),
+ self.get_serving_config: self._wrap_method(
+ self.get_serving_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.list_serving_configs: self._wrap_method(
+ self.list_serving_configs,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.cancel_operation: self._wrap_method(
self.cancel_operation,
default_timeout=None,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/rest.py
index 3b53bec98a23..c9fa5788b5cf 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/rest.py
@@ -20,6 +20,7 @@
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import google.protobuf
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
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
@@ -31,8 +32,8 @@
from requests import __version__ as requests_version
from google.cloud.discoveryengine_v1._compat import transcode_request
+from google.cloud.discoveryengine_v1.types import serving_config, serving_config_service
from google.cloud.discoveryengine_v1.types import serving_config as gcd_serving_config
-from google.cloud.discoveryengine_v1.types import serving_config_service
from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
from .rest_base import _BaseServingConfigServiceRestTransport
@@ -75,6 +76,34 @@ class ServingConfigServiceRestInterceptor:
.. code-block:: python
class MyCustomServingConfigServiceInterceptor(ServingConfigServiceRestInterceptor):
+ def pre_create_serving_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_create_serving_config(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_delete_serving_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def pre_get_serving_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_get_serving_config(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_list_serving_configs(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_list_serving_configs(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
def pre_update_serving_config(self, request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
@@ -89,6 +118,173 @@ def post_update_serving_config(self, response):
"""
+ def pre_create_serving_config(
+ self,
+ request: serving_config_service.CreateServingConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ serving_config_service.CreateServingConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for create_serving_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the ServingConfigService server.
+ """
+ return request, metadata
+
+ def post_create_serving_config(
+ self, response: gcd_serving_config.ServingConfig
+ ) -> gcd_serving_config.ServingConfig:
+ """Post-rpc interceptor for create_serving_config
+
+ DEPRECATED. Please use the `post_create_serving_config_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the ServingConfigService server but before
+ it is returned to user code. This `post_create_serving_config` interceptor runs
+ before the `post_create_serving_config_with_metadata` interceptor.
+ """
+ return response
+
+ def post_create_serving_config_with_metadata(
+ self,
+ response: gcd_serving_config.ServingConfig,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ gcd_serving_config.ServingConfig, Sequence[Tuple[str, Union[str, bytes]]]
+ ]:
+ """Post-rpc interceptor for create_serving_config
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the ServingConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_create_serving_config_with_metadata`
+ interceptor in new development instead of the `post_create_serving_config` interceptor.
+ When both interceptors are used, this `post_create_serving_config_with_metadata` interceptor runs after the
+ `post_create_serving_config` interceptor. The (possibly modified) response returned by
+ `post_create_serving_config` will be passed to
+ `post_create_serving_config_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_delete_serving_config(
+ self,
+ request: serving_config_service.DeleteServingConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ serving_config_service.DeleteServingConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for delete_serving_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the ServingConfigService server.
+ """
+ return request, metadata
+
+ def pre_get_serving_config(
+ self,
+ request: serving_config_service.GetServingConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ serving_config_service.GetServingConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for get_serving_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the ServingConfigService server.
+ """
+ return request, metadata
+
+ def post_get_serving_config(
+ self, response: serving_config.ServingConfig
+ ) -> serving_config.ServingConfig:
+ """Post-rpc interceptor for get_serving_config
+
+ DEPRECATED. Please use the `post_get_serving_config_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the ServingConfigService server but before
+ it is returned to user code. This `post_get_serving_config` interceptor runs
+ before the `post_get_serving_config_with_metadata` interceptor.
+ """
+ return response
+
+ def post_get_serving_config_with_metadata(
+ self,
+ response: serving_config.ServingConfig,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[serving_config.ServingConfig, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for get_serving_config
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the ServingConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_get_serving_config_with_metadata`
+ interceptor in new development instead of the `post_get_serving_config` interceptor.
+ When both interceptors are used, this `post_get_serving_config_with_metadata` interceptor runs after the
+ `post_get_serving_config` interceptor. The (possibly modified) response returned by
+ `post_get_serving_config` will be passed to
+ `post_get_serving_config_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_list_serving_configs(
+ self,
+ request: serving_config_service.ListServingConfigsRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ serving_config_service.ListServingConfigsRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for list_serving_configs
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the ServingConfigService server.
+ """
+ return request, metadata
+
+ def post_list_serving_configs(
+ self, response: serving_config_service.ListServingConfigsResponse
+ ) -> serving_config_service.ListServingConfigsResponse:
+ """Post-rpc interceptor for list_serving_configs
+
+ DEPRECATED. Please use the `post_list_serving_configs_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the ServingConfigService server but before
+ it is returned to user code. This `post_list_serving_configs` interceptor runs
+ before the `post_list_serving_configs_with_metadata` interceptor.
+ """
+ return response
+
+ def post_list_serving_configs_with_metadata(
+ self,
+ response: serving_config_service.ListServingConfigsResponse,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ serving_config_service.ListServingConfigsResponse,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Post-rpc interceptor for list_serving_configs
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the ServingConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_list_serving_configs_with_metadata`
+ interceptor in new development instead of the `post_list_serving_configs` interceptor.
+ When both interceptors are used, this `post_list_serving_configs_with_metadata` interceptor runs after the
+ `post_list_serving_configs` interceptor. The (possibly modified) response returned by
+ `post_list_serving_configs` will be passed to
+ `post_list_serving_configs_with_metadata`.
+ """
+ return response, metadata
+
def pre_update_serving_config(
self,
request: serving_config_service.UpdateServingConfigRequest,
@@ -308,12 +504,12 @@ def __init__(
self._interceptor = interceptor or ServingConfigServiceRestInterceptor()
self._prep_wrapped_messages(client_info)
- class _UpdateServingConfig(
- _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig,
+ class _CreateServingConfig(
+ _BaseServingConfigServiceRestTransport._BaseCreateServingConfig,
ServingConfigServiceRestStub,
):
def __hash__(self):
- return hash("ServingConfigServiceRestTransport.UpdateServingConfig")
+ return hash("ServingConfigServiceRestTransport.CreateServingConfig")
@staticmethod
def _get_response(
@@ -340,17 +536,17 @@ def _get_response(
def __call__(
self,
- request: serving_config_service.UpdateServingConfigRequest,
+ request: serving_config_service.CreateServingConfigRequest,
*,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Optional[float] = None,
metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
) -> gcd_serving_config.ServingConfig:
- r"""Call the update serving config method over HTTP.
+ r"""Call the create serving config method over HTTP.
Args:
- request (~.serving_config_service.UpdateServingConfigRequest):
- The request object. Request for UpdateServingConfig
+ request (~.serving_config_service.CreateServingConfigRequest):
+ The request object. Request for CreateServingConfig
method.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
@@ -371,16 +567,16 @@ def __call__(
"""
- http_options = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_http_options()
- request, metadata = self._interceptor.pre_update_serving_config(
+ http_options = _BaseServingConfigServiceRestTransport._BaseCreateServingConfig._get_http_options()
+ request, metadata = self._interceptor.pre_create_serving_config(
request, metadata
)
transcoded_request, body, query_params = transcode_request(
http_options,
request,
required_fields_default_values=getattr(
- _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig,
- "_BaseUpdateServingConfig__REQUIRED_FIELDS_DEFAULT_VALUES",
+ _BaseServingConfigServiceRestTransport._BaseCreateServingConfig,
+ "_BaseCreateServingConfig__REQUIRED_FIELDS_DEFAULT_VALUES",
None,
),
rest_numeric_enums=True,
@@ -404,10 +600,10 @@ def __call__(
"headers": dict(metadata),
}
_LOGGER.debug(
- f"Sending request for google.cloud.discoveryengine_v1.ServingConfigServiceClient.UpdateServingConfig",
+ f"Sending request for google.cloud.discoveryengine_v1.ServingConfigServiceClient.CreateServingConfig",
extra={
"serviceName": "google.cloud.discoveryengine.v1.ServingConfigService",
- "rpcName": "UpdateServingConfig",
+ "rpcName": "CreateServingConfig",
"httpRequest": http_request,
"metadata": http_request["headers"],
},
@@ -415,7 +611,7 @@ def __call__(
# Send the request
response = (
- ServingConfigServiceRestTransport._UpdateServingConfig._get_response(
+ ServingConfigServiceRestTransport._CreateServingConfig._get_response(
self._host,
metadata,
query_params,
@@ -437,9 +633,9 @@ def __call__(
json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
- resp = self._interceptor.post_update_serving_config(resp)
+ resp = self._interceptor.post_create_serving_config(resp)
response_metadata = [(k, str(v)) for k, v in response.headers.items()]
- resp, _ = self._interceptor.post_update_serving_config_with_metadata(
+ resp, _ = self._interceptor.post_create_serving_config_with_metadata(
resp, response_metadata
)
if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
@@ -457,16 +653,635 @@ def __call__(
"status": response.status_code,
}
_LOGGER.debug(
- "Received response for google.cloud.discoveryengine_v1.ServingConfigServiceClient.update_serving_config",
+ "Received response for google.cloud.discoveryengine_v1.ServingConfigServiceClient.create_serving_config",
extra={
"serviceName": "google.cloud.discoveryengine.v1.ServingConfigService",
- "rpcName": "UpdateServingConfig",
+ "rpcName": "CreateServingConfig",
"metadata": http_response["headers"],
"httpResponse": http_response,
},
)
return resp
+ class _DeleteServingConfig(
+ _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig,
+ ServingConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("ServingConfigServiceRestTransport.DeleteServingConfig")
+
+ @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: serving_config_service.DeleteServingConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ):
+ r"""Call the delete serving config method over HTTP.
+
+ Args:
+ request (~.serving_config_service.DeleteServingConfigRequest):
+ The request object. Request for DeleteServingConfig
+ 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 = _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig._get_http_options()
+ request, metadata = self._interceptor.pre_delete_serving_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseServingConfigServiceRestTransport._BaseDeleteServingConfig,
+ "_BaseDeleteServingConfig__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.ServingConfigServiceClient.DeleteServingConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "rpcName": "DeleteServingConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ ServingConfigServiceRestTransport._DeleteServingConfig._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)
+
+ class _GetServingConfig(
+ _BaseServingConfigServiceRestTransport._BaseGetServingConfig,
+ ServingConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("ServingConfigServiceRestTransport.GetServingConfig")
+
+ @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: serving_config_service.GetServingConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> serving_config.ServingConfig:
+ r"""Call the get serving config method over HTTP.
+
+ Args:
+ request (~.serving_config_service.GetServingConfigRequest):
+ The request object. Request for GetServingConfig 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:
+ ~.serving_config.ServingConfig:
+ Configures metadata that is used to
+ generate serving time results (e.g.
+ search results or recommendation
+ predictions). The ServingConfig is
+ passed in the search and predict request
+ and generates results.
+
+ """
+
+ http_options = _BaseServingConfigServiceRestTransport._BaseGetServingConfig._get_http_options()
+ request, metadata = self._interceptor.pre_get_serving_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseServingConfigServiceRestTransport._BaseGetServingConfig,
+ "_BaseGetServingConfig__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.ServingConfigServiceClient.GetServingConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "rpcName": "GetServingConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ ServingConfigServiceRestTransport._GetServingConfig._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 = serving_config.ServingConfig()
+ pb_resp = serving_config.ServingConfig.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_get_serving_config(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_get_serving_config_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = serving_config.ServingConfig.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.ServingConfigServiceClient.get_serving_config",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "rpcName": "GetServingConfig",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _ListServingConfigs(
+ _BaseServingConfigServiceRestTransport._BaseListServingConfigs,
+ ServingConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("ServingConfigServiceRestTransport.ListServingConfigs")
+
+ @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: serving_config_service.ListServingConfigsRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> serving_config_service.ListServingConfigsResponse:
+ r"""Call the list serving configs method over HTTP.
+
+ Args:
+ request (~.serving_config_service.ListServingConfigsRequest):
+ The request object. Request for ListServingConfigs
+ 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:
+ ~.serving_config_service.ListServingConfigsResponse:
+ Response for ListServingConfigs
+ method.
+
+ """
+
+ http_options = _BaseServingConfigServiceRestTransport._BaseListServingConfigs._get_http_options()
+ request, metadata = self._interceptor.pre_list_serving_configs(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseServingConfigServiceRestTransport._BaseListServingConfigs,
+ "_BaseListServingConfigs__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.ServingConfigServiceClient.ListServingConfigs",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "rpcName": "ListServingConfigs",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ ServingConfigServiceRestTransport._ListServingConfigs._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 = serving_config_service.ListServingConfigsResponse()
+ pb_resp = serving_config_service.ListServingConfigsResponse.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_list_serving_configs(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_list_serving_configs_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = (
+ serving_config_service.ListServingConfigsResponse.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.ServingConfigServiceClient.list_serving_configs",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "rpcName": "ListServingConfigs",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _UpdateServingConfig(
+ _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig,
+ ServingConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("ServingConfigServiceRestTransport.UpdateServingConfig")
+
+ @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: serving_config_service.UpdateServingConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> gcd_serving_config.ServingConfig:
+ r"""Call the update serving config method over HTTP.
+
+ Args:
+ request (~.serving_config_service.UpdateServingConfigRequest):
+ The request object. Request for UpdateServingConfig
+ 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:
+ ~.gcd_serving_config.ServingConfig:
+ Configures metadata that is used to
+ generate serving time results (e.g.
+ search results or recommendation
+ predictions). The ServingConfig is
+ passed in the search and predict request
+ and generates results.
+
+ """
+
+ http_options = _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig._get_http_options()
+ request, metadata = self._interceptor.pre_update_serving_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseServingConfigServiceRestTransport._BaseUpdateServingConfig,
+ "_BaseUpdateServingConfig__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.ServingConfigServiceClient.UpdateServingConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "rpcName": "UpdateServingConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ ServingConfigServiceRestTransport._UpdateServingConfig._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 = gcd_serving_config.ServingConfig()
+ pb_resp = gcd_serving_config.ServingConfig.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_update_serving_config(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_update_serving_config_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = gcd_serving_config.ServingConfig.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.ServingConfigServiceClient.update_serving_config",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "rpcName": "UpdateServingConfig",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ @property
+ def create_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.CreateServingConfigRequest],
+ gcd_serving_config.ServingConfig,
+ ]:
+ # 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._CreateServingConfig(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def delete_serving_config(
+ self,
+ ) -> Callable[[serving_config_service.DeleteServingConfigRequest], empty_pb2.Empty]:
+ # 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._DeleteServingConfig(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def get_serving_config(
+ self,
+ ) -> Callable[
+ [serving_config_service.GetServingConfigRequest], serving_config.ServingConfig
+ ]:
+ # 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._GetServingConfig(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def list_serving_configs(
+ self,
+ ) -> Callable[
+ [serving_config_service.ListServingConfigsRequest],
+ serving_config_service.ListServingConfigsResponse,
+ ]:
+ # 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._ListServingConfigs(self._session, self._host, self._interceptor) # type: ignore
+
@property
def update_serving_config(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/rest_base.py
index dede3428f9aa..7c06a5b11577 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/serving_config_service/transports/rest_base.py
@@ -17,13 +17,14 @@
import re
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
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 serving_config, serving_config_service
from google.cloud.discoveryengine_v1.types import serving_config as gcd_serving_config
-from google.cloud.discoveryengine_v1.types import serving_config_service
from .base import DEFAULT_CLIENT_INFO, ServingConfigServiceTransport
@@ -90,6 +91,107 @@ def __init__(
api_audience=api_audience,
)
+ class _BaseCreateServingConfig:
+ def __hash__(self): # pragma: NO COVER
+ return NotImplementedError("__hash__ must be implemented.")
+
+ __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {
+ "servingConfigId": "",
+ }
+
+ @staticmethod
+ def _get_http_options():
+ http_options: List[Dict[str, str]] = [
+ {
+ "method": "post",
+ "uri": "/v1/{parent=projects/*/locations/*/dataStores/*}/servingConfigs",
+ "body": "serving_config",
+ },
+ {
+ "method": "post",
+ "uri": "/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/servingConfigs",
+ "body": "serving_config",
+ },
+ {
+ "method": "post",
+ "uri": "/v1/{parent=projects/*/locations/*/collections/*/engines/*}/servingConfigs",
+ "body": "serving_config",
+ },
+ ]
+ return http_options
+
+ class _BaseDeleteServingConfig:
+ 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/*/dataStores/*/servingConfigs/*}",
+ },
+ {
+ "method": "delete",
+ "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}",
+ },
+ {
+ "method": "delete",
+ "uri": "/v1/{name=projects/*/locations/*/collections/*/engines/*/servingConfigs/*}",
+ },
+ ]
+ return http_options
+
+ class _BaseGetServingConfig:
+ 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/*/dataStores/*/servingConfigs/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/servingConfigs/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v1/{name=projects/*/locations/*/collections/*/engines/*/servingConfigs/*}",
+ },
+ ]
+ return http_options
+
+ class _BaseListServingConfigs:
+ 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/*/dataStores/*}/servingConfigs",
+ },
+ {
+ "method": "get",
+ "uri": "/v1/{parent=projects/*/locations/*/collections/*/dataStores/*}/servingConfigs",
+ },
+ {
+ "method": "get",
+ "uri": "/v1/{parent=projects/*/locations/*/collections/*/engines/*}/servingConfigs",
+ },
+ ]
+ return http_options
+
class _BaseUpdateServingConfig:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@@ -186,6 +288,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/session_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/session_service/transports/base.py
index 79633df8d1af..58315e0895ef 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/session_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/session_service/transports/base.py
@@ -41,7 +41,12 @@
class SessionServiceTransport(abc.ABC):
"""Abstract transport class for SessionService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ AUTH_SCOPES = (
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ )
DEFAULT_HOST: str = "discoveryengine.googleapis.com"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/session_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/session_service/transports/rest_base.py
index ed0f6c2063b5..6b75cede11d7 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/session_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/session_service/transports/rest_base.py
@@ -286,6 +286,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/base.py
index 028f872771be..4dde1dd4e79a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/base.py
@@ -42,7 +42,11 @@
class SiteSearchEngineServiceTransport(abc.ABC):
"""Abstract transport class for SiteSearchEngineService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest.py
index f60f12cd5ddc..b97133a5fc3b 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest.py
@@ -1182,6 +1182,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest_base.py
index c5ec10fa428a..e03cadc37495 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/site_search_engine_service/transports/rest_base.py
@@ -468,6 +468,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py
index 5f9b13b489b4..8bb4ac2eedca 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/async_client.py
@@ -54,6 +54,7 @@
from google.cloud.discoveryengine_v1.types import (
common,
+ feedback,
import_config,
purge_config,
user_event,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/client.py
index 64c3d9ab0cde..2748bca20a46 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/client.py
@@ -78,6 +78,7 @@
from google.cloud.discoveryengine_v1.types import (
common,
+ feedback,
import_config,
purge_config,
user_event,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py
index 1e9bd4428639..b72c0fd1b8c7 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/base.py
@@ -45,7 +45,12 @@
class UserEventServiceTransport(abc.ABC):
"""Abstract transport class for UserEventService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ AUTH_SCOPES = (
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ )
DEFAULT_HOST: str = "discoveryengine.googleapis.com"
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py
index 2c67a3b5146e..fd03e82a7c3a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest.py
@@ -546,6 +546,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest_base.py
index f910ea9e7ab0..8c3943ecc942 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_event_service/transports/rest_base.py
@@ -266,6 +266,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/async_client.py
index b4ee0a711e39..fe884fb1a921 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/async_client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/async_client.py
@@ -353,8 +353,9 @@ async def sample_list_user_licenses():
The request object. Request message for
[UserLicenseService.ListUserLicenses][google.cloud.discoveryengine.v1.UserLicenseService.ListUserLicenses].
parent (:class:`str`):
- Required. The parent [UserStore][] resource name,
- format:
+ Required. The parent
+ [UserStore][google.cloud.discoveryengine.v1.UserStore]
+ resource name, format:
``projects/{project}/locations/{location}/userStores/{user_store_id}``.
This corresponds to the ``parent`` field
@@ -437,6 +438,125 @@ async def sample_list_user_licenses():
# Done; return the response.
return response
+ async def list_license_configs_usage_stats(
+ self,
+ request: Optional[
+ Union[user_license_service.ListLicenseConfigsUsageStatsRequest, 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]]] = (),
+ ) -> user_license_service.ListLicenseConfigsUsageStatsResponse:
+ r"""Lists all the
+ [LicenseConfigUsageStats][google.cloud.discoveryengine.v1.LicenseConfigUsageStats]s
+ associated with the project.
+
+ .. code-block:: python
+
+ # This snippet has been automatically generated and should be regarded as a
+ # code template only.
+ # It will require modifications to work:
+ # - It may require correct/in-range values for request initialization.
+ # - It may require specifying regional endpoints when creating the service
+ # client as shown in:
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
+ from google.cloud import discoveryengine_v1
+
+ async def sample_list_license_configs_usage_stats():
+ # Create a client
+ client = discoveryengine_v1.UserLicenseServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListLicenseConfigsUsageStatsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ response = await client.list_license_configs_usage_stats(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.ListLicenseConfigsUsageStatsRequest, dict]]):
+ The request object. Request message for
+ [UserLicenseService.ListLicenseConfigsUsageStats][google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats]
+ method.
+ parent (:class:`str`):
+ Required. The parent branch resource name, such as
+ ``projects/{project}/locations/{location}/userStores/{user_store_id}``.
+
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each value must be of type `str`,
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
+ be of type `bytes`.
+
+ Returns:
+ google.cloud.discoveryengine_v1.types.ListLicenseConfigsUsageStatsResponse:
+ Response message for
+ [UserLicenseService.ListLicenseConfigsUsageStats][google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats]
+ method.
+
+ """
+ # 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, user_license_service.ListLicenseConfigsUsageStatsRequest
+ ):
+ request = user_license_service.ListLicenseConfigsUsageStatsRequest(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_license_configs_usage_stats
+ ]
+
+ # 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 batch_update_user_licenses(
self,
request: Optional[
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/client.py
index c08e0096e64a..f53fd464f7e2 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/client.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/client.py
@@ -667,8 +667,9 @@ def sample_list_user_licenses():
The request object. Request message for
[UserLicenseService.ListUserLicenses][google.cloud.discoveryengine.v1.UserLicenseService.ListUserLicenses].
parent (str):
- Required. The parent [UserStore][] resource name,
- format:
+ Required. The parent
+ [UserStore][google.cloud.discoveryengine.v1.UserStore]
+ resource name, format:
``projects/{project}/locations/{location}/userStores/{user_store_id}``.
This corresponds to the ``parent`` field
@@ -748,6 +749,124 @@ def sample_list_user_licenses():
# Done; return the response.
return response
+ def list_license_configs_usage_stats(
+ self,
+ request: Optional[
+ Union[user_license_service.ListLicenseConfigsUsageStatsRequest, 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]]] = (),
+ ) -> user_license_service.ListLicenseConfigsUsageStatsResponse:
+ r"""Lists all the
+ [LicenseConfigUsageStats][google.cloud.discoveryengine.v1.LicenseConfigUsageStats]s
+ associated with the project.
+
+ .. code-block:: python
+
+ # This snippet has been automatically generated and should be regarded as a
+ # code template only.
+ # It will require modifications to work:
+ # - It may require correct/in-range values for request initialization.
+ # - It may require specifying regional endpoints when creating the service
+ # client as shown in:
+ # https://googleapis.dev/python/google-api-core/latest/client_options.html
+ from google.cloud import discoveryengine_v1
+
+ def sample_list_license_configs_usage_stats():
+ # Create a client
+ client = discoveryengine_v1.UserLicenseServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListLicenseConfigsUsageStatsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ response = client.list_license_configs_usage_stats(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.ListLicenseConfigsUsageStatsRequest, dict]):
+ The request object. Request message for
+ [UserLicenseService.ListLicenseConfigsUsageStats][google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats]
+ method.
+ parent (str):
+ Required. The parent branch resource name, such as
+ ``projects/{project}/locations/{location}/userStores/{user_store_id}``.
+
+ This corresponds to the ``parent`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each value must be of type `str`,
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
+ be of type `bytes`.
+
+ Returns:
+ google.cloud.discoveryengine_v1.types.ListLicenseConfigsUsageStatsResponse:
+ Response message for
+ [UserLicenseService.ListLicenseConfigsUsageStats][google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats]
+ method.
+
+ """
+ # 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, user_license_service.ListLicenseConfigsUsageStatsRequest
+ ):
+ request = user_license_service.ListLicenseConfigsUsageStatsRequest(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_license_configs_usage_stats
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
+ )
+
+ # Validate the universe domain.
+ self._validate_universe_domain()
+
+ # Send the request.
+ response = rpc(
+ request,
+ retry=retry,
+ timeout=timeout,
+ metadata=metadata,
+ )
+
+ # Done; return the response.
+ return response
+
def batch_update_user_licenses(
self,
request: Optional[
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/base.py
index 3e7447fdfb98..9c5e7cf5e477 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/base.py
@@ -39,7 +39,11 @@
class UserLicenseServiceTransport(abc.ABC):
"""Abstract transport class for UserLicenseService."""
- AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",)
+ 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"
@@ -147,6 +151,11 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
+ self.list_license_configs_usage_stats: gapic_v1.method.wrap_method(
+ self.list_license_configs_usage_stats,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.batch_update_user_licenses: gapic_v1.method.wrap_method(
self.batch_update_user_licenses,
default_timeout=None,
@@ -195,6 +204,18 @@ def list_user_licenses(
]:
raise NotImplementedError()
+ @property
+ def list_license_configs_usage_stats(
+ self,
+ ) -> Callable[
+ [user_license_service.ListLicenseConfigsUsageStatsRequest],
+ Union[
+ user_license_service.ListLicenseConfigsUsageStatsResponse,
+ Awaitable[user_license_service.ListLicenseConfigsUsageStatsResponse],
+ ],
+ ]:
+ raise NotImplementedError()
+
@property
def batch_update_user_licenses(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/grpc.py
index 193cef220913..15e844e6e546 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/grpc.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/grpc.py
@@ -373,6 +373,40 @@ def list_user_licenses(
)
return self._stubs["list_user_licenses"]
+ @property
+ def list_license_configs_usage_stats(
+ self,
+ ) -> Callable[
+ [user_license_service.ListLicenseConfigsUsageStatsRequest],
+ user_license_service.ListLicenseConfigsUsageStatsResponse,
+ ]:
+ r"""Return a callable for the list license configs usage
+ stats method over gRPC.
+
+ Lists all the
+ [LicenseConfigUsageStats][google.cloud.discoveryengine.v1.LicenseConfigUsageStats]s
+ associated with the project.
+
+ Returns:
+ Callable[[~.ListLicenseConfigsUsageStatsRequest],
+ ~.ListLicenseConfigsUsageStatsResponse]:
+ 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_license_configs_usage_stats" not in self._stubs:
+ self._stubs["list_license_configs_usage_stats"] = (
+ self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.UserLicenseService/ListLicenseConfigsUsageStats",
+ request_serializer=user_license_service.ListLicenseConfigsUsageStatsRequest.serialize,
+ response_deserializer=user_license_service.ListLicenseConfigsUsageStatsResponse.deserialize,
+ )
+ )
+ return self._stubs["list_license_configs_usage_stats"]
+
@property
def batch_update_user_licenses(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/grpc_asyncio.py
index 2419f69cad8e..d0ffd9e6303d 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/grpc_asyncio.py
@@ -381,6 +381,40 @@ def list_user_licenses(
)
return self._stubs["list_user_licenses"]
+ @property
+ def list_license_configs_usage_stats(
+ self,
+ ) -> Callable[
+ [user_license_service.ListLicenseConfigsUsageStatsRequest],
+ Awaitable[user_license_service.ListLicenseConfigsUsageStatsResponse],
+ ]:
+ r"""Return a callable for the list license configs usage
+ stats method over gRPC.
+
+ Lists all the
+ [LicenseConfigUsageStats][google.cloud.discoveryengine.v1.LicenseConfigUsageStats]s
+ associated with the project.
+
+ Returns:
+ Callable[[~.ListLicenseConfigsUsageStatsRequest],
+ Awaitable[~.ListLicenseConfigsUsageStatsResponse]]:
+ 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_license_configs_usage_stats" not in self._stubs:
+ self._stubs["list_license_configs_usage_stats"] = (
+ self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.UserLicenseService/ListLicenseConfigsUsageStats",
+ request_serializer=user_license_service.ListLicenseConfigsUsageStatsRequest.serialize,
+ response_deserializer=user_license_service.ListLicenseConfigsUsageStatsResponse.deserialize,
+ )
+ )
+ return self._stubs["list_license_configs_usage_stats"]
+
@property
def batch_update_user_licenses(
self,
@@ -422,6 +456,11 @@ def _prep_wrapped_messages(self, client_info):
default_timeout=None,
client_info=client_info,
),
+ self.list_license_configs_usage_stats: self._wrap_method(
+ self.list_license_configs_usage_stats,
+ default_timeout=None,
+ client_info=client_info,
+ ),
self.batch_update_user_licenses: self._wrap_method(
self.batch_update_user_licenses,
default_timeout=None,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/rest.py
index 45859a4d9027..269090945db6 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/rest.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/rest.py
@@ -82,6 +82,14 @@ def post_batch_update_user_licenses(self, response):
logging.log(f"Received response: {response}")
return response
+ def pre_list_license_configs_usage_stats(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_list_license_configs_usage_stats(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
def pre_list_user_licenses(self, request, metadata):
logging.log(f"Received request: {request}")
return request, metadata
@@ -145,6 +153,58 @@ def post_batch_update_user_licenses_with_metadata(
"""
return response, metadata
+ def pre_list_license_configs_usage_stats(
+ self,
+ request: user_license_service.ListLicenseConfigsUsageStatsRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ user_license_service.ListLicenseConfigsUsageStatsRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for list_license_configs_usage_stats
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the UserLicenseService server.
+ """
+ return request, metadata
+
+ def post_list_license_configs_usage_stats(
+ self, response: user_license_service.ListLicenseConfigsUsageStatsResponse
+ ) -> user_license_service.ListLicenseConfigsUsageStatsResponse:
+ """Post-rpc interceptor for list_license_configs_usage_stats
+
+ DEPRECATED. Please use the `post_list_license_configs_usage_stats_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the UserLicenseService server but before
+ it is returned to user code. This `post_list_license_configs_usage_stats` interceptor runs
+ before the `post_list_license_configs_usage_stats_with_metadata` interceptor.
+ """
+ return response
+
+ def post_list_license_configs_usage_stats_with_metadata(
+ self,
+ response: user_license_service.ListLicenseConfigsUsageStatsResponse,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ user_license_service.ListLicenseConfigsUsageStatsResponse,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Post-rpc interceptor for list_license_configs_usage_stats
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the UserLicenseService server but before it is returned to user code.
+
+ We recommend only using this `post_list_license_configs_usage_stats_with_metadata`
+ interceptor in new development instead of the `post_list_license_configs_usage_stats` interceptor.
+ When both interceptors are used, this `post_list_license_configs_usage_stats_with_metadata` interceptor runs after the
+ `post_list_license_configs_usage_stats` interceptor. The (possibly modified) response returned by
+ `post_list_license_configs_usage_stats` will be passed to
+ `post_list_license_configs_usage_stats_with_metadata`.
+ """
+ return response, metadata
+
def pre_list_user_licenses(
self,
request: user_license_service.ListUserLicensesRequest,
@@ -430,6 +490,10 @@ def operations_client(self) -> operations_v1.AbstractOperationsClient:
"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/*}",
@@ -701,6 +765,162 @@ def __call__(
)
return resp
+ class _ListLicenseConfigsUsageStats(
+ _BaseUserLicenseServiceRestTransport._BaseListLicenseConfigsUsageStats,
+ UserLicenseServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("UserLicenseServiceRestTransport.ListLicenseConfigsUsageStats")
+
+ @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: user_license_service.ListLicenseConfigsUsageStatsRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> user_license_service.ListLicenseConfigsUsageStatsResponse:
+ r"""Call the list license configs
+ usage stats method over HTTP.
+
+ Args:
+ request (~.user_license_service.ListLicenseConfigsUsageStatsRequest):
+ The request object. Request message for
+ [UserLicenseService.ListLicenseConfigsUsageStats][google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats]
+ 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:
+ ~.user_license_service.ListLicenseConfigsUsageStatsResponse:
+ Response message for
+ [UserLicenseService.ListLicenseConfigsUsageStats][google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats]
+ method.
+
+ """
+
+ http_options = _BaseUserLicenseServiceRestTransport._BaseListLicenseConfigsUsageStats._get_http_options()
+ request, metadata = self._interceptor.pre_list_license_configs_usage_stats(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseUserLicenseServiceRestTransport._BaseListLicenseConfigsUsageStats,
+ "_BaseListLicenseConfigsUsageStats__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.UserLicenseServiceClient.ListLicenseConfigsUsageStats",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserLicenseService",
+ "rpcName": "ListLicenseConfigsUsageStats",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = UserLicenseServiceRestTransport._ListLicenseConfigsUsageStats._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 = user_license_service.ListLicenseConfigsUsageStatsResponse()
+ pb_resp = user_license_service.ListLicenseConfigsUsageStatsResponse.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_list_license_configs_usage_stats(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = (
+ self._interceptor.post_list_license_configs_usage_stats_with_metadata(
+ resp, response_metadata
+ )
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = user_license_service.ListLicenseConfigsUsageStatsResponse.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.UserLicenseServiceClient.list_license_configs_usage_stats",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserLicenseService",
+ "rpcName": "ListLicenseConfigsUsageStats",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
class _ListUserLicenses(
_BaseUserLicenseServiceRestTransport._BaseListUserLicenses,
UserLicenseServiceRestStub,
@@ -864,6 +1084,19 @@ def batch_update_user_licenses(
self._session, self._host, self._interceptor
) # type: ignore
+ @property
+ def list_license_configs_usage_stats(
+ self,
+ ) -> Callable[
+ [user_license_service.ListLicenseConfigsUsageStatsRequest],
+ user_license_service.ListLicenseConfigsUsageStatsResponse,
+ ]:
+ # 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._ListLicenseConfigsUsageStats(
+ self._session, self._host, self._interceptor
+ ) # type: ignore
+
@property
def list_user_licenses(
self,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/rest_base.py
index 67bd6208c8f1..a8a42dc84889 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/rest_base.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_license_service/transports/rest_base.py
@@ -106,6 +106,22 @@ def _get_http_options():
]
return http_options
+ class _BaseListLicenseConfigsUsageStats:
+ 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/*/userStores/*}/licenseConfigsUsageStats",
+ },
+ ]
+ return http_options
+
class _BaseListUserLicenses:
def __hash__(self): # pragma: NO COVER
return NotImplementedError("__hash__ must be implemented.")
@@ -191,6 +207,10 @@ def _get_http_options():
"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/*}",
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/__init__.py
new file mode 100644
index 000000000000..101c4198c3c4
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_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 UserStoreServiceAsyncClient
+from .client import UserStoreServiceClient
+
+__all__ = (
+ "UserStoreServiceClient",
+ "UserStoreServiceAsyncClient",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/async_client.py
new file mode 100644
index 000000000000..968d81482a6c
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/async_client.py
@@ -0,0 +1,732 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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
+
+import google.protobuf.field_mask_pb2 as field_mask_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 user_store, user_store_service
+from google.cloud.discoveryengine_v1.types import user_store as gcd_user_store
+
+from .client import UserStoreServiceClient
+from .transports.base import DEFAULT_CLIENT_INFO, UserStoreServiceTransport
+from .transports.grpc_asyncio import UserStoreServiceGrpcAsyncIOTransport
+
+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 UserStoreServiceAsyncClient:
+ """Service for managing User Stores."""
+
+ _client: UserStoreServiceClient
+
+ # Copy defaults from the synchronous client for use here.
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
+ DEFAULT_ENDPOINT = UserStoreServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = UserStoreServiceClient.DEFAULT_MTLS_ENDPOINT
+ _DEFAULT_ENDPOINT_TEMPLATE = UserStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE
+ _DEFAULT_UNIVERSE = UserStoreServiceClient._DEFAULT_UNIVERSE
+
+ license_config_path = staticmethod(UserStoreServiceClient.license_config_path)
+ parse_license_config_path = staticmethod(
+ UserStoreServiceClient.parse_license_config_path
+ )
+ user_store_path = staticmethod(UserStoreServiceClient.user_store_path)
+ parse_user_store_path = staticmethod(UserStoreServiceClient.parse_user_store_path)
+ common_billing_account_path = staticmethod(
+ UserStoreServiceClient.common_billing_account_path
+ )
+ parse_common_billing_account_path = staticmethod(
+ UserStoreServiceClient.parse_common_billing_account_path
+ )
+ common_folder_path = staticmethod(UserStoreServiceClient.common_folder_path)
+ parse_common_folder_path = staticmethod(
+ UserStoreServiceClient.parse_common_folder_path
+ )
+ common_organization_path = staticmethod(
+ UserStoreServiceClient.common_organization_path
+ )
+ parse_common_organization_path = staticmethod(
+ UserStoreServiceClient.parse_common_organization_path
+ )
+ common_project_path = staticmethod(UserStoreServiceClient.common_project_path)
+ parse_common_project_path = staticmethod(
+ UserStoreServiceClient.parse_common_project_path
+ )
+ common_location_path = staticmethod(UserStoreServiceClient.common_location_path)
+ parse_common_location_path = staticmethod(
+ UserStoreServiceClient.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:
+ UserStoreServiceAsyncClient: The constructed client.
+ """
+ sa_info_func = (
+ UserStoreServiceClient.from_service_account_info.__func__ # type: ignore
+ )
+ return sa_info_func(UserStoreServiceAsyncClient, 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:
+ UserStoreServiceAsyncClient: The constructed client.
+ """
+ sa_file_func = (
+ UserStoreServiceClient.from_service_account_file.__func__ # type: ignore
+ )
+ return sa_file_func(UserStoreServiceAsyncClient, 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 UserStoreServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
+
+ @property
+ def transport(self) -> UserStoreServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ UserStoreServiceTransport: 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 = UserStoreServiceClient.get_transport_class
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[ga_credentials.Credentials] = None,
+ transport: Optional[
+ Union[
+ str, UserStoreServiceTransport, Callable[..., UserStoreServiceTransport]
+ ]
+ ] = "grpc_asyncio",
+ client_options: Optional[ClientOptions] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the user store 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,UserStoreServiceTransport,Callable[..., UserStoreServiceTransport]]]):
+ 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 UserStoreServiceTransport 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 = UserStoreServiceClient(
+ 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.UserStoreServiceAsyncClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "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.UserStoreService",
+ "credentialsType": None,
+ },
+ )
+
+ async def get_user_store(
+ self,
+ request: Optional[Union[user_store_service.GetUserStoreRequest, 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]]] = (),
+ ) -> user_store.UserStore:
+ r"""Gets the User Store.
+
+ .. 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_user_store():
+ # Create a client
+ client = discoveryengine_v1.UserStoreServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetUserStoreRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_user_store(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.GetUserStoreRequest, dict]]):
+ The request object. Request message for
+ [UserStoreService.GetUserStore][google.cloud.discoveryengine.v1.UserStoreService.GetUserStore]
+ name (:class:`str`):
+ Required. The name of the User Store to get. Format:
+ ``projects/{project}/locations/{location}/userStores/{user_store_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.discoveryengine_v1.types.UserStore:
+ Configures metadata that is used for
+ End User entities.
+
+ """
+ # 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, user_store_service.GetUserStoreRequest):
+ request = user_store_service.GetUserStoreRequest(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_user_store
+ ]
+
+ # 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_user_store(
+ self,
+ request: Optional[
+ Union[user_store_service.UpdateUserStoreRequest, dict]
+ ] = None,
+ *,
+ user_store: Optional[gcd_user_store.UserStore] = 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_user_store.UserStore:
+ r"""Updates the User Store.
+
+ .. 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_user_store():
+ # Create a client
+ client = discoveryengine_v1.UserStoreServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.UpdateUserStoreRequest(
+ )
+
+ # Make the request
+ response = await client.update_user_store(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateUserStoreRequest, dict]]):
+ The request object. Request message for
+ [UserStoreService.UpdateUserStore][google.cloud.discoveryengine.v1.UserStoreService.UpdateUserStore]
+ method.
+ user_store (:class:`google.cloud.discoveryengine_v1.types.UserStore`):
+ Required. The User Store to update. Format:
+ ``projects/{project}/locations/{location}/userStores/{user_store_id}``
+
+ This corresponds to the ``user_store`` 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.
+
+ 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.UserStore:
+ Configures metadata that is used for
+ End User entities.
+
+ """
+ # 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 = [user_store, 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, user_store_service.UpdateUserStoreRequest):
+ request = user_store_service.UpdateUserStoreRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if user_store is not None:
+ request.user_store = user_store
+ 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_user_store
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("user_store.name", request.user_store.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) -> "UserStoreServiceAsyncClient":
+ 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__ = ("UserStoreServiceAsyncClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/client.py
new file mode 100644
index 000000000000..51be8231d02d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/client.py
@@ -0,0 +1,1056 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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__)
+
+import google.protobuf.field_mask_pb2 as field_mask_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 user_store, user_store_service
+from google.cloud.discoveryengine_v1.types import user_store as gcd_user_store
+
+from .transports.base import DEFAULT_CLIENT_INFO, UserStoreServiceTransport
+from .transports.grpc import UserStoreServiceGrpcTransport
+from .transports.grpc_asyncio import UserStoreServiceGrpcAsyncIOTransport
+from .transports.rest import UserStoreServiceRestTransport
+
+
+class UserStoreServiceClientMeta(type):
+ """Metaclass for the UserStoreService 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[UserStoreServiceTransport]]
+ _transport_registry["grpc"] = UserStoreServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = UserStoreServiceGrpcAsyncIOTransport
+ _transport_registry["rest"] = UserStoreServiceRestTransport
+
+ def get_transport_class(
+ cls,
+ label: Optional[str] = None,
+ ) -> Type[UserStoreServiceTransport]:
+ """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 UserStoreServiceClient(metaclass=UserStoreServiceClientMeta):
+ """Service for managing User Stores."""
+
+ # 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:
+ UserStoreServiceClient: 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:
+ UserStoreServiceClient: 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) -> UserStoreServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ UserStoreServiceTransport: The transport used by the client
+ instance.
+ """
+ return self._transport
+
+ @staticmethod
+ def license_config_path(
+ project: str,
+ location: str,
+ license_config: str,
+ ) -> str:
+ """Returns a fully-qualified license_config string."""
+ return "projects/{project}/locations/{location}/licenseConfigs/{license_config}".format(
+ project=project,
+ location=location,
+ license_config=license_config,
+ )
+
+ @staticmethod
+ def parse_license_config_path(path: str) -> Dict[str, str]:
+ """Parses a license_config path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/licenseConfigs/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def user_store_path(
+ project: str,
+ location: str,
+ user_store: str,
+ ) -> str:
+ """Returns a fully-qualified user_store string."""
+ return "projects/{project}/locations/{location}/userStores/{user_store}".format(
+ project=project,
+ location=location,
+ user_store=user_store,
+ )
+
+ @staticmethod
+ def parse_user_store_path(path: str) -> Dict[str, str]:
+ """Parses a user_store path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/userStores/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_billing_account_path(
+ billing_account: str,
+ ) -> str:
+ """Returns a fully-qualified billing_account string."""
+ return "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+
+ @staticmethod
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
+ """Parse a billing_account path into its component segments."""
+ m = re.match(r"^billingAccounts/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_folder_path(
+ folder: str,
+ ) -> str:
+ """Returns a fully-qualified folder string."""
+ return "folders/{folder}".format(
+ folder=folder,
+ )
+
+ @staticmethod
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
+ """Parse a folder path into its component segments."""
+ m = re.match(r"^folders/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_organization_path(
+ organization: str,
+ ) -> str:
+ """Returns a fully-qualified organization string."""
+ return "organizations/{organization}".format(
+ organization=organization,
+ )
+
+ @staticmethod
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
+ """Parse a organization path into its component segments."""
+ m = re.match(r"^organizations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_project_path(
+ project: str,
+ ) -> str:
+ """Returns a fully-qualified project string."""
+ return "projects/{project}".format(
+ project=project,
+ )
+
+ @staticmethod
+ def parse_common_project_path(path: str) -> Dict[str, str]:
+ """Parse a project path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_location_path(
+ project: str,
+ location: str,
+ ) -> str:
+ """Returns a fully-qualified location string."""
+ return "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+
+ @staticmethod
+ def parse_common_location_path(path: str) -> Dict[str, str]:
+ """Parse a location path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @classmethod
+ def get_mtls_endpoint_and_cert_source(
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
+ ):
+ """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, UserStoreServiceTransport, Callable[..., UserStoreServiceTransport]
+ ]
+ ] = None,
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the user store 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,UserStoreServiceTransport,Callable[..., UserStoreServiceTransport]]]):
+ 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 UserStoreServiceTransport 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 = UserStoreServiceClient._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=UserStoreServiceClient._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, UserStoreServiceTransport)
+ if transport_provided:
+ # transport is a UserStoreServiceTransport 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(UserStoreServiceTransport, 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=UserStoreServiceClient._DEFAULT_UNIVERSE,
+ default_mtls_endpoint=UserStoreServiceClient.DEFAULT_MTLS_ENDPOINT,
+ default_endpoint_template=UserStoreServiceClient._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[UserStoreServiceTransport],
+ Callable[..., UserStoreServiceTransport],
+ ] = (
+ UserStoreServiceClient.get_transport_class(transport)
+ if isinstance(transport, str) or transport is None
+ else cast(Callable[..., UserStoreServiceTransport], 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.UserStoreServiceClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "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.UserStoreService",
+ "credentialsType": None,
+ },
+ )
+
+ def get_user_store(
+ self,
+ request: Optional[Union[user_store_service.GetUserStoreRequest, 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]]] = (),
+ ) -> user_store.UserStore:
+ r"""Gets the User Store.
+
+ .. 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_user_store():
+ # Create a client
+ client = discoveryengine_v1.UserStoreServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetUserStoreRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_user_store(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.GetUserStoreRequest, dict]):
+ The request object. Request message for
+ [UserStoreService.GetUserStore][google.cloud.discoveryengine.v1.UserStoreService.GetUserStore]
+ name (str):
+ Required. The name of the User Store to get. Format:
+ ``projects/{project}/locations/{location}/userStores/{user_store_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.discoveryengine_v1.types.UserStore:
+ Configures metadata that is used for
+ End User entities.
+
+ """
+ # 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, user_store_service.GetUserStoreRequest):
+ request = user_store_service.GetUserStoreRequest(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_user_store]
+
+ # 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_user_store(
+ self,
+ request: Optional[
+ Union[user_store_service.UpdateUserStoreRequest, dict]
+ ] = None,
+ *,
+ user_store: Optional[gcd_user_store.UserStore] = 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_user_store.UserStore:
+ r"""Updates the User Store.
+
+ .. 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_user_store():
+ # Create a client
+ client = discoveryengine_v1.UserStoreServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.UpdateUserStoreRequest(
+ )
+
+ # Make the request
+ response = client.update_user_store(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.UpdateUserStoreRequest, dict]):
+ The request object. Request message for
+ [UserStoreService.UpdateUserStore][google.cloud.discoveryengine.v1.UserStoreService.UpdateUserStore]
+ method.
+ user_store (google.cloud.discoveryengine_v1.types.UserStore):
+ Required. The User Store to update. Format:
+ ``projects/{project}/locations/{location}/userStores/{user_store_id}``
+
+ This corresponds to the ``user_store`` 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.
+
+ 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.cloud.discoveryengine_v1.types.UserStore:
+ Configures metadata that is used for
+ End User entities.
+
+ """
+ # 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 = [user_store, 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, user_store_service.UpdateUserStoreRequest):
+ request = user_store_service.UpdateUserStoreRequest(request)
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if user_store is not None:
+ request.user_store = user_store
+ 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_user_store]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("user_store.name", request.user_store.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) -> "UserStoreServiceClient":
+ 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__ = ("UserStoreServiceClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/README.rst b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/README.rst
new file mode 100644
index 000000000000..0256c44160fb
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/README.rst
@@ -0,0 +1,10 @@
+
+transport inheritance structure
+_______________________________
+
+``UserStoreServiceTransport`` is the ABC for all transports.
+
+- public child ``UserStoreServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``).
+- public child ``UserStoreServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``).
+- private child ``_BaseUserStoreServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``).
+- public child ``UserStoreServiceRestTransport`` 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/user_store_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/__init__.py
new file mode 100644
index 000000000000..bd3404c60cc5
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_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 UserStoreServiceTransport
+from .grpc import UserStoreServiceGrpcTransport
+from .grpc_asyncio import UserStoreServiceGrpcAsyncIOTransport
+from .rest import UserStoreServiceRestInterceptor, UserStoreServiceRestTransport
+
+# Compile a registry of transports.
+_transport_registry = OrderedDict() # type: Dict[str, Type[UserStoreServiceTransport]]
+_transport_registry["grpc"] = UserStoreServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = UserStoreServiceGrpcAsyncIOTransport
+_transport_registry["rest"] = UserStoreServiceRestTransport
+
+__all__ = (
+ "UserStoreServiceTransport",
+ "UserStoreServiceGrpcTransport",
+ "UserStoreServiceGrpcAsyncIOTransport",
+ "UserStoreServiceRestTransport",
+ "UserStoreServiceRestInterceptor",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/base.py
new file mode 100644
index 000000000000..a6d7133535e6
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/base.py
@@ -0,0 +1,239 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import abc
+from typing import 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 user_store, user_store_service
+from google.cloud.discoveryengine_v1.types import user_store as gcd_user_store
+
+DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=package_version.__version__
+)
+DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
+
+
+class UserStoreServiceTransport(abc.ABC):
+ """Abstract transport class for UserStoreService."""
+
+ 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.get_user_store: gapic_v1.method.wrap_method(
+ self.get_user_store,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.update_user_store: gapic_v1.method.wrap_method(
+ self.update_user_store,
+ 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 get_user_store(
+ self,
+ ) -> Callable[
+ [user_store_service.GetUserStoreRequest],
+ Union[user_store.UserStore, Awaitable[user_store.UserStore]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def update_user_store(
+ self,
+ ) -> Callable[
+ [user_store_service.UpdateUserStoreRequest],
+ Union[gcd_user_store.UserStore, Awaitable[gcd_user_store.UserStore]],
+ ]:
+ 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__ = ("UserStoreServiceTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/grpc.py
new file mode 100644
index 000000000000..256ad4c09122
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_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 user_store, user_store_service
+from google.cloud.discoveryengine_v1.types import user_store as gcd_user_store
+
+from .base import DEFAULT_CLIENT_INFO, UserStoreServiceTransport
+
+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.UserStoreService",
+ "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.UserStoreService",
+ "rpcName": client_call_details.method,
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class UserStoreServiceGrpcTransport(UserStoreServiceTransport):
+ """gRPC backend transport for UserStoreService.
+
+ Service for managing User Stores.
+
+ 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 get_user_store(
+ self,
+ ) -> Callable[[user_store_service.GetUserStoreRequest], user_store.UserStore]:
+ r"""Return a callable for the get user store method over gRPC.
+
+ Gets the User Store.
+
+ Returns:
+ Callable[[~.GetUserStoreRequest],
+ ~.UserStore]:
+ 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_user_store" not in self._stubs:
+ self._stubs["get_user_store"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.UserStoreService/GetUserStore",
+ request_serializer=user_store_service.GetUserStoreRequest.serialize,
+ response_deserializer=user_store.UserStore.deserialize,
+ )
+ return self._stubs["get_user_store"]
+
+ @property
+ def update_user_store(
+ self,
+ ) -> Callable[
+ [user_store_service.UpdateUserStoreRequest], gcd_user_store.UserStore
+ ]:
+ r"""Return a callable for the update user store method over gRPC.
+
+ Updates the User Store.
+
+ Returns:
+ Callable[[~.UpdateUserStoreRequest],
+ ~.UserStore]:
+ 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_user_store" not in self._stubs:
+ self._stubs["update_user_store"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.UserStoreService/UpdateUserStore",
+ request_serializer=user_store_service.UpdateUserStoreRequest.serialize,
+ response_deserializer=gcd_user_store.UserStore.deserialize,
+ )
+ return self._stubs["update_user_store"]
+
+ 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__ = ("UserStoreServiceGrpcTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/grpc_asyncio.py
new file mode 100644
index 000000000000..64a15bad4a74
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/grpc_asyncio.py
@@ -0,0 +1,491 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 user_store, user_store_service
+from google.cloud.discoveryengine_v1.types import user_store as gcd_user_store
+
+from .base import DEFAULT_CLIENT_INFO, UserStoreServiceTransport
+from .grpc import UserStoreServiceGrpcTransport
+
+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.UserStoreService",
+ "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.UserStoreService",
+ "rpcName": str(client_call_details.method),
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class UserStoreServiceGrpcAsyncIOTransport(UserStoreServiceTransport):
+ """gRPC AsyncIO backend transport for UserStoreService.
+
+ Service for managing User Stores.
+
+ 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 get_user_store(
+ self,
+ ) -> Callable[
+ [user_store_service.GetUserStoreRequest], Awaitable[user_store.UserStore]
+ ]:
+ r"""Return a callable for the get user store method over gRPC.
+
+ Gets the User Store.
+
+ Returns:
+ Callable[[~.GetUserStoreRequest],
+ Awaitable[~.UserStore]]:
+ 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_user_store" not in self._stubs:
+ self._stubs["get_user_store"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.UserStoreService/GetUserStore",
+ request_serializer=user_store_service.GetUserStoreRequest.serialize,
+ response_deserializer=user_store.UserStore.deserialize,
+ )
+ return self._stubs["get_user_store"]
+
+ @property
+ def update_user_store(
+ self,
+ ) -> Callable[
+ [user_store_service.UpdateUserStoreRequest], Awaitable[gcd_user_store.UserStore]
+ ]:
+ r"""Return a callable for the update user store method over gRPC.
+
+ Updates the User Store.
+
+ Returns:
+ Callable[[~.UpdateUserStoreRequest],
+ Awaitable[~.UserStore]]:
+ 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_user_store" not in self._stubs:
+ self._stubs["update_user_store"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.UserStoreService/UpdateUserStore",
+ request_serializer=user_store_service.UpdateUserStoreRequest.serialize,
+ response_deserializer=gcd_user_store.UserStore.deserialize,
+ )
+ return self._stubs["update_user_store"]
+
+ def _prep_wrapped_messages(self, client_info):
+ """Precompute the wrapped methods, overriding the base class method to use async wrappers."""
+ self._wrapped_methods = {
+ self.get_user_store: self._wrap_method(
+ self.get_user_store,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.update_user_store: self._wrap_method(
+ self.update_user_store,
+ 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__ = ("UserStoreServiceGrpcAsyncIOTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/rest.py
new file mode 100644
index 000000000000..80fe2c576ad2
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/rest.py
@@ -0,0 +1,1086 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 user_store, user_store_service
+from google.cloud.discoveryengine_v1.types import user_store as gcd_user_store
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .rest_base import _BaseUserStoreServiceRestTransport
+
+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 UserStoreServiceRestInterceptor:
+ """Interceptor for UserStoreService.
+
+ 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 UserStoreServiceRestTransport.
+
+ .. code-block:: python
+ class MyCustomUserStoreServiceInterceptor(UserStoreServiceRestInterceptor):
+ def pre_get_user_store(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_get_user_store(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_update_user_store(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_update_user_store(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ transport = UserStoreServiceRestTransport(interceptor=MyCustomUserStoreServiceInterceptor())
+ client = UserStoreServiceClient(transport=transport)
+
+
+ """
+
+ def pre_get_user_store(
+ self,
+ request: user_store_service.GetUserStoreRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ user_store_service.GetUserStoreRequest, Sequence[Tuple[str, Union[str, bytes]]]
+ ]:
+ """Pre-rpc interceptor for get_user_store
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the UserStoreService server.
+ """
+ return request, metadata
+
+ def post_get_user_store(
+ self, response: user_store.UserStore
+ ) -> user_store.UserStore:
+ """Post-rpc interceptor for get_user_store
+
+ DEPRECATED. Please use the `post_get_user_store_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the UserStoreService server but before
+ it is returned to user code. This `post_get_user_store` interceptor runs
+ before the `post_get_user_store_with_metadata` interceptor.
+ """
+ return response
+
+ def post_get_user_store_with_metadata(
+ self,
+ response: user_store.UserStore,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[user_store.UserStore, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for get_user_store
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the UserStoreService server but before it is returned to user code.
+
+ We recommend only using this `post_get_user_store_with_metadata`
+ interceptor in new development instead of the `post_get_user_store` interceptor.
+ When both interceptors are used, this `post_get_user_store_with_metadata` interceptor runs after the
+ `post_get_user_store` interceptor. The (possibly modified) response returned by
+ `post_get_user_store` will be passed to
+ `post_get_user_store_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_update_user_store(
+ self,
+ request: user_store_service.UpdateUserStoreRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ user_store_service.UpdateUserStoreRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for update_user_store
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the UserStoreService server.
+ """
+ return request, metadata
+
+ def post_update_user_store(
+ self, response: gcd_user_store.UserStore
+ ) -> gcd_user_store.UserStore:
+ """Post-rpc interceptor for update_user_store
+
+ DEPRECATED. Please use the `post_update_user_store_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the UserStoreService server but before
+ it is returned to user code. This `post_update_user_store` interceptor runs
+ before the `post_update_user_store_with_metadata` interceptor.
+ """
+ return response
+
+ def post_update_user_store_with_metadata(
+ self,
+ response: gcd_user_store.UserStore,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[gcd_user_store.UserStore, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for update_user_store
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the UserStoreService server but before it is returned to user code.
+
+ We recommend only using this `post_update_user_store_with_metadata`
+ interceptor in new development instead of the `post_update_user_store` interceptor.
+ When both interceptors are used, this `post_update_user_store_with_metadata` interceptor runs after the
+ `post_update_user_store` interceptor. The (possibly modified) response returned by
+ `post_update_user_store` will be passed to
+ `post_update_user_store_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 UserStoreService 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 UserStoreService 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 UserStoreService 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 UserStoreService 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 UserStoreService 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 UserStoreService server but before
+ it is returned to user code.
+ """
+ return response
+
+
+@dataclasses.dataclass
+class UserStoreServiceRestStub:
+ _session: AuthorizedSession
+ _host: str
+ _interceptor: UserStoreServiceRestInterceptor
+
+
+class UserStoreServiceRestTransport(_BaseUserStoreServiceRestTransport):
+ """REST backend synchronous transport for UserStoreService.
+
+ Service for managing User Stores.
+
+ 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[UserStoreServiceRestInterceptor] = 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[UserStoreServiceRestInterceptor]): 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 UserStoreServiceRestInterceptor()
+ self._prep_wrapped_messages(client_info)
+
+ class _GetUserStore(
+ _BaseUserStoreServiceRestTransport._BaseGetUserStore, UserStoreServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("UserStoreServiceRestTransport.GetUserStore")
+
+ @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: user_store_service.GetUserStoreRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> user_store.UserStore:
+ r"""Call the get user store method over HTTP.
+
+ Args:
+ request (~.user_store_service.GetUserStoreRequest):
+ The request object. Request message for
+ [UserStoreService.GetUserStore][google.cloud.discoveryengine.v1.UserStoreService.GetUserStore]
+ retry (google.api_core.retry.Retry): Designation of what errors, if any,
+ should be retried.
+ timeout (float): The timeout for this request.
+ metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
+ sent along with the request as metadata. Normally, each value must be of type `str`,
+ but for metadata keys ending with the suffix `-bin`, the corresponding values must
+ be of type `bytes`.
+
+ Returns:
+ ~.user_store.UserStore:
+ Configures metadata that is used for
+ End User entities.
+
+ """
+
+ http_options = (
+ _BaseUserStoreServiceRestTransport._BaseGetUserStore._get_http_options()
+ )
+ request, metadata = self._interceptor.pre_get_user_store(request, metadata)
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseUserStoreServiceRestTransport._BaseGetUserStore,
+ "_BaseGetUserStore__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.UserStoreServiceClient.GetUserStore",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "rpcName": "GetUserStore",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = UserStoreServiceRestTransport._GetUserStore._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 = user_store.UserStore()
+ pb_resp = user_store.UserStore.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_get_user_store(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_get_user_store_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = user_store.UserStore.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.UserStoreServiceClient.get_user_store",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "rpcName": "GetUserStore",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _UpdateUserStore(
+ _BaseUserStoreServiceRestTransport._BaseUpdateUserStore,
+ UserStoreServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("UserStoreServiceRestTransport.UpdateUserStore")
+
+ @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: user_store_service.UpdateUserStoreRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> gcd_user_store.UserStore:
+ r"""Call the update user store method over HTTP.
+
+ Args:
+ request (~.user_store_service.UpdateUserStoreRequest):
+ The request object. Request message for
+ [UserStoreService.UpdateUserStore][google.cloud.discoveryengine.v1.UserStoreService.UpdateUserStore]
+ 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:
+ ~.gcd_user_store.UserStore:
+ Configures metadata that is used for
+ End User entities.
+
+ """
+
+ http_options = _BaseUserStoreServiceRestTransport._BaseUpdateUserStore._get_http_options()
+ request, metadata = self._interceptor.pre_update_user_store(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseUserStoreServiceRestTransport._BaseUpdateUserStore,
+ "_BaseUpdateUserStore__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.UserStoreServiceClient.UpdateUserStore",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "rpcName": "UpdateUserStore",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = UserStoreServiceRestTransport._UpdateUserStore._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 = gcd_user_store.UserStore()
+ pb_resp = gcd_user_store.UserStore.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_update_user_store(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_update_user_store_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = gcd_user_store.UserStore.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.UserStoreServiceClient.update_user_store",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "rpcName": "UpdateUserStore",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ @property
+ def get_user_store(
+ self,
+ ) -> Callable[[user_store_service.GetUserStoreRequest], user_store.UserStore]:
+ # 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._GetUserStore(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def update_user_store(
+ self,
+ ) -> Callable[
+ [user_store_service.UpdateUserStoreRequest], gcd_user_store.UserStore
+ ]:
+ # 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._UpdateUserStore(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(
+ _BaseUserStoreServiceRestTransport._BaseCancelOperation,
+ UserStoreServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("UserStoreServiceRestTransport.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 = _BaseUserStoreServiceRestTransport._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(
+ _BaseUserStoreServiceRestTransport._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.UserStoreServiceClient.CancelOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "rpcName": "CancelOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = UserStoreServiceRestTransport._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(
+ _BaseUserStoreServiceRestTransport._BaseGetOperation, UserStoreServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("UserStoreServiceRestTransport.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 = (
+ _BaseUserStoreServiceRestTransport._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(
+ _BaseUserStoreServiceRestTransport._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.UserStoreServiceClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "rpcName": "GetOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = UserStoreServiceRestTransport._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.UserStoreServiceAsyncClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "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(
+ _BaseUserStoreServiceRestTransport._BaseListOperations, UserStoreServiceRestStub
+ ):
+ def __hash__(self):
+ return hash("UserStoreServiceRestTransport.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 = _BaseUserStoreServiceRestTransport._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(
+ _BaseUserStoreServiceRestTransport._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.UserStoreServiceClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "rpcName": "ListOperations",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = UserStoreServiceRestTransport._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.UserStoreServiceAsyncClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "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__ = ("UserStoreServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/rest_base.py
new file mode 100644
index 000000000000..203e058de5d3
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/user_store_service/transports/rest_base.py
@@ -0,0 +1,309 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 user_store, user_store_service
+from google.cloud.discoveryengine_v1.types import user_store as gcd_user_store
+
+from .base import DEFAULT_CLIENT_INFO, UserStoreServiceTransport
+
+
+class _BaseUserStoreServiceRestTransport(UserStoreServiceTransport):
+ """Base REST backend transport for UserStoreService.
+
+ 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 _BaseGetUserStore:
+ 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/*/userStores/*}",
+ },
+ ]
+ return http_options
+
+ class _BaseUpdateUserStore:
+ 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/{user_store.name=projects/*/locations/*/userStores/*}",
+ "body": "user_store",
+ },
+ ]
+ 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__ = ("_BaseUserStoreServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/__init__.py
new file mode 100644
index 000000000000..fa7f424f82d5
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_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 WidgetConfigServiceAsyncClient
+from .client import WidgetConfigServiceClient
+
+__all__ = (
+ "WidgetConfigServiceClient",
+ "WidgetConfigServiceAsyncClient",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/async_client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/async_client.py
new file mode 100644
index 000000000000..3424f1ec0b35
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/async_client.py
@@ -0,0 +1,765 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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
+
+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 (
+ common,
+ widget_config,
+ widget_config_service,
+)
+from google.cloud.discoveryengine_v1.types import widget_config as gcd_widget_config
+
+from .client import WidgetConfigServiceClient
+from .transports.base import DEFAULT_CLIENT_INFO, WidgetConfigServiceTransport
+from .transports.grpc_asyncio import WidgetConfigServiceGrpcAsyncIOTransport
+
+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 WidgetConfigServiceAsyncClient:
+ """Service for managing
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ configuration.
+ """
+
+ _client: WidgetConfigServiceClient
+
+ # Copy defaults from the synchronous client for use here.
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
+ DEFAULT_ENDPOINT = WidgetConfigServiceClient.DEFAULT_ENDPOINT
+ DEFAULT_MTLS_ENDPOINT = WidgetConfigServiceClient.DEFAULT_MTLS_ENDPOINT
+ _DEFAULT_ENDPOINT_TEMPLATE = WidgetConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE
+ _DEFAULT_UNIVERSE = WidgetConfigServiceClient._DEFAULT_UNIVERSE
+
+ widget_config_path = staticmethod(WidgetConfigServiceClient.widget_config_path)
+ parse_widget_config_path = staticmethod(
+ WidgetConfigServiceClient.parse_widget_config_path
+ )
+ common_billing_account_path = staticmethod(
+ WidgetConfigServiceClient.common_billing_account_path
+ )
+ parse_common_billing_account_path = staticmethod(
+ WidgetConfigServiceClient.parse_common_billing_account_path
+ )
+ common_folder_path = staticmethod(WidgetConfigServiceClient.common_folder_path)
+ parse_common_folder_path = staticmethod(
+ WidgetConfigServiceClient.parse_common_folder_path
+ )
+ common_organization_path = staticmethod(
+ WidgetConfigServiceClient.common_organization_path
+ )
+ parse_common_organization_path = staticmethod(
+ WidgetConfigServiceClient.parse_common_organization_path
+ )
+ common_project_path = staticmethod(WidgetConfigServiceClient.common_project_path)
+ parse_common_project_path = staticmethod(
+ WidgetConfigServiceClient.parse_common_project_path
+ )
+ common_location_path = staticmethod(WidgetConfigServiceClient.common_location_path)
+ parse_common_location_path = staticmethod(
+ WidgetConfigServiceClient.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:
+ WidgetConfigServiceAsyncClient: The constructed client.
+ """
+ sa_info_func = (
+ WidgetConfigServiceClient.from_service_account_info.__func__ # type: ignore
+ )
+ return sa_info_func(WidgetConfigServiceAsyncClient, 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:
+ WidgetConfigServiceAsyncClient: The constructed client.
+ """
+ sa_file_func = (
+ WidgetConfigServiceClient.from_service_account_file.__func__ # type: ignore
+ )
+ return sa_file_func(WidgetConfigServiceAsyncClient, 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 WidgetConfigServiceClient.get_mtls_endpoint_and_cert_source(
+ client_options
+ ) # type: ignore
+
+ @property
+ def transport(self) -> WidgetConfigServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ WidgetConfigServiceTransport: 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 = WidgetConfigServiceClient.get_transport_class
+
+ def __init__(
+ self,
+ *,
+ credentials: Optional[ga_credentials.Credentials] = None,
+ transport: Optional[
+ Union[
+ str,
+ WidgetConfigServiceTransport,
+ Callable[..., WidgetConfigServiceTransport],
+ ]
+ ] = "grpc_asyncio",
+ client_options: Optional[ClientOptions] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the widget 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,WidgetConfigServiceTransport,Callable[..., WidgetConfigServiceTransport]]]):
+ 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 WidgetConfigServiceTransport 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 = WidgetConfigServiceClient(
+ 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.WidgetConfigServiceAsyncClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "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.WidgetConfigService",
+ "credentialsType": None,
+ },
+ )
+
+ async def get_widget_config(
+ self,
+ request: Optional[
+ Union[widget_config_service.GetWidgetConfigRequest, 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]]] = (),
+ ) -> widget_config.WidgetConfig:
+ r"""Gets a
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig].
+
+ .. 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_widget_config():
+ # Create a client
+ client = discoveryengine_v1.WidgetConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetWidgetConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_widget_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.GetWidgetConfigRequest, dict]]):
+ The request object. Request for
+ [WidgetConfigService.GetWidgetConfig][google.cloud.discoveryengine.v1.WidgetConfigService.GetWidgetConfig]
+ method.
+ name (:class:`str`):
+ Required. Full WidgetConfig resource name. Format:
+ ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/widgetConfigs/{widget_config_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.discoveryengine_v1.types.WidgetConfig:
+ WidgetConfig captures configs at the
+ Widget level.
+
+ """
+ # 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, widget_config_service.GetWidgetConfigRequest):
+ request = widget_config_service.GetWidgetConfigRequest(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_widget_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 update_widget_config(
+ self,
+ request: Optional[
+ Union[widget_config_service.UpdateWidgetConfigRequest, dict]
+ ] = None,
+ *,
+ widget_config: Optional[gcd_widget_config.WidgetConfig] = 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_widget_config.WidgetConfig:
+ r"""Update a WidgetConfig.
+
+ .. 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_widget_config():
+ # Create a client
+ client = discoveryengine_v1.WidgetConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ widget_config = discoveryengine_v1.WidgetConfig()
+ widget_config.display_name = "display_name_value"
+ widget_config.solution_type = "SOLUTION_TYPE_AI_MODE"
+
+ request = discoveryengine_v1.UpdateWidgetConfigRequest(
+ widget_config=widget_config,
+ )
+
+ # Make the request
+ response = await client.update_widget_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Optional[Union[google.cloud.discoveryengine_v1.types.UpdateWidgetConfigRequest, dict]]):
+ The request object. Request for
+ [WidgetConfigService.UpdateWidgetConfig][google.cloud.discoveryengine.v1.WidgetConfigService.UpdateWidgetConfig]
+ method.
+ widget_config (:class:`google.cloud.discoveryengine_v1.types.WidgetConfig`):
+ Required. The
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ to update.
+
+ If the caller does not have permission to update the
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig],
+ then a PERMISSION_DENIED error is returned.
+
+ If the
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ to update does not exist, a NOT_FOUND error is returned.
+
+ This corresponds to the ``widget_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
+ Indicates which fields in the provided
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ to update. The following are the only supported fields:
+
+ - [WidgetConfig.enable_autocomplete][google.cloud.discoveryengine.v1.WidgetConfig.enable_autocomplete]
+
+ If not set, all supported fields are updated.
+
+ 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.WidgetConfig:
+ WidgetConfig captures configs at the
+ Widget level.
+
+ """
+ # 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 = [widget_config, 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, widget_config_service.UpdateWidgetConfigRequest):
+ request = widget_config_service.UpdateWidgetConfigRequest(request)
+
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if widget_config is not None:
+ request.widget_config = widget_config
+ 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_widget_config
+ ]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("widget_config.name", request.widget_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 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) -> "WidgetConfigServiceAsyncClient":
+ 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__ = ("WidgetConfigServiceAsyncClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/client.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/client.py
new file mode 100644
index 000000000000..33ef87a9db27
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/client.py
@@ -0,0 +1,1069 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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__)
+
+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 (
+ common,
+ widget_config,
+ widget_config_service,
+)
+from google.cloud.discoveryengine_v1.types import widget_config as gcd_widget_config
+
+from .transports.base import DEFAULT_CLIENT_INFO, WidgetConfigServiceTransport
+from .transports.grpc import WidgetConfigServiceGrpcTransport
+from .transports.grpc_asyncio import WidgetConfigServiceGrpcAsyncIOTransport
+from .transports.rest import WidgetConfigServiceRestTransport
+
+
+class WidgetConfigServiceClientMeta(type):
+ """Metaclass for the WidgetConfigService 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[WidgetConfigServiceTransport]]
+ _transport_registry["grpc"] = WidgetConfigServiceGrpcTransport
+ _transport_registry["grpc_asyncio"] = WidgetConfigServiceGrpcAsyncIOTransport
+ _transport_registry["rest"] = WidgetConfigServiceRestTransport
+
+ def get_transport_class(
+ cls,
+ label: Optional[str] = None,
+ ) -> Type[WidgetConfigServiceTransport]:
+ """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 WidgetConfigServiceClient(metaclass=WidgetConfigServiceClientMeta):
+ """Service for managing
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ 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:
+ WidgetConfigServiceClient: 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:
+ WidgetConfigServiceClient: 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) -> WidgetConfigServiceTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ WidgetConfigServiceTransport: The transport used by the client
+ instance.
+ """
+ return self._transport
+
+ @staticmethod
+ def widget_config_path(
+ project: str,
+ location: str,
+ data_store: str,
+ widget_config: str,
+ ) -> str:
+ """Returns a fully-qualified widget_config string."""
+ return "projects/{project}/locations/{location}/dataStores/{data_store}/widgetConfigs/{widget_config}".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ widget_config=widget_config,
+ )
+
+ @staticmethod
+ def parse_widget_config_path(path: str) -> Dict[str, str]:
+ """Parses a widget_config path into its component segments."""
+ m = re.match(
+ r"^projects/(?P.+?)/locations/(?P.+?)/dataStores/(?P.+?)/widgetConfigs/(?P.+?)$",
+ path,
+ )
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_billing_account_path(
+ billing_account: str,
+ ) -> str:
+ """Returns a fully-qualified billing_account string."""
+ return "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+
+ @staticmethod
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
+ """Parse a billing_account path into its component segments."""
+ m = re.match(r"^billingAccounts/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_folder_path(
+ folder: str,
+ ) -> str:
+ """Returns a fully-qualified folder string."""
+ return "folders/{folder}".format(
+ folder=folder,
+ )
+
+ @staticmethod
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
+ """Parse a folder path into its component segments."""
+ m = re.match(r"^folders/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_organization_path(
+ organization: str,
+ ) -> str:
+ """Returns a fully-qualified organization string."""
+ return "organizations/{organization}".format(
+ organization=organization,
+ )
+
+ @staticmethod
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
+ """Parse a organization path into its component segments."""
+ m = re.match(r"^organizations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_project_path(
+ project: str,
+ ) -> str:
+ """Returns a fully-qualified project string."""
+ return "projects/{project}".format(
+ project=project,
+ )
+
+ @staticmethod
+ def parse_common_project_path(path: str) -> Dict[str, str]:
+ """Parse a project path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_location_path(
+ project: str,
+ location: str,
+ ) -> str:
+ """Returns a fully-qualified location string."""
+ return "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+
+ @staticmethod
+ def parse_common_location_path(path: str) -> Dict[str, str]:
+ """Parse a location path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @classmethod
+ def get_mtls_endpoint_and_cert_source(
+ cls, client_options: Optional[client_options_lib.ClientOptions] = None
+ ):
+ """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,
+ WidgetConfigServiceTransport,
+ Callable[..., WidgetConfigServiceTransport],
+ ]
+ ] = None,
+ client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
+ client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
+ ) -> None:
+ """Instantiates the widget 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,WidgetConfigServiceTransport,Callable[..., WidgetConfigServiceTransport]]]):
+ 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 WidgetConfigServiceTransport 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 = WidgetConfigServiceClient._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=WidgetConfigServiceClient._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, WidgetConfigServiceTransport)
+ if transport_provided:
+ # transport is a WidgetConfigServiceTransport 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(WidgetConfigServiceTransport, 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=WidgetConfigServiceClient._DEFAULT_UNIVERSE,
+ default_mtls_endpoint=WidgetConfigServiceClient.DEFAULT_MTLS_ENDPOINT,
+ default_endpoint_template=WidgetConfigServiceClient._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[WidgetConfigServiceTransport],
+ Callable[..., WidgetConfigServiceTransport],
+ ] = (
+ WidgetConfigServiceClient.get_transport_class(transport)
+ if isinstance(transport, str) or transport is None
+ else cast(Callable[..., WidgetConfigServiceTransport], 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.WidgetConfigServiceClient`.",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "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.WidgetConfigService",
+ "credentialsType": None,
+ },
+ )
+
+ def get_widget_config(
+ self,
+ request: Optional[
+ Union[widget_config_service.GetWidgetConfigRequest, 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]]] = (),
+ ) -> widget_config.WidgetConfig:
+ r"""Gets a
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig].
+
+ .. 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_widget_config():
+ # Create a client
+ client = discoveryengine_v1.WidgetConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetWidgetConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_widget_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.GetWidgetConfigRequest, dict]):
+ The request object. Request for
+ [WidgetConfigService.GetWidgetConfig][google.cloud.discoveryengine.v1.WidgetConfigService.GetWidgetConfig]
+ method.
+ name (str):
+ Required. Full WidgetConfig resource name. Format:
+ ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/widgetConfigs/{widget_config_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.discoveryengine_v1.types.WidgetConfig:
+ WidgetConfig captures configs at the
+ Widget level.
+
+ """
+ # 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, widget_config_service.GetWidgetConfigRequest):
+ request = widget_config_service.GetWidgetConfigRequest(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_widget_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 update_widget_config(
+ self,
+ request: Optional[
+ Union[widget_config_service.UpdateWidgetConfigRequest, dict]
+ ] = None,
+ *,
+ widget_config: Optional[gcd_widget_config.WidgetConfig] = 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_widget_config.WidgetConfig:
+ r"""Update a WidgetConfig.
+
+ .. 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_widget_config():
+ # Create a client
+ client = discoveryengine_v1.WidgetConfigServiceClient()
+
+ # Initialize request argument(s)
+ widget_config = discoveryengine_v1.WidgetConfig()
+ widget_config.display_name = "display_name_value"
+ widget_config.solution_type = "SOLUTION_TYPE_AI_MODE"
+
+ request = discoveryengine_v1.UpdateWidgetConfigRequest(
+ widget_config=widget_config,
+ )
+
+ # Make the request
+ response = client.update_widget_config(request=request)
+
+ # Handle the response
+ print(response)
+
+ Args:
+ request (Union[google.cloud.discoveryengine_v1.types.UpdateWidgetConfigRequest, dict]):
+ The request object. Request for
+ [WidgetConfigService.UpdateWidgetConfig][google.cloud.discoveryengine.v1.WidgetConfigService.UpdateWidgetConfig]
+ method.
+ widget_config (google.cloud.discoveryengine_v1.types.WidgetConfig):
+ Required. The
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ to update.
+
+ If the caller does not have permission to update the
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig],
+ then a PERMISSION_DENIED error is returned.
+
+ If the
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ to update does not exist, a NOT_FOUND error is returned.
+
+ This corresponds to the ``widget_config`` field
+ on the ``request`` instance; if ``request`` is provided, this
+ should not be set.
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
+ Indicates which fields in the provided
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ to update. The following are the only supported fields:
+
+ - [WidgetConfig.enable_autocomplete][google.cloud.discoveryengine.v1.WidgetConfig.enable_autocomplete]
+
+ If not set, all supported fields are updated.
+
+ 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.cloud.discoveryengine_v1.types.WidgetConfig:
+ WidgetConfig captures configs at the
+ Widget level.
+
+ """
+ # 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 = [widget_config, 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, widget_config_service.UpdateWidgetConfigRequest):
+ request = widget_config_service.UpdateWidgetConfigRequest(request)
+ # If we have keyword arguments corresponding to fields on the
+ # request, apply these.
+ if widget_config is not None:
+ request.widget_config = widget_config
+ 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_widget_config]
+
+ # Certain fields should be provided within the metadata header;
+ # add these here.
+ metadata = tuple(metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata(
+ (("widget_config.name", request.widget_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 __enter__(self) -> "WidgetConfigServiceClient":
+ 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__ = ("WidgetConfigServiceClient",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/README.rst b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/README.rst
new file mode 100644
index 000000000000..3ab11eccbb34
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/README.rst
@@ -0,0 +1,10 @@
+
+transport inheritance structure
+_______________________________
+
+``WidgetConfigServiceTransport`` is the ABC for all transports.
+
+- public child ``WidgetConfigServiceGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``).
+- public child ``WidgetConfigServiceGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``).
+- private child ``_BaseWidgetConfigServiceRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``).
+- public child ``WidgetConfigServiceRestTransport`` 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/widget_config_service/transports/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/__init__.py
new file mode 100644
index 000000000000..b569c7e76ade
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_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 WidgetConfigServiceTransport
+from .grpc import WidgetConfigServiceGrpcTransport
+from .grpc_asyncio import WidgetConfigServiceGrpcAsyncIOTransport
+from .rest import WidgetConfigServiceRestInterceptor, WidgetConfigServiceRestTransport
+
+# Compile a registry of transports.
+_transport_registry = OrderedDict() # type: Dict[str, Type[WidgetConfigServiceTransport]]
+_transport_registry["grpc"] = WidgetConfigServiceGrpcTransport
+_transport_registry["grpc_asyncio"] = WidgetConfigServiceGrpcAsyncIOTransport
+_transport_registry["rest"] = WidgetConfigServiceRestTransport
+
+__all__ = (
+ "WidgetConfigServiceTransport",
+ "WidgetConfigServiceGrpcTransport",
+ "WidgetConfigServiceGrpcAsyncIOTransport",
+ "WidgetConfigServiceRestTransport",
+ "WidgetConfigServiceRestInterceptor",
+)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/base.py
new file mode 100644
index 000000000000..19e4c98ff3d4
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/base.py
@@ -0,0 +1,242 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 widget_config, widget_config_service
+from google.cloud.discoveryengine_v1.types import widget_config as gcd_widget_config
+
+DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
+ gapic_version=package_version.__version__
+)
+DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
+
+
+class WidgetConfigServiceTransport(abc.ABC):
+ """Abstract transport class for WidgetConfigService."""
+
+ AUTH_SCOPES = (
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "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.get_widget_config: gapic_v1.method.wrap_method(
+ self.get_widget_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.update_widget_config: gapic_v1.method.wrap_method(
+ self.update_widget_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 get_widget_config(
+ self,
+ ) -> Callable[
+ [widget_config_service.GetWidgetConfigRequest],
+ Union[widget_config.WidgetConfig, Awaitable[widget_config.WidgetConfig]],
+ ]:
+ raise NotImplementedError()
+
+ @property
+ def update_widget_config(
+ self,
+ ) -> Callable[
+ [widget_config_service.UpdateWidgetConfigRequest],
+ Union[
+ gcd_widget_config.WidgetConfig, Awaitable[gcd_widget_config.WidgetConfig]
+ ],
+ ]:
+ 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__ = ("WidgetConfigServiceTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/grpc.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/grpc.py
new file mode 100644
index 000000000000..754a1080fbe7
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/grpc.py
@@ -0,0 +1,452 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 widget_config, widget_config_service
+from google.cloud.discoveryengine_v1.types import widget_config as gcd_widget_config
+
+from .base import DEFAULT_CLIENT_INFO, WidgetConfigServiceTransport
+
+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.WidgetConfigService",
+ "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.WidgetConfigService",
+ "rpcName": client_call_details.method,
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class WidgetConfigServiceGrpcTransport(WidgetConfigServiceTransport):
+ """gRPC backend transport for WidgetConfigService.
+
+ Service for managing
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ 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 get_widget_config(
+ self,
+ ) -> Callable[
+ [widget_config_service.GetWidgetConfigRequest], widget_config.WidgetConfig
+ ]:
+ r"""Return a callable for the get widget config method over gRPC.
+
+ Gets a
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig].
+
+ Returns:
+ Callable[[~.GetWidgetConfigRequest],
+ ~.WidgetConfig]:
+ 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_widget_config" not in self._stubs:
+ self._stubs["get_widget_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.WidgetConfigService/GetWidgetConfig",
+ request_serializer=widget_config_service.GetWidgetConfigRequest.serialize,
+ response_deserializer=widget_config.WidgetConfig.deserialize,
+ )
+ return self._stubs["get_widget_config"]
+
+ @property
+ def update_widget_config(
+ self,
+ ) -> Callable[
+ [widget_config_service.UpdateWidgetConfigRequest],
+ gcd_widget_config.WidgetConfig,
+ ]:
+ r"""Return a callable for the update widget config method over gRPC.
+
+ Update a WidgetConfig.
+
+ Returns:
+ Callable[[~.UpdateWidgetConfigRequest],
+ ~.WidgetConfig]:
+ 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_widget_config" not in self._stubs:
+ self._stubs["update_widget_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.WidgetConfigService/UpdateWidgetConfig",
+ request_serializer=widget_config_service.UpdateWidgetConfigRequest.serialize,
+ response_deserializer=gcd_widget_config.WidgetConfig.deserialize,
+ )
+ return self._stubs["update_widget_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__ = ("WidgetConfigServiceGrpcTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/grpc_asyncio.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/grpc_asyncio.py
new file mode 100644
index 000000000000..6ef415855b72
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/grpc_asyncio.py
@@ -0,0 +1,496 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 widget_config, widget_config_service
+from google.cloud.discoveryengine_v1.types import widget_config as gcd_widget_config
+
+from .base import DEFAULT_CLIENT_INFO, WidgetConfigServiceTransport
+from .grpc import WidgetConfigServiceGrpcTransport
+
+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.WidgetConfigService",
+ "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.WidgetConfigService",
+ "rpcName": str(client_call_details.method),
+ "response": grpc_response,
+ "metadata": grpc_response["metadata"],
+ },
+ )
+ return response
+
+
+class WidgetConfigServiceGrpcAsyncIOTransport(WidgetConfigServiceTransport):
+ """gRPC AsyncIO backend transport for WidgetConfigService.
+
+ Service for managing
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ 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 get_widget_config(
+ self,
+ ) -> Callable[
+ [widget_config_service.GetWidgetConfigRequest],
+ Awaitable[widget_config.WidgetConfig],
+ ]:
+ r"""Return a callable for the get widget config method over gRPC.
+
+ Gets a
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig].
+
+ Returns:
+ Callable[[~.GetWidgetConfigRequest],
+ Awaitable[~.WidgetConfig]]:
+ 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_widget_config" not in self._stubs:
+ self._stubs["get_widget_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.WidgetConfigService/GetWidgetConfig",
+ request_serializer=widget_config_service.GetWidgetConfigRequest.serialize,
+ response_deserializer=widget_config.WidgetConfig.deserialize,
+ )
+ return self._stubs["get_widget_config"]
+
+ @property
+ def update_widget_config(
+ self,
+ ) -> Callable[
+ [widget_config_service.UpdateWidgetConfigRequest],
+ Awaitable[gcd_widget_config.WidgetConfig],
+ ]:
+ r"""Return a callable for the update widget config method over gRPC.
+
+ Update a WidgetConfig.
+
+ Returns:
+ Callable[[~.UpdateWidgetConfigRequest],
+ Awaitable[~.WidgetConfig]]:
+ 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_widget_config" not in self._stubs:
+ self._stubs["update_widget_config"] = self._logged_channel.unary_unary(
+ "/google.cloud.discoveryengine.v1.WidgetConfigService/UpdateWidgetConfig",
+ request_serializer=widget_config_service.UpdateWidgetConfigRequest.serialize,
+ response_deserializer=gcd_widget_config.WidgetConfig.deserialize,
+ )
+ return self._stubs["update_widget_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.get_widget_config: self._wrap_method(
+ self.get_widget_config,
+ default_timeout=None,
+ client_info=client_info,
+ ),
+ self.update_widget_config: self._wrap_method(
+ self.update_widget_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__ = ("WidgetConfigServiceGrpcAsyncIOTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/rest.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/rest.py
new file mode 100644
index 000000000000..0355d0c42629
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/rest.py
@@ -0,0 +1,1096 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 widget_config, widget_config_service
+from google.cloud.discoveryengine_v1.types import widget_config as gcd_widget_config
+
+from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO
+from .rest_base import _BaseWidgetConfigServiceRestTransport
+
+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 WidgetConfigServiceRestInterceptor:
+ """Interceptor for WidgetConfigService.
+
+ 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 WidgetConfigServiceRestTransport.
+
+ .. code-block:: python
+ class MyCustomWidgetConfigServiceInterceptor(WidgetConfigServiceRestInterceptor):
+ def pre_get_widget_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_get_widget_config(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ def pre_update_widget_config(self, request, metadata):
+ logging.log(f"Received request: {request}")
+ return request, metadata
+
+ def post_update_widget_config(self, response):
+ logging.log(f"Received response: {response}")
+ return response
+
+ transport = WidgetConfigServiceRestTransport(interceptor=MyCustomWidgetConfigServiceInterceptor())
+ client = WidgetConfigServiceClient(transport=transport)
+
+
+ """
+
+ def pre_get_widget_config(
+ self,
+ request: widget_config_service.GetWidgetConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ widget_config_service.GetWidgetConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for get_widget_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the WidgetConfigService server.
+ """
+ return request, metadata
+
+ def post_get_widget_config(
+ self, response: widget_config.WidgetConfig
+ ) -> widget_config.WidgetConfig:
+ """Post-rpc interceptor for get_widget_config
+
+ DEPRECATED. Please use the `post_get_widget_config_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the WidgetConfigService server but before
+ it is returned to user code. This `post_get_widget_config` interceptor runs
+ before the `post_get_widget_config_with_metadata` interceptor.
+ """
+ return response
+
+ def post_get_widget_config_with_metadata(
+ self,
+ response: widget_config.WidgetConfig,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[widget_config.WidgetConfig, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for get_widget_config
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the WidgetConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_get_widget_config_with_metadata`
+ interceptor in new development instead of the `post_get_widget_config` interceptor.
+ When both interceptors are used, this `post_get_widget_config_with_metadata` interceptor runs after the
+ `post_get_widget_config` interceptor. The (possibly modified) response returned by
+ `post_get_widget_config` will be passed to
+ `post_get_widget_config_with_metadata`.
+ """
+ return response, metadata
+
+ def pre_update_widget_config(
+ self,
+ request: widget_config_service.UpdateWidgetConfigRequest,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[
+ widget_config_service.UpdateWidgetConfigRequest,
+ Sequence[Tuple[str, Union[str, bytes]]],
+ ]:
+ """Pre-rpc interceptor for update_widget_config
+
+ Override in a subclass to manipulate the request or metadata
+ before they are sent to the WidgetConfigService server.
+ """
+ return request, metadata
+
+ def post_update_widget_config(
+ self, response: gcd_widget_config.WidgetConfig
+ ) -> gcd_widget_config.WidgetConfig:
+ """Post-rpc interceptor for update_widget_config
+
+ DEPRECATED. Please use the `post_update_widget_config_with_metadata`
+ interceptor instead.
+
+ Override in a subclass to read or manipulate the response
+ after it is returned by the WidgetConfigService server but before
+ it is returned to user code. This `post_update_widget_config` interceptor runs
+ before the `post_update_widget_config_with_metadata` interceptor.
+ """
+ return response
+
+ def post_update_widget_config_with_metadata(
+ self,
+ response: gcd_widget_config.WidgetConfig,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]],
+ ) -> Tuple[gcd_widget_config.WidgetConfig, Sequence[Tuple[str, Union[str, bytes]]]]:
+ """Post-rpc interceptor for update_widget_config
+
+ Override in a subclass to read or manipulate the response or metadata after it
+ is returned by the WidgetConfigService server but before it is returned to user code.
+
+ We recommend only using this `post_update_widget_config_with_metadata`
+ interceptor in new development instead of the `post_update_widget_config` interceptor.
+ When both interceptors are used, this `post_update_widget_config_with_metadata` interceptor runs after the
+ `post_update_widget_config` interceptor. The (possibly modified) response returned by
+ `post_update_widget_config` will be passed to
+ `post_update_widget_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 WidgetConfigService 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 WidgetConfigService 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 WidgetConfigService 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 WidgetConfigService 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 WidgetConfigService 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 WidgetConfigService server but before
+ it is returned to user code.
+ """
+ return response
+
+
+@dataclasses.dataclass
+class WidgetConfigServiceRestStub:
+ _session: AuthorizedSession
+ _host: str
+ _interceptor: WidgetConfigServiceRestInterceptor
+
+
+class WidgetConfigServiceRestTransport(_BaseWidgetConfigServiceRestTransport):
+ """REST backend synchronous transport for WidgetConfigService.
+
+ Service for managing
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ 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[WidgetConfigServiceRestInterceptor] = 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[WidgetConfigServiceRestInterceptor]): 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 WidgetConfigServiceRestInterceptor()
+ self._prep_wrapped_messages(client_info)
+
+ class _GetWidgetConfig(
+ _BaseWidgetConfigServiceRestTransport._BaseGetWidgetConfig,
+ WidgetConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("WidgetConfigServiceRestTransport.GetWidgetConfig")
+
+ @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: widget_config_service.GetWidgetConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> widget_config.WidgetConfig:
+ r"""Call the get widget config method over HTTP.
+
+ Args:
+ request (~.widget_config_service.GetWidgetConfigRequest):
+ The request object. Request for
+ [WidgetConfigService.GetWidgetConfig][google.cloud.discoveryengine.v1.WidgetConfigService.GetWidgetConfig]
+ 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:
+ ~.widget_config.WidgetConfig:
+ WidgetConfig captures configs at the
+ Widget level.
+
+ """
+
+ http_options = _BaseWidgetConfigServiceRestTransport._BaseGetWidgetConfig._get_http_options()
+ request, metadata = self._interceptor.pre_get_widget_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseWidgetConfigServiceRestTransport._BaseGetWidgetConfig,
+ "_BaseGetWidgetConfig__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.WidgetConfigServiceClient.GetWidgetConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "rpcName": "GetWidgetConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = WidgetConfigServiceRestTransport._GetWidgetConfig._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 = widget_config.WidgetConfig()
+ pb_resp = widget_config.WidgetConfig.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_get_widget_config(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_get_widget_config_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = widget_config.WidgetConfig.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.WidgetConfigServiceClient.get_widget_config",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "rpcName": "GetWidgetConfig",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ class _UpdateWidgetConfig(
+ _BaseWidgetConfigServiceRestTransport._BaseUpdateWidgetConfig,
+ WidgetConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("WidgetConfigServiceRestTransport.UpdateWidgetConfig")
+
+ @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: widget_config_service.UpdateWidgetConfigRequest,
+ *,
+ retry: OptionalRetry = gapic_v1.method.DEFAULT,
+ timeout: Optional[float] = None,
+ metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
+ ) -> gcd_widget_config.WidgetConfig:
+ r"""Call the update widget config method over HTTP.
+
+ Args:
+ request (~.widget_config_service.UpdateWidgetConfigRequest):
+ The request object. Request for
+ [WidgetConfigService.UpdateWidgetConfig][google.cloud.discoveryengine.v1.WidgetConfigService.UpdateWidgetConfig]
+ 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:
+ ~.gcd_widget_config.WidgetConfig:
+ WidgetConfig captures configs at the
+ Widget level.
+
+ """
+
+ http_options = _BaseWidgetConfigServiceRestTransport._BaseUpdateWidgetConfig._get_http_options()
+ request, metadata = self._interceptor.pre_update_widget_config(
+ request, metadata
+ )
+ transcoded_request, body, query_params = transcode_request(
+ http_options,
+ request,
+ required_fields_default_values=getattr(
+ _BaseWidgetConfigServiceRestTransport._BaseUpdateWidgetConfig,
+ "_BaseUpdateWidgetConfig__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.WidgetConfigServiceClient.UpdateWidgetConfig",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "rpcName": "UpdateWidgetConfig",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = (
+ WidgetConfigServiceRestTransport._UpdateWidgetConfig._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 = gcd_widget_config.WidgetConfig()
+ pb_resp = gcd_widget_config.WidgetConfig.pb(resp)
+
+ json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True)
+
+ resp = self._interceptor.post_update_widget_config(resp)
+ response_metadata = [(k, str(v)) for k, v in response.headers.items()]
+ resp, _ = self._interceptor.post_update_widget_config_with_metadata(
+ resp, response_metadata
+ )
+ if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
+ logging.DEBUG
+ ): # pragma: NO COVER
+ try:
+ response_payload = gcd_widget_config.WidgetConfig.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.WidgetConfigServiceClient.update_widget_config",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "rpcName": "UpdateWidgetConfig",
+ "metadata": http_response["headers"],
+ "httpResponse": http_response,
+ },
+ )
+ return resp
+
+ @property
+ def get_widget_config(
+ self,
+ ) -> Callable[
+ [widget_config_service.GetWidgetConfigRequest], widget_config.WidgetConfig
+ ]:
+ # 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._GetWidgetConfig(self._session, self._host, self._interceptor) # type: ignore
+
+ @property
+ def update_widget_config(
+ self,
+ ) -> Callable[
+ [widget_config_service.UpdateWidgetConfigRequest],
+ gcd_widget_config.WidgetConfig,
+ ]:
+ # 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._UpdateWidgetConfig(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(
+ _BaseWidgetConfigServiceRestTransport._BaseCancelOperation,
+ WidgetConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("WidgetConfigServiceRestTransport.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 = _BaseWidgetConfigServiceRestTransport._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(
+ _BaseWidgetConfigServiceRestTransport._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.WidgetConfigServiceClient.CancelOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "rpcName": "CancelOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = WidgetConfigServiceRestTransport._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(
+ _BaseWidgetConfigServiceRestTransport._BaseGetOperation,
+ WidgetConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("WidgetConfigServiceRestTransport.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 = _BaseWidgetConfigServiceRestTransport._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(
+ _BaseWidgetConfigServiceRestTransport._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.WidgetConfigServiceClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "rpcName": "GetOperation",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = WidgetConfigServiceRestTransport._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.WidgetConfigServiceAsyncClient.GetOperation",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "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(
+ _BaseWidgetConfigServiceRestTransport._BaseListOperations,
+ WidgetConfigServiceRestStub,
+ ):
+ def __hash__(self):
+ return hash("WidgetConfigServiceRestTransport.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 = _BaseWidgetConfigServiceRestTransport._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(
+ _BaseWidgetConfigServiceRestTransport._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.WidgetConfigServiceClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "rpcName": "ListOperations",
+ "httpRequest": http_request,
+ "metadata": http_request["headers"],
+ },
+ )
+
+ # Send the request
+ response = WidgetConfigServiceRestTransport._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.WidgetConfigServiceAsyncClient.ListOperations",
+ extra={
+ "serviceName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "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__ = ("WidgetConfigServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/rest_base.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/rest_base.py
new file mode 100644
index 000000000000..e059563e4f90
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/services/widget_config_service/transports/rest_base.py
@@ -0,0 +1,327 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 widget_config, widget_config_service
+from google.cloud.discoveryengine_v1.types import widget_config as gcd_widget_config
+
+from .base import DEFAULT_CLIENT_INFO, WidgetConfigServiceTransport
+
+
+class _BaseWidgetConfigServiceRestTransport(WidgetConfigServiceTransport):
+ """Base REST backend transport for WidgetConfigService.
+
+ 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 _BaseGetWidgetConfig:
+ 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/*/dataStores/*/widgetConfigs/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v1/{name=projects/*/locations/*/collections/*/dataStores/*/widgetConfigs/*}",
+ },
+ {
+ "method": "get",
+ "uri": "/v1/{name=projects/*/locations/*/collections/*/engines/*/widgetConfigs/*}",
+ },
+ ]
+ return http_options
+
+ class _BaseUpdateWidgetConfig:
+ 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/{widget_config.name=projects/*/locations/*/dataStores/*/widgetConfigs/*}",
+ "body": "widget_config",
+ },
+ {
+ "method": "patch",
+ "uri": "/v1/{widget_config.name=projects/*/locations/*/collections/*/dataStores/*/widgetConfigs/*}",
+ "body": "widget_config",
+ },
+ {
+ "method": "patch",
+ "uri": "/v1/{widget_config.name=projects/*/locations/*/collections/*/engines/*/widgetConfigs/*}",
+ "body": "widget_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__ = ("_BaseWidgetConfigServiceRestTransport",)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/__init__.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/__init__.py
index ccd559ea3576..4b6c226e50ad 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/__init__.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/__init__.py
@@ -13,6 +13,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+from .acl_config import (
+ AclConfig,
+)
+from .acl_config_service import (
+ GetAclConfigRequest,
+ UpdateAclConfigRequest,
+)
+from .agent_gateway_setting import (
+ AgentGatewaySetting,
+)
from .answer import (
Answer,
)
@@ -26,8 +36,14 @@
)
from .assistant_service import (
AssistUserMetadata,
+ CreateAssistantRequest,
+ DeleteAssistantRequest,
+ GetAssistantRequest,
+ ListAssistantsRequest,
+ ListAssistantsResponse,
StreamAssistRequest,
StreamAssistResponse,
+ UpdateAssistantRequest,
)
from .chunk import (
Chunk,
@@ -43,10 +59,19 @@
UpdateCmekConfigMetadata,
UpdateCmekConfigRequest,
)
+from .collection import (
+ Collection,
+)
+from .collection_service import (
+ DeleteCollectionMetadata,
+ DeleteCollectionRequest,
+)
from .common import (
CustomAttribute,
+ DataProtectionPolicy,
DoubleList,
HealthcareFhirConfig,
+ IdpConfig,
IndustryVertical,
Interval,
Principal,
@@ -54,7 +79,10 @@
SearchLinkPromotion,
SearchTier,
SearchUseCase,
+ SessionConfig,
SolutionType,
+ SubscriptionTerm,
+ SubscriptionTier,
UserInfo,
)
from .completion import (
@@ -62,6 +90,8 @@
SuggestionDenyListEntry,
)
from .completion_service import (
+ AdvancedCompleteQueryRequest,
+ AdvancedCompleteQueryResponse,
CompleteQueryRequest,
CompleteQueryResponse,
)
@@ -106,6 +136,24 @@
from .custom_tuning_model import (
CustomTuningModel,
)
+from .data_connector import (
+ ActionConfig,
+ AlertPolicyConfig,
+ BAPConfig,
+ CliConfig,
+ ConnectorType,
+ DataConnector,
+ DestinationConfig,
+ DynamicTool,
+ IdentityScheduleConfig,
+ Tenant,
+)
+from .data_connector_service import (
+ GetDataConnectorRequest,
+ SetUpDataConnectorMetadata,
+ SetUpDataConnectorRequest,
+ UpdateDataConnectorRequest,
+)
from .data_store import (
AdvancedSiteSearchConfig,
DataStore,
@@ -151,10 +199,15 @@
ListEnginesResponse,
UpdateEngineRequest,
)
+from .feedback import (
+ Feedback,
+)
from .grounded_generation_service import (
CheckGroundingRequest,
CheckGroundingResponse,
CheckGroundingSpec,
+ Citation,
+ CitationMetadata,
GenerateGroundedContentRequest,
GenerateGroundedContentResponse,
GroundedGenerationContent,
@@ -205,6 +258,23 @@
ImportUserEventsResponse,
SpannerSource,
)
+from .license_config import (
+ LicenseConfig,
+)
+from .license_config_service import (
+ CreateLicenseConfigRequest,
+ DistributeLicenseConfigRequest,
+ DistributeLicenseConfigResponse,
+ GetLicenseConfigRequest,
+ ListLicenseConfigsRequest,
+ ListLicenseConfigsResponse,
+ RetractLicenseConfigRequest,
+ RetractLicenseConfigResponse,
+ UpdateLicenseConfigRequest,
+)
+from .logging import (
+ ObservabilityConfig,
+)
from .project import (
Project,
)
@@ -266,9 +336,15 @@
TrainCustomModelResponse,
)
from .serving_config import (
+ AnswerGenerationSpec,
ServingConfig,
)
from .serving_config_service import (
+ CreateServingConfigRequest,
+ DeleteServingConfigRequest,
+ GetServingConfigRequest,
+ ListServingConfigsRequest,
+ ListServingConfigsResponse,
UpdateServingConfigRequest,
)
from .session import (
@@ -331,25 +407,53 @@
WriteUserEventRequest,
)
from .user_license import (
+ LicenseConfigUsageStats,
UserLicense,
)
from .user_license_service import (
BatchUpdateUserLicensesMetadata,
BatchUpdateUserLicensesRequest,
BatchUpdateUserLicensesResponse,
+ ListLicenseConfigsUsageStatsRequest,
+ ListLicenseConfigsUsageStatsResponse,
ListUserLicensesRequest,
ListUserLicensesResponse,
)
+from .user_store import (
+ UserStore,
+)
+from .user_store_service import (
+ GetUserStoreRequest,
+ UpdateUserStoreRequest,
+)
+from .widget_config import (
+ ModelInfoView,
+ WidgetConfig,
+)
+from .widget_config_service import (
+ GetWidgetConfigRequest,
+ UpdateWidgetConfigRequest,
+)
__all__ = (
+ "AclConfig",
+ "GetAclConfigRequest",
+ "UpdateAclConfigRequest",
+ "AgentGatewaySetting",
"Answer",
"AssistAnswer",
"AssistantContent",
"AssistantGroundedContent",
"Assistant",
"AssistUserMetadata",
+ "CreateAssistantRequest",
+ "DeleteAssistantRequest",
+ "GetAssistantRequest",
+ "ListAssistantsRequest",
+ "ListAssistantsResponse",
"StreamAssistRequest",
"StreamAssistResponse",
+ "UpdateAssistantRequest",
"Chunk",
"CmekConfig",
"DeleteCmekConfigMetadata",
@@ -360,20 +464,30 @@
"SingleRegionKey",
"UpdateCmekConfigMetadata",
"UpdateCmekConfigRequest",
+ "Collection",
+ "DeleteCollectionMetadata",
+ "DeleteCollectionRequest",
"CustomAttribute",
+ "DataProtectionPolicy",
"DoubleList",
"HealthcareFhirConfig",
+ "IdpConfig",
"Interval",
"Principal",
"SearchLinkPromotion",
+ "SessionConfig",
"UserInfo",
"IndustryVertical",
"SearchAddOn",
"SearchTier",
"SearchUseCase",
"SolutionType",
+ "SubscriptionTerm",
+ "SubscriptionTier",
"CompletionSuggestion",
"SuggestionDenyListEntry",
+ "AdvancedCompleteQueryRequest",
+ "AdvancedCompleteQueryResponse",
"CompleteQueryRequest",
"CompleteQueryResponse",
"Condition",
@@ -407,6 +521,20 @@
"UpdateConversationRequest",
"UpdateSessionRequest",
"CustomTuningModel",
+ "ActionConfig",
+ "AlertPolicyConfig",
+ "BAPConfig",
+ "CliConfig",
+ "DataConnector",
+ "DestinationConfig",
+ "DynamicTool",
+ "IdentityScheduleConfig",
+ "Tenant",
+ "ConnectorType",
+ "GetDataConnectorRequest",
+ "SetUpDataConnectorMetadata",
+ "SetUpDataConnectorRequest",
+ "UpdateDataConnectorRequest",
"AdvancedSiteSearchConfig",
"DataStore",
"NaturalLanguageQueryUnderstandingConfig",
@@ -438,9 +566,12 @@
"ListEnginesRequest",
"ListEnginesResponse",
"UpdateEngineRequest",
+ "Feedback",
"CheckGroundingRequest",
"CheckGroundingResponse",
"CheckGroundingSpec",
+ "Citation",
+ "CitationMetadata",
"GenerateGroundedContentRequest",
"GenerateGroundedContentResponse",
"GroundedGenerationContent",
@@ -482,6 +613,17 @@
"ImportUserEventsRequest",
"ImportUserEventsResponse",
"SpannerSource",
+ "LicenseConfig",
+ "CreateLicenseConfigRequest",
+ "DistributeLicenseConfigRequest",
+ "DistributeLicenseConfigResponse",
+ "GetLicenseConfigRequest",
+ "ListLicenseConfigsRequest",
+ "ListLicenseConfigsResponse",
+ "RetractLicenseConfigRequest",
+ "RetractLicenseConfigResponse",
+ "UpdateLicenseConfigRequest",
+ "ObservabilityConfig",
"Project",
"ProvisionProjectMetadata",
"ProvisionProjectRequest",
@@ -522,7 +664,13 @@
"TrainCustomModelMetadata",
"TrainCustomModelRequest",
"TrainCustomModelResponse",
+ "AnswerGenerationSpec",
"ServingConfig",
+ "CreateServingConfigRequest",
+ "DeleteServingConfigRequest",
+ "GetServingConfigRequest",
+ "ListServingConfigsRequest",
+ "ListServingConfigsResponse",
"UpdateServingConfigRequest",
"Query",
"Session",
@@ -573,10 +721,20 @@
"UserEvent",
"CollectUserEventRequest",
"WriteUserEventRequest",
+ "LicenseConfigUsageStats",
"UserLicense",
"BatchUpdateUserLicensesMetadata",
"BatchUpdateUserLicensesRequest",
"BatchUpdateUserLicensesResponse",
+ "ListLicenseConfigsUsageStatsRequest",
+ "ListLicenseConfigsUsageStatsResponse",
"ListUserLicensesRequest",
"ListUserLicensesResponse",
+ "UserStore",
+ "GetUserStoreRequest",
+ "UpdateUserStoreRequest",
+ "WidgetConfig",
+ "ModelInfoView",
+ "GetWidgetConfigRequest",
+ "UpdateWidgetConfigRequest",
)
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/acl_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/acl_config.py
new file mode 100644
index 000000000000..08acd86c380d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/acl_config.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.
+#
+from __future__ import annotations
+
+from typing import MutableMapping, MutableSequence
+
+import proto # type: ignore
+
+from google.cloud.discoveryengine_v1.types import common
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "AclConfig",
+ },
+)
+
+
+class AclConfig(proto.Message):
+ r"""Access Control Configuration.
+
+ Attributes:
+ name (str):
+ Immutable. The full resource name of the acl configuration.
+ Format:
+ ``projects/{project}/locations/{location}/aclConfig``.
+
+ This field must be a UTF-8 encoded string with a length
+ limit of 1024 characters.
+ idp_config (google.cloud.discoveryengine_v1.types.IdpConfig):
+ Identity provider config.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ idp_config: common.IdpConfig = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=common.IdpConfig,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/acl_config_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/acl_config_service.py
new file mode 100644
index 000000000000..eb0f2dd85658
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/acl_config_service.py
@@ -0,0 +1,69 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.cloud.discoveryengine_v1.types import acl_config as gcd_acl_config
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "GetAclConfigRequest",
+ "UpdateAclConfigRequest",
+ },
+)
+
+
+class GetAclConfigRequest(proto.Message):
+ r"""Request message for GetAclConfigRequest method.
+
+ Attributes:
+ 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.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class UpdateAclConfigRequest(proto.Message):
+ r"""Request message for UpdateAclConfig method.
+
+ Attributes:
+ acl_config (google.cloud.discoveryengine_v1.types.AclConfig):
+
+ """
+
+ acl_config: gcd_acl_config.AclConfig = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_acl_config.AclConfig,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/agent_gateway_setting.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/agent_gateway_setting.py
new file mode 100644
index 000000000000..052237db8955
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/agent_gateway_setting.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.
+#
+from __future__ import annotations
+
+from typing import MutableMapping, MutableSequence
+
+import proto # type: ignore
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "AgentGatewaySetting",
+ },
+)
+
+
+class AgentGatewaySetting(proto.Message):
+ r"""Agent Gateway setting, which may be attached to Gemini
+ Enterprise resources for egress control of Gemini Enterprise
+ agents to agents and tools outside of Gemini Enterprise.
+
+ Attributes:
+ default_egress_agent_gateway (google.cloud.discoveryengine_v1.types.AgentGatewaySetting.AgentGatewayReference):
+ Optional. The default egress agent gateway to use, when this
+ setting is applied to a Gemini Enterprise resource.
+
+ The deployment mode must be GOOGLE_MANAGED, and the governed
+ access path must be AGENT_TO_ANYWHERE.
+ """
+
+ class AgentGatewayReference(proto.Message):
+ r"""Reference to an Agent Gateway resource.
+
+ Attributes:
+ name (str):
+ Required. Immutable. The resource name of the agent gateway.
+
+ Expected format:
+ ``projects/{project_number}/locations/{location}/agentGateways/{agent_gateway}``.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+ default_egress_agent_gateway: AgentGatewayReference = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=AgentGatewayReference,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assist_answer.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assist_answer.py
index 6f5557da2378..8c997c88e5ae 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assist_answer.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assist_answer.py
@@ -17,8 +17,13 @@
from typing import MutableMapping, MutableSequence
+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.discoveryengine_v1.types import grounded_generation_service
+
__protobuf__ = proto.module(
package="google.cloud.discoveryengine.v1",
manifest={
@@ -35,17 +40,33 @@ class AssistAnswer(proto.Message):
Attributes:
name (str):
- Immutable. Resource name of the ``AssistAnswer``. Format:
+ Immutable. Identifier. Resource name of the
+ ``AssistAnswer``. Format:
``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/sessions/{session}/assistAnswers/{assist_answer}``
This field must be a UTF-8 encoded string with a length
limit of 1024 characters.
state (google.cloud.discoveryengine_v1.types.AssistAnswer.State):
State of the answer generation.
+ connector_display_names (MutableMapping[str, str]):
+ Output only. Maps an internal connector agent name (the
+ machine identifier embedded in tool names, e.g.
+ ``custom_mcp__agent``) to the connector's
+ human-readable display name. Populated at serving time for
+ custom MCP / agent gateway connectors so user-facing
+ surfaces (e.g. the tool-call chip) can show the connector
+ name instead of its internal identifier. Empty when there
+ are no such connectors.
replies (MutableSequence[google.cloud.discoveryengine_v1.types.AssistAnswer.Reply]):
Replies of the assistant.
assist_skipped_reasons (MutableSequence[google.cloud.discoveryengine_v1.types.AssistAnswer.AssistSkippedReason]):
Reasons for not answering the assist call.
+ customer_policy_enforcement_result (google.cloud.discoveryengine_v1.types.AssistAnswer.CustomerPolicyEnforcementResult):
+ Optional. The field contains information
+ about the various policy checks' results like
+ the banned phrases or the Model Armor checks.
+ This field is populated only if the assist call
+ was skipped due to a policy violation.
"""
class State(proto.Enum):
@@ -62,6 +83,10 @@ class State(proto.Enum):
Assist operation has succeeded.
SKIPPED (4):
Assist operation has been skipped.
+ CANCELLED (5):
+ Assist operation has been cancelled (e.g.
+ client closed the stream). May contain a partial
+ response.
"""
STATE_UNSPECIFIED = 0
@@ -69,6 +94,7 @@ class State(proto.Enum):
FAILED = 2
SUCCEEDED = 3
SKIPPED = 4
+ CANCELLED = 5
class AssistSkippedReason(proto.Enum):
r"""Possible reasons for not answering an assist call.
@@ -101,6 +127,8 @@ class Reply(proto.Message):
the assistant.
This field is a member of `oneof`_ ``reply``.
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
+ The time when the reply was created.
"""
grounded_content: "AssistantGroundedContent" = proto.Field(
@@ -109,6 +137,172 @@ class Reply(proto.Message):
oneof="reply",
message="AssistantGroundedContent",
)
+ create_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=14,
+ message=timestamp_pb2.Timestamp,
+ )
+
+ class CustomerPolicyEnforcementResult(proto.Message):
+ r"""Customer policy enforcement results. Contains the results of
+ the various policy checks, like the banned phrases or the Model
+ Armor checks.
+
+ Attributes:
+ verdict (google.cloud.discoveryengine_v1.types.AssistAnswer.CustomerPolicyEnforcementResult.Verdict):
+ Final verdict of the customer policy
+ enforcement. If only one policy blocked the
+ processing, the verdict is BLOCK.
+ policy_results (MutableSequence[google.cloud.discoveryengine_v1.types.AssistAnswer.CustomerPolicyEnforcementResult.PolicyEnforcementResult]):
+ Customer policy enforcement results.
+ Populated only if the assist call was skipped
+ due to a policy violation. It contains results
+ from those filters that blocked the processing
+ of the query.
+ violation_source (google.cloud.discoveryengine_v1.types.AssistAnswer.CustomerPolicyEnforcementResult.ViolationSource):
+ Output only. The source of the violation.
+ """
+
+ class Verdict(proto.Enum):
+ r"""The verdict of the customer policy enforcement.
+
+ Values:
+ UNSPECIFIED (0):
+ Unknown value.
+ ALLOW (1):
+ There was no policy violation.
+ BLOCK (2):
+ Processing was blocked by the customer
+ policy.
+ """
+
+ UNSPECIFIED = 0
+ ALLOW = 1
+ BLOCK = 2
+
+ class ViolationSource(proto.Enum):
+ r"""If the assist call was skipped due to a policy violation,
+ this contains the source of the violation.
+
+ Values:
+ VIOLATION_SOURCE_UNSPECIFIED (0):
+ Unknown value.
+ SYSTEM (1):
+ Violation found in the system response.
+ PROMPT (2):
+ Violation found in the user prompt.
+ ATTACHMENT (3):
+ Violation found in the user attachment.
+ """
+
+ VIOLATION_SOURCE_UNSPECIFIED = 0
+ SYSTEM = 1
+ PROMPT = 2
+ ATTACHMENT = 3
+
+ class BannedPhraseEnforcementResult(proto.Message):
+ r"""Customer policy enforcement result for the banned phrase
+ policy.
+
+ Attributes:
+ banned_phrases (MutableSequence[str]):
+ The banned phrases that were found in the
+ query or the answer.
+ """
+
+ banned_phrases: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=1,
+ )
+
+ class ModelArmorEnforcementResult(proto.Message):
+ r"""Customer policy enforcement result for the Model Armor
+ policy.
+
+ 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:
+ model_armor_violation (str):
+ The Model Armor violation that was found.
+
+ This field is a member of `oneof`_ ``result``.
+ error (google.rpc.status_pb2.Status):
+ The error returned by Model Armor if the
+ policy enforcement failed for some reason.
+
+ This field is a member of `oneof`_ ``result``.
+ """
+
+ model_armor_violation: str = proto.Field(
+ proto.STRING,
+ number=1,
+ oneof="result",
+ )
+ error: status_pb2.Status = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ oneof="result",
+ message=status_pb2.Status,
+ )
+
+ class PolicyEnforcementResult(proto.Message):
+ r"""Customer policy enforcement result for a single policy type.
+
+ 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:
+ banned_phrase_enforcement_result (google.cloud.discoveryengine_v1.types.AssistAnswer.CustomerPolicyEnforcementResult.BannedPhraseEnforcementResult):
+ The policy enforcement result for the banned
+ phrase policy.
+
+ This field is a member of `oneof`_ ``enforcement_result``.
+ model_armor_enforcement_result (google.cloud.discoveryengine_v1.types.AssistAnswer.CustomerPolicyEnforcementResult.ModelArmorEnforcementResult):
+ The policy enforcement result for the Model
+ Armor policy.
+
+ This field is a member of `oneof`_ ``enforcement_result``.
+ """
+
+ banned_phrase_enforcement_result: "AssistAnswer.CustomerPolicyEnforcementResult.BannedPhraseEnforcementResult" = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ oneof="enforcement_result",
+ message="AssistAnswer.CustomerPolicyEnforcementResult.BannedPhraseEnforcementResult",
+ )
+ model_armor_enforcement_result: "AssistAnswer.CustomerPolicyEnforcementResult.ModelArmorEnforcementResult" = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ oneof="enforcement_result",
+ message="AssistAnswer.CustomerPolicyEnforcementResult.ModelArmorEnforcementResult",
+ )
+
+ verdict: "AssistAnswer.CustomerPolicyEnforcementResult.Verdict" = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum="AssistAnswer.CustomerPolicyEnforcementResult.Verdict",
+ )
+ policy_results: MutableSequence[
+ "AssistAnswer.CustomerPolicyEnforcementResult.PolicyEnforcementResult"
+ ] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=3,
+ message="AssistAnswer.CustomerPolicyEnforcementResult.PolicyEnforcementResult",
+ )
+ violation_source: "AssistAnswer.CustomerPolicyEnforcementResult.ViolationSource" = proto.Field(
+ proto.ENUM,
+ number=4,
+ enum="AssistAnswer.CustomerPolicyEnforcementResult.ViolationSource",
+ )
name: str = proto.Field(
proto.STRING,
@@ -119,6 +313,11 @@ class Reply(proto.Message):
number=2,
enum=State,
)
+ connector_display_names: MutableMapping[str, str] = proto.MapField(
+ proto.STRING,
+ proto.STRING,
+ number=14,
+ )
replies: MutableSequence[Reply] = proto.RepeatedField(
proto.MESSAGE,
number=3,
@@ -129,6 +328,11 @@ class Reply(proto.Message):
number=5,
enum=AssistSkippedReason,
)
+ customer_policy_enforcement_result: CustomerPolicyEnforcementResult = proto.Field(
+ proto.MESSAGE,
+ number=8,
+ message=CustomerPolicyEnforcementResult,
+ )
class AssistantContent(proto.Message):
@@ -326,6 +530,9 @@ class AssistantGroundedContent(proto.Message):
This field is a member of `oneof`_ ``metadata``.
content (google.cloud.discoveryengine_v1.types.AssistantContent):
The content.
+ citation_metadata (google.cloud.discoveryengine_v1.types.CitationMetadata):
+ Source attribution of the generated content. See also
+ https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview#citation_check
"""
class TextGroundingMetadata(proto.Message):
@@ -334,6 +541,9 @@ class TextGroundingMetadata(proto.Message):
Attributes:
segments (MutableSequence[google.cloud.discoveryengine_v1.types.AssistantGroundedContent.TextGroundingMetadata.Segment]):
Grounding information for parts of the text.
+ visual_segments (MutableSequence[google.cloud.discoveryengine_v1.types.AssistantGroundedContent.TextGroundingMetadata.VisualSegment]):
+ Grounding information for parts of the visual
+ content.
references (MutableSequence[google.cloud.discoveryengine_v1.types.AssistantGroundedContent.TextGroundingMetadata.Reference]):
References for the grounded text.
"""
@@ -378,14 +588,42 @@ class Segment(proto.Message):
number=6,
)
+ class VisualSegment(proto.Message):
+ r"""Grounding information for a visual segment.
+
+ Attributes:
+ reference_indices (MutableSequence[int]):
+ References for the visual segment.
+ content_id (str):
+ The content id of the visual segment. In order to display
+ the citation of the visual element, this content_id needs to
+ match with the
+ ``grounded_content.content_metadata.content_id`` field.
+ """
+
+ reference_indices: MutableSequence[int] = proto.RepeatedField(
+ proto.INT32,
+ number=1,
+ )
+ content_id: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
class Reference(proto.Message):
r"""Referenced content and related document metadata.
Attributes:
content (str):
Referenced text content.
+ code_snippet (str):
+ Chunk of code snippet from the referenced
+ document.
document_metadata (google.cloud.discoveryengine_v1.types.AssistantGroundedContent.TextGroundingMetadata.Reference.DocumentMetadata):
Document metadata.
+ chunk_metadata (google.protobuf.struct_pb2.Struct):
+ Output only. Generic structured chunk
+ metadata from upstream data source connectors.
"""
class DocumentMetadata(proto.Message):
@@ -394,6 +632,8 @@ class DocumentMetadata(proto.Message):
.. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
Attributes:
+ language (google.cloud.discoveryengine_v1.types.AssistantGroundedContent.TextGroundingMetadata.Reference.DocumentMetadata.Language):
+
document (str):
Document resource name.
@@ -418,8 +658,35 @@ class DocumentMetadata(proto.Message):
the target site.
This field is a member of `oneof`_ ``_domain``.
+ mime_type (str):
+ The mime type of the document.
+ https://www.iana.org/assignments/media-types/media-types.xhtml.
+
+ This field is a member of `oneof`_ ``_mime_type``.
"""
+ class Language(proto.Enum):
+ r"""Language of the referenced content. For now, it is only used
+ for code.
+
+ Values:
+ LANGUAGE_UNSPECIFIED (0):
+ No description available.
+ PYTHON (1):
+ No description available.
+ SQL (2):
+ No description available.
+ """
+
+ LANGUAGE_UNSPECIFIED = 0
+ PYTHON = 1
+ SQL = 2
+
+ language: "AssistantGroundedContent.TextGroundingMetadata.Reference.DocumentMetadata.Language" = proto.Field(
+ proto.ENUM,
+ number=8,
+ enum="AssistantGroundedContent.TextGroundingMetadata.Reference.DocumentMetadata.Language",
+ )
document: str = proto.Field(
proto.STRING,
number=1,
@@ -445,16 +712,30 @@ class DocumentMetadata(proto.Message):
number=5,
optional=True,
)
+ mime_type: str = proto.Field(
+ proto.STRING,
+ number=7,
+ optional=True,
+ )
content: str = proto.Field(
proto.STRING,
number=1,
)
+ code_snippet: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
document_metadata: "AssistantGroundedContent.TextGroundingMetadata.Reference.DocumentMetadata" = proto.Field(
proto.MESSAGE,
number=2,
message="AssistantGroundedContent.TextGroundingMetadata.Reference.DocumentMetadata",
)
+ chunk_metadata: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ message=struct_pb2.Struct,
+ )
segments: MutableSequence[
"AssistantGroundedContent.TextGroundingMetadata.Segment"
@@ -463,6 +744,13 @@ class DocumentMetadata(proto.Message):
number=4,
message="AssistantGroundedContent.TextGroundingMetadata.Segment",
)
+ visual_segments: MutableSequence[
+ "AssistantGroundedContent.TextGroundingMetadata.VisualSegment"
+ ] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=6,
+ message="AssistantGroundedContent.TextGroundingMetadata.VisualSegment",
+ )
references: MutableSequence[
"AssistantGroundedContent.TextGroundingMetadata.Reference"
] = proto.RepeatedField(
@@ -482,6 +770,11 @@ class DocumentMetadata(proto.Message):
number=1,
message="AssistantContent",
)
+ citation_metadata: grounded_generation_service.CitationMetadata = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ message=grounded_generation_service.CitationMetadata,
+ )
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant.py
index 1aa0864a5c55..8adbd1e837b8 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant.py
@@ -17,8 +17,11 @@
from typing import MutableMapping, MutableSequence
+import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
import proto # type: ignore
+from google.cloud.discoveryengine_v1.types import common
+
__protobuf__ = proto.module(
package="google.cloud.discoveryengine.v1",
manifest={
@@ -37,12 +40,362 @@ class Assistant(proto.Message):
It must be a UTF-8 encoded string with a length limit of
1024 characters.
+ display_name (str):
+ Required. The assistant display name.
+
+ It must be a UTF-8 encoded string with a length
+ limit of 128 characters.
+ description (str):
+ Optional. Description for additional
+ information. Expected to be shown on the
+ configuration UI, not to the users of the
+ assistant.
+ generation_config (google.cloud.discoveryengine_v1.types.Assistant.GenerationConfig):
+ Optional. Configuration for the generation of
+ the assistant response.
+ web_grounding_type (google.cloud.discoveryengine_v1.types.Assistant.WebGroundingType):
+ Optional. The type of web grounding to use.
+ default_web_grounding_toggle_off (bool):
+ Optional. This field controls the default web grounding
+ toggle for end users if ``web_grounding_type`` is set to
+ ``WEB_GROUNDING_TYPE_GOOGLE_SEARCH`` or
+ ``WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH``. By default,
+ this field is set to false. If ``web_grounding_type`` is
+ ``WEB_GROUNDING_TYPE_GOOGLE_SEARCH`` or
+ ``WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH``, end users will
+ have web grounding enabled by default on UI. If true,
+ grounding toggle will be disabled by default on UI. End
+ users can still enable web grounding in the UI if web
+ grounding is enabled.
+ enabled_tools (MutableMapping[str, google.cloud.discoveryengine_v1.types.Assistant.ToolList]):
+ Optional. Note: not implemented yet. Use
+ [enabled_actions][google.cloud.discoveryengine.v1.Assistant.enabled_actions]
+ instead. The enabled tools on this assistant. The keys are
+ connector name, for example
+ "projects/{projectId}/locations/{locationId}/collections/{collectionId}/dataconnector
+ The values consist of admin enabled tools towards the
+ connector instance. Admin can selectively enable multiple
+ tools on any of the connector instances that they created in
+ the project. For example {"jira1ConnectorName": [(toolId1,
+ "createTicket"), (toolId2, "transferTicket")],
+ "gmail1ConnectorName": [(toolId3, "sendEmail"),..] }
+ customer_policy (google.cloud.discoveryengine_v1.types.Assistant.CustomerPolicy):
+ Optional. Customer policy for the assistant.
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. Represents the time when this
+ Assistant was created.
+ update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. Represents the time when this
+ Assistant was most recently updated.
"""
+ class WebGroundingType(proto.Enum):
+ r"""The type of web grounding to use.
+
+ Values:
+ WEB_GROUNDING_TYPE_UNSPECIFIED (0):
+ Default, unspecified setting. This is the
+ same as disabled.
+ WEB_GROUNDING_TYPE_DISABLED (1):
+ Web grounding is disabled.
+ WEB_GROUNDING_TYPE_GOOGLE_SEARCH (2):
+ Grounding with Google Search is enabled.
+ WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH (3):
+ Grounding with Enterprise Web Search is
+ enabled.
+ """
+
+ WEB_GROUNDING_TYPE_UNSPECIFIED = 0
+ WEB_GROUNDING_TYPE_DISABLED = 1
+ WEB_GROUNDING_TYPE_GOOGLE_SEARCH = 2
+ WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH = 3
+
+ class GenerationConfig(proto.Message):
+ r"""Configuration for the generation of the assistant response.
+
+ Attributes:
+ default_model_id (str):
+ Optional. The default model to use for
+ assistant.
+ allowed_model_ids (MutableSequence[str]):
+ Optional. The list of models that are allowed
+ to be used for assistant.
+ system_instruction (google.cloud.discoveryengine_v1.types.Assistant.GenerationConfig.SystemInstruction):
+ System instruction, also known as the prompt
+ preamble for LLM calls. See also
+ https://cloud.google.com/vertex-ai/generative-ai/docs/learn/prompts/system-instructions
+ default_language (str):
+ The default language to use for the generation of the
+ assistant response. Use an ISO 639-1 language code such as
+ ``en``. If not specified, the language will be automatically
+ detected.
+ """
+
+ class SystemInstruction(proto.Message):
+ r"""System instruction, also known as the prompt preamble for LLM
+ calls.
+
+ Attributes:
+ additional_system_instruction (str):
+ Optional. Additional system instruction that
+ will be added to the default system instruction.
+ """
+
+ additional_system_instruction: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+ default_model_id: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ allowed_model_ids: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=2,
+ )
+ system_instruction: "Assistant.GenerationConfig.SystemInstruction" = (
+ proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message="Assistant.GenerationConfig.SystemInstruction",
+ )
+ )
+ default_language: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+
+ class ToolInfo(proto.Message):
+ r"""Information to identify a tool.
+
+ Attributes:
+ tool_name (str):
+ The name of the tool as defined by
+ DataConnectorService.QueryAvailableActions. Note: it's using
+ ``action`` in the DataConnectorService apis, but they are
+ the same as the ``tool`` here.
+ tool_display_name (str):
+ The display name of the tool.
+ """
+
+ tool_name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ tool_display_name: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+ class ToolList(proto.Message):
+ r"""The enabled tools on a connector
+
+ Attributes:
+ tool_info (MutableSequence[google.cloud.discoveryengine_v1.types.Assistant.ToolInfo]):
+ The list of tools with corresponding tool
+ information.
+ """
+
+ tool_info: MutableSequence["Assistant.ToolInfo"] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message="Assistant.ToolInfo",
+ )
+
+ class CustomerPolicy(proto.Message):
+ r"""Customer-defined policy for the assistant.
+
+ Attributes:
+ banned_phrases (MutableSequence[google.cloud.discoveryengine_v1.types.Assistant.CustomerPolicy.BannedPhrase]):
+ Optional. List of banned phrases.
+ model_armor_config (google.cloud.discoveryengine_v1.types.Assistant.CustomerPolicy.ModelArmorConfig):
+ Optional. Model Armor configuration to be
+ used for sanitizing user prompts and assistant
+ responses.
+ data_protection_policy (google.cloud.discoveryengine_v1.types.DataProtectionPolicy):
+ Optional. Data protection policy to be used
+ for sanitizing file uploads.
+ """
+
+ class BannedPhrase(proto.Message):
+ r"""Definition of a customer-defined banned phrase. A banned
+ phrase is not allowed to appear in the user query or the LLM
+ response, or else the answer will be refused.
+
+ Attributes:
+ phrase (str):
+ Required. The raw string content to be
+ banned.
+ match_type (google.cloud.discoveryengine_v1.types.Assistant.CustomerPolicy.BannedPhrase.BannedPhraseMatchType):
+ Optional. Match type for the banned phrase.
+ ignore_diacritics (bool):
+ Optional. If true, diacritical marks (e.g.,
+ accents, umlauts) are ignored when matching
+ banned phrases. For example, "cafe" would match
+ "café".
+ """
+
+ class BannedPhraseMatchType(proto.Enum):
+ r"""The matching method for the banned phrase.
+
+ Values:
+ BANNED_PHRASE_MATCH_TYPE_UNSPECIFIED (0):
+ Defaults to SIMPLE_STRING_MATCH.
+ SIMPLE_STRING_MATCH (1):
+ The banned phrase matches if it is found
+ anywhere in the text as an exact substring.
+ WORD_BOUNDARY_STRING_MATCH (2):
+ Banned phrase only matches if the pattern
+ found in the text is surrounded by word
+ delimiters. The phrase itself may still contain
+ word delimiters.
+ """
+
+ BANNED_PHRASE_MATCH_TYPE_UNSPECIFIED = 0
+ SIMPLE_STRING_MATCH = 1
+ WORD_BOUNDARY_STRING_MATCH = 2
+
+ phrase: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ match_type: "Assistant.CustomerPolicy.BannedPhrase.BannedPhraseMatchType" = proto.Field(
+ proto.ENUM,
+ number=2,
+ enum="Assistant.CustomerPolicy.BannedPhrase.BannedPhraseMatchType",
+ )
+ ignore_diacritics: bool = proto.Field(
+ proto.BOOL,
+ number=3,
+ )
+
+ class ModelArmorConfig(proto.Message):
+ r"""Configuration for customer defined Model Armor templates to
+ be used for sanitizing user prompts and assistant responses.
+
+ Attributes:
+ user_prompt_template (str):
+ Optional. The resource name of the Model Armor template for
+ sanitizing user prompts. Format:
+ ``projects/{project}/locations/{location}/templates/{template_id}``
+
+ If not specified, no sanitization will be applied to the
+ user prompt.
+ response_template (str):
+ Optional. The resource name of the Model Armor template for
+ sanitizing assistant responses. Format:
+ ``projects/{project}/locations/{location}/templates/{template_id}``
+
+ If not specified, no sanitization will be applied to the
+ assistant response.
+ failure_mode (google.cloud.discoveryengine_v1.types.Assistant.CustomerPolicy.ModelArmorConfig.FailureMode):
+ Optional. Defines the failure mode for Model
+ Armor sanitization.
+ """
+
+ class FailureMode(proto.Enum):
+ r"""Determines the behavior when Model Armor fails to process a
+ request.
+
+ Values:
+ FAILURE_MODE_UNSPECIFIED (0):
+ Unspecified failure mode, default behavior is
+ ``FAIL_CLOSED``.
+ FAIL_OPEN (1):
+ In case of a Model Armor processing failure,
+ the request is allowed to proceed without any
+ changes.
+ FAIL_CLOSED (2):
+ In case of a Model Armor processing failure,
+ the request is rejected.
+ """
+
+ FAILURE_MODE_UNSPECIFIED = 0
+ FAIL_OPEN = 1
+ FAIL_CLOSED = 2
+
+ user_prompt_template: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ response_template: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ failure_mode: "Assistant.CustomerPolicy.ModelArmorConfig.FailureMode" = (
+ proto.Field(
+ proto.ENUM,
+ number=3,
+ enum="Assistant.CustomerPolicy.ModelArmorConfig.FailureMode",
+ )
+ )
+
+ banned_phrases: MutableSequence["Assistant.CustomerPolicy.BannedPhrase"] = (
+ proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message="Assistant.CustomerPolicy.BannedPhrase",
+ )
+ )
+ model_armor_config: "Assistant.CustomerPolicy.ModelArmorConfig" = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message="Assistant.CustomerPolicy.ModelArmorConfig",
+ )
+ data_protection_policy: common.DataProtectionPolicy = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message=common.DataProtectionPolicy,
+ )
+
name: str = proto.Field(
proto.STRING,
number=1,
)
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ description: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ generation_config: GenerationConfig = proto.Field(
+ proto.MESSAGE,
+ number=19,
+ message=GenerationConfig,
+ )
+ web_grounding_type: WebGroundingType = proto.Field(
+ proto.ENUM,
+ number=4,
+ enum=WebGroundingType,
+ )
+ default_web_grounding_toggle_off: bool = proto.Field(
+ proto.BOOL,
+ number=22,
+ )
+ enabled_tools: MutableMapping[str, ToolList] = proto.MapField(
+ proto.STRING,
+ proto.MESSAGE,
+ number=18,
+ message=ToolList,
+ )
+ customer_policy: CustomerPolicy = proto.Field(
+ proto.MESSAGE,
+ number=12,
+ message=CustomerPolicy,
+ )
+ create_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=24,
+ message=timestamp_pb2.Timestamp,
+ )
+ update_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=25,
+ message=timestamp_pb2.Timestamp,
+ )
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant_service.py
index 4d902a7b305a..e4ad6b09b94f 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/assistant_service.py
@@ -17,9 +17,11 @@
from typing import MutableMapping, MutableSequence
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
import proto # type: ignore
from google.cloud.discoveryengine_v1.types import assist_answer, search_service
+from google.cloud.discoveryengine_v1.types import assistant as gcd_assistant
from google.cloud.discoveryengine_v1.types import session as gcd_session
__protobuf__ = proto.module(
@@ -28,6 +30,12 @@
"AssistUserMetadata",
"StreamAssistRequest",
"StreamAssistResponse",
+ "CreateAssistantRequest",
+ "DeleteAssistantRequest",
+ "GetAssistantRequest",
+ "ListAssistantsRequest",
+ "ListAssistantsResponse",
+ "UpdateAssistantRequest",
},
)
@@ -145,8 +153,10 @@ class ToolsSpec(proto.Message):
Optional. Specification of the web grounding tool. If field
is present, enables grounding with web search. Works only if
[Assistant.web_grounding_type][google.cloud.discoveryengine.v1.Assistant.web_grounding_type]
- is [WEB_GROUNDING_TYPE_GOOGLE_SEARCH][] or
- [WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH][].
+ is
+ [WEB_GROUNDING_TYPE_GOOGLE_SEARCH][google.cloud.discoveryengine.v1.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_GOOGLE_SEARCH]
+ or
+ [WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH][google.cloud.discoveryengine.v1.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH].
image_generation_spec (google.cloud.discoveryengine_v1.types.StreamAssistRequest.ToolsSpec.ImageGenerationSpec):
Optional. Specification of the image
generation tool.
@@ -309,17 +319,32 @@ class StreamAssistResponse(proto.Message):
[AssistAnswer.replies][google.cloud.discoveryengine.v1.AssistAnswer.replies]
field in each response will contain replies (reply
fragments) to be appended to the ones received in previous
- responses. [AssistAnswer.name][] won't be filled.
+ responses.
+ [AssistAnswer.name][google.cloud.discoveryengine.v1.AssistAnswer.name]
+ won't be filled.
If the state is ``SUCCEEDED``, ``FAILED`` or ``SKIPPED``,
- the response is the last response and [AssistAnswer.name][]
+ the response is the last response and
+ [AssistAnswer.name][google.cloud.discoveryengine.v1.AssistAnswer.name]
will have a value.
session_info (google.cloud.discoveryengine_v1.types.StreamAssistResponse.SessionInfo):
- Session information.
+ Session information. Only included in the
+ final StreamAssistResponse of the response
+ stream.
assist_token (str):
A global unique ID that identifies the
current pair of request and stream of responses.
Used for feedback and support.
+ invocation_tools (MutableSequence[str]):
+ The tool names of the tools that were
+ invoked.
+ invoked_skills (MutableSequence[google.cloud.discoveryengine_v1.types.StreamAssistResponse.InvokedSkill]):
+ The skills executed during the turn.
+ connector_auth_errors (MutableSequence[google.cloud.discoveryengine_v1.types.StreamAssistResponse.ConnectorAuthError]):
+ Per-connector authentication errors
+ encountered during the request. Present when one
+ or more connectors failed authentication but the
+ request proceeded with the remaining connectors.
"""
class SessionInfo(proto.Message):
@@ -338,6 +363,47 @@ class SessionInfo(proto.Message):
number=1,
)
+ class InvokedSkill(proto.Message):
+ r"""Represents a skill used during the assist call.
+
+ Attributes:
+ name (str):
+ The resource name of the skill.
+ display_name (str):
+ The display name of the skill.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+ class ConnectorAuthError(proto.Message):
+ r"""Describes an authentication error for a specific data
+ connector.
+
+ Attributes:
+ data_connector (str):
+ Resource name of the data connector that
+ failed authentication.
+ error_message (str):
+ Human-readable error message describing the
+ auth failure.
+ """
+
+ data_connector: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ error_message: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
answer: assist_answer.AssistAnswer = proto.Field(
proto.MESSAGE,
number=1,
@@ -352,6 +418,220 @@ class SessionInfo(proto.Message):
proto.STRING,
number=4,
)
+ invocation_tools: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=8,
+ )
+ invoked_skills: MutableSequence[InvokedSkill] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=10,
+ message=InvokedSkill,
+ )
+ connector_auth_errors: MutableSequence[ConnectorAuthError] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=11,
+ message=ConnectorAuthError,
+ )
+
+
+class CreateAssistantRequest(proto.Message):
+ r"""Request for the
+ [AssistantService.CreateAssistant][google.cloud.discoveryengine.v1.AssistantService.CreateAssistant]
+ method.
+
+ Attributes:
+ parent (str):
+ Required. The parent resource name. Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}``
+ assistant (google.cloud.discoveryengine_v1.types.Assistant):
+ Required. The
+ [Assistant][google.cloud.discoveryengine.v1.Assistant] to
+ create.
+ assistant_id (str):
+ Required. The ID to use for the
+ [Assistant][google.cloud.discoveryengine.v1.Assistant],
+ which will become the final component of the
+ [Assistant][google.cloud.discoveryengine.v1.Assistant]'s
+ resource name.
+
+ This field must conform to
+ `RFC-1034 `__ with a
+ length limit of 63 characters.
+ """
+
+ parent: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ assistant: gcd_assistant.Assistant = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=gcd_assistant.Assistant,
+ )
+ assistant_id: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+
+class DeleteAssistantRequest(proto.Message):
+ r"""Request message for the
+ [AssistantService.DeleteAssistant][google.cloud.discoveryengine.v1.AssistantService.DeleteAssistant]
+ method.
+
+ Attributes:
+ name (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.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class GetAssistantRequest(proto.Message):
+ r"""Request message for the
+ [AssistantService.GetAssistant][google.cloud.discoveryengine.v1.AssistantService.GetAssistant]
+ method.
+
+ Attributes:
+ name (str):
+ Required. Resource name of
+ [Assistant][google.cloud.discoveryengine.v1.Assistant].
+ Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/assistants/{assistant}``
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class ListAssistantsRequest(proto.Message):
+ r"""Request message for the
+ [AssistantService.ListAssistants][google.cloud.discoveryengine.v1.AssistantService.ListAssistants]
+ method.
+
+ Attributes:
+ parent (str):
+ Required. The parent resource name. Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}``
+ page_size (int):
+ Maximum number of
+ [Assistant][google.cloud.discoveryengine.v1.Assistant]s to
+ return. If unspecified, defaults to 100. The maximum allowed
+ value is 1000; anything above that will be coerced down to
+ 1000.
+ page_token (str):
+ A page token
+ [ListAssistantsResponse.next_page_token][google.cloud.discoveryengine.v1.ListAssistantsResponse.next_page_token],
+ received from a previous
+ [AssistantService.ListAssistants][google.cloud.discoveryengine.v1.AssistantService.ListAssistants]
+ call. Provide this to retrieve the subsequent page.
+
+ When paginating, all other parameters provided to
+ [ListAssistants][google.cloud.discoveryengine.v1.AssistantService.ListAssistants]
+ must match the call that provided the page token.
+ """
+
+ parent: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ page_size: int = proto.Field(
+ proto.INT32,
+ number=2,
+ )
+ page_token: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+
+class ListAssistantsResponse(proto.Message):
+ r"""Response message for the
+ [AssistantService.ListAssistants][google.cloud.discoveryengine.v1.AssistantService.ListAssistants]
+ method.
+
+ Attributes:
+ assistants (MutableSequence[google.cloud.discoveryengine_v1.types.Assistant]):
+ All the customer's
+ [Assistant][google.cloud.discoveryengine.v1.Assistant]s.
+ next_page_token (str):
+ A token that can be sent as
+ [ListAssistantsRequest.page_token][google.cloud.discoveryengine.v1.ListAssistantsRequest.page_token]
+ to retrieve the next page. If this field is omitted, there
+ are no subsequent pages.
+ """
+
+ @property
+ def raw_page(self):
+ return self
+
+ assistants: MutableSequence[gcd_assistant.Assistant] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_assistant.Assistant,
+ )
+ next_page_token: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+
+class UpdateAssistantRequest(proto.Message):
+ r"""Request message for the
+ [AssistantService.UpdateAssistant][google.cloud.discoveryengine.v1.AssistantService.UpdateAssistant]
+ method.
+
+ Attributes:
+ assistant (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.
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
+ The list of fields to update.
+ """
+
+ assistant: gcd_assistant.Assistant = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_assistant.Assistant,
+ )
+ update_mask: field_mask_pb2.FieldMask = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=field_mask_pb2.FieldMask,
+ )
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/chunk.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/chunk.py
index 1dbd6e3d0c83..a9ee51dd7226 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/chunk.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/chunk.py
@@ -107,6 +107,9 @@ class DocumentMetadata(proto.Message):
Uri of the document.
title (str):
Title of the document.
+ mime_type (str):
+ The mime type of the document.
+ https://www.iana.org/assignments/media-types/media-types.xhtml.
struct_data (google.protobuf.struct_pb2.Struct):
Data representation. The structured JSON data for the
document. It should conform to the registered
@@ -122,6 +125,10 @@ class DocumentMetadata(proto.Message):
proto.STRING,
number=2,
)
+ mime_type: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
struct_data: struct_pb2.Struct = proto.Field(
proto.MESSAGE,
number=3,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/cmek_config_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/cmek_config_service.py
index d314bb3da73a..4d746c218518 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/cmek_config_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/cmek_config_service.py
@@ -112,8 +112,9 @@ class CmekConfig(proto.Message):
resources
``projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{keyId}``.
kms_key_version (str):
- KMS key version resource name which will be used to encrypt
- resources ``/cryptoKeyVersions/{keyVersion}``.
+ Output only. KMS key version resource name which will be
+ used to encrypt resources
+ ``/cryptoKeyVersions/{keyVersion}``.
state (google.cloud.discoveryengine_v1.types.CmekConfig.State):
Output only. The states of the CmekConfig.
is_default (bool):
@@ -155,6 +156,11 @@ class State(proto.Enum):
DELETED (8):
The KMS key is soft deleted. Some cleanup
policy will eventually be applied.
+ EXPIRED (9):
+ The KMS key is expired, meaning the key has
+ been disabled for 30+ days. The customer can
+ call DeleteCmekConfig to change the state to
+ DELETED.
"""
STATE_UNSPECIFIED = 0
@@ -166,6 +172,7 @@ class State(proto.Enum):
UNUSABLE = 5
ACTIVE_ROTATING = 6
DELETED = 8
+ EXPIRED = 9
class NotebookLMState(proto.Enum):
r"""States of NotebookLM.
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/collection.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/collection.py
new file mode 100644
index 000000000000..d1c1b38d1448
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/collection.py
@@ -0,0 +1,69 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.discoveryengine.v1",
+ manifest={
+ "Collection",
+ },
+)
+
+
+class Collection(proto.Message):
+ r"""Collection is a container for configuring resources and
+ access to a set of DataStores.
+
+ Attributes:
+ name (str):
+ Immutable. The full resource name of the Collection. Format:
+ ``projects/{project}/locations/{location}/collections/{collection_id}``.
+
+ This field must be a UTF-8 encoded string with a length
+ limit of 1024 characters.
+ display_name (str):
+ Required. The Collection display name.
+
+ This field must be a UTF-8 encoded string with a length
+ limit of 128 characters. Otherwise, an INVALID_ARGUMENT
+ error is returned.
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. Timestamp the
+ [Collection][google.cloud.discoveryengine.v1.Collection] was
+ created at.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ create_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=timestamp_pb2.Timestamp,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/collection_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/collection_service.py
new file mode 100644
index 000000000000..74b411e45767
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/collection_service.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.discoveryengine.v1",
+ manifest={
+ "DeleteCollectionRequest",
+ "DeleteCollectionMetadata",
+ },
+)
+
+
+class DeleteCollectionRequest(proto.Message):
+ r"""Request message for
+ [CollectionService.DeleteCollection][google.cloud.discoveryengine.v1.CollectionService.DeleteCollection]
+ method.
+
+ Attributes:
+ name (str):
+ Required. The full resource name of the Collection, in the
+ format of
+ ``projects/{project}/locations/{location}/collections/{collection}``.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class DeleteCollectionMetadata(proto.Message):
+ r"""Metadata related to the progress of the
+ [CollectionService.UpdateCollection][] operation. This will be
+ returned by the google.longrunning.Operation.metadata field.
+
+ Attributes:
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
+ Operation create time.
+ update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Operation last update time. If the operation
+ is done, this is also the finish time.
+ """
+
+ create_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=timestamp_pb2.Timestamp,
+ )
+ update_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=timestamp_pb2.Timestamp,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/common.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/common.py
index 72ca6870c063..559cacaaeb03 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/common.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/common.py
@@ -17,6 +17,7 @@
from typing import MutableMapping, MutableSequence
+import google.type.latlng_pb2 as latlng_pb2 # type: ignore
import proto # type: ignore
__protobuf__ = proto.module(
@@ -27,13 +28,18 @@
"SearchUseCase",
"SearchTier",
"SearchAddOn",
+ "SubscriptionTier",
+ "SubscriptionTerm",
"Interval",
"CustomAttribute",
"UserInfo",
"DoubleList",
+ "IdpConfig",
"Principal",
"HealthcareFhirConfig",
"SearchLinkPromotion",
+ "SessionConfig",
+ "DataProtectionPolicy",
},
)
@@ -78,6 +84,8 @@ class SolutionType(proto.Enum):
It's used for Generative chat engine only, the associated
data stores must enrolled with ``SOLUTION_TYPE_CHAT``
solution.
+ SOLUTION_TYPE_AI_MODE (5):
+ Used for AI Mode.
"""
SOLUTION_TYPE_UNSPECIFIED = 0
@@ -85,6 +93,7 @@ class SolutionType(proto.Enum):
SOLUTION_TYPE_SEARCH = 2
SOLUTION_TYPE_CHAT = 3
SOLUTION_TYPE_GENERATIVE_CHAT = 4
+ SOLUTION_TYPE_AI_MODE = 5
class SearchUseCase(proto.Enum):
@@ -143,6 +152,95 @@ class SearchAddOn(proto.Enum):
SEARCH_ADD_ON_LLM = 1
+class SubscriptionTier(proto.Enum):
+ r"""Subscription tier information.
+
+ Values:
+ SUBSCRIPTION_TIER_UNSPECIFIED (0):
+ Default value.
+ SUBSCRIPTION_TIER_SEARCH (1):
+ Search tier.
+ Search tier can access Vertex AI Search features
+ and NotebookLM features.
+ SUBSCRIPTION_TIER_SEARCH_AND_ASSISTANT (2):
+ Gemini Enterprise Plus tier.
+ SUBSCRIPTION_TIER_NOTEBOOK_LM (3):
+ NotebookLM tier.
+ NotebookLM is a subscription tier can only
+ access NotebookLM features.
+ SUBSCRIPTION_TIER_FRONTLINE_WORKER (4):
+ Gemini Frontline worker tier.
+ SUBSCRIPTION_TIER_AGENTSPACE_STARTER (10):
+ Gemini Business Starter tier.
+ SUBSCRIPTION_TIER_AGENTSPACE_BUSINESS (6):
+ Gemini Business tier.
+ SUBSCRIPTION_TIER_ENTERPRISE (7):
+ Gemini Enterprise Standard tier.
+ SUBSCRIPTION_TIER_ENTERPRISE_EMERGING (15):
+ Gemini Enterprise Standard tier for emerging
+ markets.
+ SUBSCRIPTION_TIER_EDU (8):
+ Gemini Enterprise EDU tier.
+ SUBSCRIPTION_TIER_EDU_PRO (9):
+ Gemini Enterprise EDU Pro tier.
+ SUBSCRIPTION_TIER_EDU_EMERGING (11):
+ Gemini Enterprise EDU tier for emerging
+ market only.
+ SUBSCRIPTION_TIER_EDU_PRO_EMERGING (12):
+ Gemini Enterprise EDU Pro tier for emerging
+ market.
+ SUBSCRIPTION_TIER_FRONTLINE_STARTER (13):
+ Gemini Frontline Starter tier.
+ SUBSCRIPTION_TIER_CONSUMPTION_ONLY (16):
+ Represents the Gemini Enterprise
+ Consumption-only tier: $0 subscription billed
+ purely on usage (PAYG).
+ SUBSCRIPTION_TIER_EDU_GOV_EMERGING (17):
+ Gemini Enterprise EDU tier for government in
+ emerging markets.
+ """
+
+ SUBSCRIPTION_TIER_UNSPECIFIED = 0
+ SUBSCRIPTION_TIER_SEARCH = 1
+ SUBSCRIPTION_TIER_SEARCH_AND_ASSISTANT = 2
+ SUBSCRIPTION_TIER_NOTEBOOK_LM = 3
+ SUBSCRIPTION_TIER_FRONTLINE_WORKER = 4
+ SUBSCRIPTION_TIER_AGENTSPACE_STARTER = 10
+ SUBSCRIPTION_TIER_AGENTSPACE_BUSINESS = 6
+ SUBSCRIPTION_TIER_ENTERPRISE = 7
+ SUBSCRIPTION_TIER_ENTERPRISE_EMERGING = 15
+ SUBSCRIPTION_TIER_EDU = 8
+ SUBSCRIPTION_TIER_EDU_PRO = 9
+ SUBSCRIPTION_TIER_EDU_EMERGING = 11
+ SUBSCRIPTION_TIER_EDU_PRO_EMERGING = 12
+ SUBSCRIPTION_TIER_FRONTLINE_STARTER = 13
+ SUBSCRIPTION_TIER_CONSUMPTION_ONLY = 16
+ SUBSCRIPTION_TIER_EDU_GOV_EMERGING = 17
+
+
+class SubscriptionTerm(proto.Enum):
+ r"""Subscription term.
+
+ Values:
+ SUBSCRIPTION_TERM_UNSPECIFIED (0):
+ Default value, do not use.
+ SUBSCRIPTION_TERM_ONE_MONTH (1):
+ 1 month.
+ SUBSCRIPTION_TERM_ONE_YEAR (2):
+ 1 year.
+ SUBSCRIPTION_TERM_THREE_YEARS (3):
+ 3 years.
+ SUBSCRIPTION_TERM_CUSTOM (6):
+ Custom term. Must set the end_date.
+ """
+
+ SUBSCRIPTION_TERM_UNSPECIFIED = 0
+ SUBSCRIPTION_TERM_ONE_MONTH = 1
+ SUBSCRIPTION_TERM_ONE_YEAR = 2
+ SUBSCRIPTION_TERM_THREE_YEARS = 3
+ SUBSCRIPTION_TERM_CUSTOM = 6
+
+
class Interval(proto.Message):
r"""A floating point interval.
@@ -252,6 +350,11 @@ class UserInfo(proto.Message):
The field must be a UTF-8 encoded string with a length limit
of 128 characters. Otherwise, an ``INVALID_ARGUMENT`` error
is returned.
+
+ Represents an opaque ID to the Search API. The Search API
+ doesn't interpret the value in any way. This field is used
+ to associate events with a user across sessions if the
+ events are being uploaded.
user_agent (str):
User agent as included in the HTTP header.
@@ -268,8 +371,49 @@ class UserInfo(proto.Message):
time_zone (str):
Optional. IANA time zone, e.g.
Europe/Budapest.
+ precise_location (google.cloud.discoveryengine_v1.types.UserInfo.PreciseLocation):
+ Optional. Input only. Precise location of the
+ user. It is used in Custom Ranking to calculate
+ the distance between the user and the relevant
+ documents.
"""
+ class PreciseLocation(proto.Message):
+ r"""Precise location info with multiple representation options.
+
+ 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:
+ point (google.type.latlng_pb2.LatLng):
+ Optional. Location represented by a
+ latitude/longitude point.
+
+ This field is a member of `oneof`_ ``location``.
+ address (str):
+ Location represented by a natural language
+ address. Will later be geocoded and converted to
+ either a point or a polygon.
+
+ This field is a member of `oneof`_ ``location``.
+ """
+
+ point: latlng_pb2.LatLng = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ oneof="location",
+ message=latlng_pb2.LatLng,
+ )
+ address: str = proto.Field(
+ proto.STRING,
+ number=2,
+ oneof="location",
+ )
+
user_id: str = proto.Field(
proto.STRING,
number=1,
@@ -282,6 +426,11 @@ class UserInfo(proto.Message):
proto.STRING,
number=3,
)
+ precise_location: PreciseLocation = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=PreciseLocation,
+ )
class DoubleList(proto.Message):
@@ -298,6 +447,58 @@ class DoubleList(proto.Message):
)
+class IdpConfig(proto.Message):
+ r"""Identity Provider Config.
+
+ Attributes:
+ idp_type (google.cloud.discoveryengine_v1.types.IdpConfig.IdpType):
+ Identity provider type configured.
+ external_idp_config (google.cloud.discoveryengine_v1.types.IdpConfig.ExternalIdpConfig):
+ External Identity provider config.
+ """
+
+ class IdpType(proto.Enum):
+ r"""Identity Provider Type.
+
+ Values:
+ IDP_TYPE_UNSPECIFIED (0):
+ Default value. ACL search not enabled.
+ GSUITE (1):
+ Google 1P provider.
+ THIRD_PARTY (2):
+ Third party provider.
+ """
+
+ IDP_TYPE_UNSPECIFIED = 0
+ GSUITE = 1
+ THIRD_PARTY = 2
+
+ class ExternalIdpConfig(proto.Message):
+ r"""Third party IDP Config.
+
+ Attributes:
+ workforce_pool_name (str):
+ Workforce pool name. Example:
+ "locations/global/workforcePools/pool_id".
+ """
+
+ workforce_pool_name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+ idp_type: IdpType = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum=IdpType,
+ )
+ external_idp_config: ExternalIdpConfig = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=ExternalIdpConfig,
+ )
+
+
class Principal(proto.Message):
r"""Principal identifier of a user or a group.
@@ -365,6 +566,13 @@ class HealthcareFhirConfig(proto.Message):
If set to ``true``, the batch ingestion will be processed in
a static indexing mode which is slower but more capable of
handling larger volume.
+ initial_filter_groups (MutableSequence[str]):
+ Optional. Names of the Group resources to use as a basis for
+ the initial patient filter, in format
+ ``projects/{project_id}/locations/{location_id}/datasets/{dataset_id}/fhirStores/{fhir_store_id}/fhir/Group/{group_id}``.
+ The filter group must be a FHIR resource name of type Group,
+ and the filter will be constructed from the direct members
+ of the group which are Patient resources.
"""
enable_configurable_schema: bool = proto.Field(
@@ -375,6 +583,10 @@ class HealthcareFhirConfig(proto.Message):
proto.BOOL,
number=2,
)
+ initial_filter_groups: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=4,
+ )
class SearchLinkPromotion(proto.Message):
@@ -434,4 +646,97 @@ class SearchLinkPromotion(proto.Message):
)
+class SessionConfig(proto.Message):
+ r"""Configuration for the session.
+
+ Attributes:
+ session_management_policy (google.cloud.discoveryengine_v1.types.SessionConfig.SessionManagementPolicy):
+ Optional. Session management policy that
+ defines who will manage the session.
+ session_ttl (google.cloud.discoveryengine_v1.types.SessionConfig.SessionTtl):
+ Optional. The TTL for the session. If unset,
+ the default value is 60 days.
+ """
+
+ class SessionManagementPolicy(proto.Enum):
+ r"""Session management policy that defines who will manage the
+ session.
+
+ Values:
+ SESSION_MANAGEMENT_POLICY_UNSPECIFIED (0):
+ Default value.
+ NOT_MANAGED (1):
+ The session will be managed by the customer.
+ VERTEX_AI_MANAGED (2):
+ Sessions multi-tenancy will be controlled by
+ Google using 1P or 3P identity providers.
+ """
+
+ SESSION_MANAGEMENT_POLICY_UNSPECIFIED = 0
+ NOT_MANAGED = 1
+ VERTEX_AI_MANAGED = 2
+
+ class SessionTtl(proto.Message):
+ r"""Defines the TTL for sessions.
+
+ .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
+
+ Attributes:
+ days (int):
+ Defines the number of days for session TTL.
+
+ This field is a member of `oneof`_ ``time_info``.
+ """
+
+ days: int = proto.Field(
+ proto.INT32,
+ number=1,
+ oneof="time_info",
+ )
+
+ session_management_policy: SessionManagementPolicy = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum=SessionManagementPolicy,
+ )
+ session_ttl: SessionTtl = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=SessionTtl,
+ )
+
+
+class DataProtectionPolicy(proto.Message):
+ r"""Contains the data protection policy config for a DataStore or
+ a connector.
+
+ Attributes:
+ sensitive_data_protection_policy (google.cloud.discoveryengine_v1.types.DataProtectionPolicy.SensitiveDataProtectionPolicy):
+ Optional. Specifies the sensitive data
+ protection policy for the connector source.
+ """
+
+ class SensitiveDataProtectionPolicy(proto.Message):
+ r"""Specifies a Sensitive Data Protection
+ (https://cloud.google.com/sensitive-data-protection/docs/sensitive-data-protection-overview)
+ policy.
+
+ Attributes:
+ policy (str):
+ Optional. Specifies the resource name of the
+ Sensitive Data Protection content policy.
+ """
+
+ policy: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+ sensitive_data_protection_policy: SensitiveDataProtectionPolicy = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=SensitiveDataProtectionPolicy,
+ )
+
+
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/completion_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/completion_service.py
index 62c0fcfd2396..0e88cc6c358a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/completion_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/completion_service.py
@@ -17,13 +17,19 @@
from typing import MutableMapping, MutableSequence
+import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
import proto # type: ignore
+from google.cloud.discoveryengine_v1.types import common
+from google.cloud.discoveryengine_v1.types import document as gcd_document
+
__protobuf__ = proto.module(
package="google.cloud.discoveryengine.v1",
manifest={
"CompleteQueryRequest",
"CompleteQueryResponse",
+ "AdvancedCompleteQueryRequest",
+ "AdvancedCompleteQueryResponse",
},
)
@@ -65,11 +71,11 @@ class CompleteQueryRequest(proto.Message):
- ``search-history`` is the default model for site search
dataStores.
user_pseudo_id (str):
- A unique identifier for tracking visitors. For example, this
- could be implemented with an HTTP cookie, which should be
- able to uniquely identify a visitor on a single device. This
- unique identifier should not change if the visitor logs in
- or out of the website.
+ Optional. A unique identifier for tracking visitors. For
+ example, this could be implemented with an HTTP cookie,
+ which should be able to uniquely identify a visitor on a
+ single device. This unique identifier should not change if
+ the visitor logs in or out of the website.
This field should NOT have a fixed value such as
``unknown_visitor``.
@@ -166,4 +172,528 @@ class QuerySuggestion(proto.Message):
)
+class AdvancedCompleteQueryRequest(proto.Message):
+ r"""Request message for
+ [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery]
+ method. .
+
+ Attributes:
+ completion_config (str):
+ Required. The completion_config of the parent dataStore or
+ engine resource name for which the completion is performed,
+ such as
+ ``projects/*/locations/global/collections/default_collection/dataStores/*/completionConfig``
+ ``projects/*/locations/global/collections/default_collection/engines/*/completionConfig``.
+ query (str):
+ Required. The typeahead input used to fetch suggestions.
+ Maximum length is 128 characters.
+
+ The query can not be empty for most of the suggestion types.
+ If it is empty, an ``INVALID_ARGUMENT`` error is returned.
+ The exception is when the suggestion_types contains only the
+ type ``RECENT_SEARCH``, the query can be an empty string.
+ The is called "zero prefix" feature, which returns user's
+ recently searched queries given the empty query.
+ query_model (str):
+ Specifies the autocomplete query model, which only applies
+ to the QUERY SuggestionType. This overrides any model
+ specified in the Configuration > Autocomplete section of the
+ Cloud console. Currently supported values:
+
+ - ``document`` - Using suggestions generated from
+ user-imported documents.
+ - ``search-history`` - Using suggestions generated from the
+ past history of
+ [SearchService.Search][google.cloud.discoveryengine.v1.SearchService.Search]
+ API calls. Do not use it when there is no traffic for
+ Search API.
+ - ``user-event`` - Using suggestions generated from
+ user-imported search events.
+ - ``document-completable`` - Using suggestions taken
+ directly from user-imported document fields marked as
+ completable.
+
+ Default values:
+
+ - ``document`` is the default model for regular dataStores.
+ - ``search-history`` is the default model for site search
+ dataStores.
+ user_pseudo_id (str):
+ Optional. A unique identifier for tracking visitors. For
+ example, this could be implemented with an HTTP cookie,
+ which should be able to uniquely identify a visitor on a
+ single device. This unique identifier should not change if
+ the visitor logs in or out of the website.
+
+ This field should NOT have a fixed value such as
+ ``unknown_visitor``.
+
+ This should be the same identifier as
+ [UserEvent.user_pseudo_id][google.cloud.discoveryengine.v1.UserEvent.user_pseudo_id]
+ and
+ [SearchRequest.user_pseudo_id][google.cloud.discoveryengine.v1.SearchRequest.user_pseudo_id].
+
+ The field must be a UTF-8 encoded string with a length limit
+ of 128
+ user_info (google.cloud.discoveryengine_v1.types.UserInfo):
+ Optional. Information about the end user.
+
+ This should be the same identifier information as
+ [UserEvent.user_info][google.cloud.discoveryengine.v1.UserEvent.user_info]
+ and
+ [SearchRequest.user_info][google.cloud.discoveryengine.v1.SearchRequest.user_info].
+ include_tail_suggestions (bool):
+ Indicates if tail suggestions should be
+ returned if there are no suggestions that match
+ the full query. Even if set to true, if there
+ are suggestions that match the full query, those
+ are returned and no tail suggestions are
+ returned.
+ boost_spec (google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryRequest.BoostSpec):
+ Optional. Specification to boost suggestions
+ matching the condition.
+ suggestion_types (MutableSequence[google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryRequest.SuggestionType]):
+ Optional. Suggestion types to return. If
+ empty or unspecified, query suggestions are
+ returned. Only one suggestion type is supported
+ at the moment.
+ suggestion_type_specs (MutableSequence[google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryRequest.SuggestionTypeSpec]):
+ Optional. Specification of each suggestion
+ type.
+ experiment_ids (MutableSequence[str]):
+ Optional. Experiment ids for this request.
+ """
+
+ class SuggestionType(proto.Enum):
+ r"""Suggestion type to return.
+
+ Values:
+ SUGGESTION_TYPE_UNSPECIFIED (0):
+ Default value.
+ QUERY (1):
+ Returns query suggestions.
+ PEOPLE (2):
+ Returns people suggestions.
+ CONTENT (3):
+ Returns content suggestions.
+ RECENT_SEARCH (4):
+ Returns recent search suggestions.
+ GOOGLE_WORKSPACE (5):
+ Returns Google Workspace suggestions.
+ """
+
+ SUGGESTION_TYPE_UNSPECIFIED = 0
+ QUERY = 1
+ PEOPLE = 2
+ CONTENT = 3
+ RECENT_SEARCH = 4
+ GOOGLE_WORKSPACE = 5
+
+ class BoostSpec(proto.Message):
+ r"""Specification to boost suggestions based on the condition of
+ the suggestion.
+
+ Attributes:
+ condition_boost_specs (MutableSequence[google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryRequest.BoostSpec.ConditionBoostSpec]):
+ Condition boost specifications. If a
+ suggestion matches multiple conditions in the
+ specifications, boost values from these
+ specifications are all applied and combined in a
+ non-linear way. Maximum number of specifications
+ is 20.
+
+ Note: Currently only support language condition
+ boost.
+ """
+
+ class ConditionBoostSpec(proto.Message):
+ r"""Boost applies to suggestions which match a condition.
+
+ Attributes:
+ condition (str):
+ An expression which specifies a boost condition. The syntax
+ is the same as `filter expression
+ syntax `__.
+ Currently, the only supported condition is a list of BCP-47
+ lang codes.
+
+ Example:
+
+ - To boost suggestions in languages ``en`` or ``fr``:
+ ``(lang_code: ANY("en", "fr"))``
+ boost (float):
+ Strength of the boost, which should be in [-1, 1]. Negative
+ boost means demotion. Default is 0.0.
+
+ Setting to 1.0 gives the suggestions a big promotion.
+ However, it does not necessarily mean that the top result
+ will be a boosted suggestion.
+
+ Setting to -1.0 gives the suggestions a big demotion.
+ However, other suggestions that are relevant might still be
+ shown.
+
+ Setting to 0.0 means no boost applied. The boosting
+ condition is ignored.
+ """
+
+ condition: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ boost: float = proto.Field(
+ proto.FLOAT,
+ number=2,
+ )
+
+ condition_boost_specs: MutableSequence[
+ "AdvancedCompleteQueryRequest.BoostSpec.ConditionBoostSpec"
+ ] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message="AdvancedCompleteQueryRequest.BoostSpec.ConditionBoostSpec",
+ )
+
+ class SuggestionTypeSpec(proto.Message):
+ r"""Specification of each suggestion type.
+
+ Attributes:
+ suggestion_type (google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryRequest.SuggestionType):
+ Optional. Suggestion type.
+ max_suggestions (int):
+ Optional. Maximum number of suggestions to
+ return for each suggestion type.
+ """
+
+ suggestion_type: "AdvancedCompleteQueryRequest.SuggestionType" = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum="AdvancedCompleteQueryRequest.SuggestionType",
+ )
+ max_suggestions: int = proto.Field(
+ proto.INT32,
+ number=2,
+ )
+
+ completion_config: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ query: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ query_model: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ user_pseudo_id: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ user_info: common.UserInfo = proto.Field(
+ proto.MESSAGE,
+ number=9,
+ message=common.UserInfo,
+ )
+ include_tail_suggestions: bool = proto.Field(
+ proto.BOOL,
+ number=5,
+ )
+ boost_spec: BoostSpec = proto.Field(
+ proto.MESSAGE,
+ number=6,
+ message=BoostSpec,
+ )
+ suggestion_types: MutableSequence[SuggestionType] = proto.RepeatedField(
+ proto.ENUM,
+ number=7,
+ enum=SuggestionType,
+ )
+ suggestion_type_specs: MutableSequence[SuggestionTypeSpec] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=10,
+ message=SuggestionTypeSpec,
+ )
+ experiment_ids: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=14,
+ )
+
+
+class AdvancedCompleteQueryResponse(proto.Message):
+ r"""Response message for
+ [CompletionService.AdvancedCompleteQuery][google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery]
+ method.
+
+ Attributes:
+ query_suggestions (MutableSequence[google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryResponse.QuerySuggestion]):
+ Results of the matched query suggestions. The
+ result list is ordered and the first result is a
+ top suggestion.
+ tail_match_triggered (bool):
+ True if the returned suggestions are all tail suggestions.
+
+ For tail matching to be triggered, include_tail_suggestions
+ in the request must be true and there must be no suggestions
+ that match the full query.
+ people_suggestions (MutableSequence[google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryResponse.PersonSuggestion]):
+ Results of the matched people suggestions.
+ The result list is ordered and the first result
+ is the top suggestion.
+ content_suggestions (MutableSequence[google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryResponse.ContentSuggestion]):
+ Results of the matched content suggestions.
+ The result list is ordered and the first result
+ is the top suggestion.
+ recent_search_suggestions (MutableSequence[google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryResponse.RecentSearchSuggestion]):
+ Results of the matched "recent search"
+ suggestions. The result list is ordered and the
+ first result is the top suggestion.
+ """
+
+ class QuerySuggestion(proto.Message):
+ r"""Suggestions as search queries.
+
+ Attributes:
+ suggestion (str):
+ The suggestion for the query.
+ completable_field_paths (MutableSequence[str]):
+ The unique document field paths that serve as
+ the source of this suggestion if it was
+ generated from completable fields.
+
+ This field is only populated for the
+ document-completable model.
+ data_store (MutableSequence[str]):
+ The name of the dataStore that this
+ suggestion belongs to.
+ score (float):
+ The score of each suggestion. The score is in the range of
+ [0, 1].
+ """
+
+ suggestion: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ completable_field_paths: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=2,
+ )
+ data_store: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=3,
+ )
+ score: float = proto.Field(
+ proto.DOUBLE,
+ number=4,
+ )
+
+ class PersonSuggestion(proto.Message):
+ r"""Suggestions as people.
+
+ Attributes:
+ suggestion (str):
+ The suggestion for the query.
+ person_type (google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryResponse.PersonSuggestion.PersonType):
+ The type of the person.
+ document (google.cloud.discoveryengine_v1.types.Document):
+ The document data snippet in the suggestion.
+ Only a subset of fields is populated.
+ data_store (str):
+ The name of the dataStore that this
+ suggestion belongs to.
+ score (float):
+ The score of each suggestion. The score is in the range of
+ [0, 1].
+ display_photo_uri (str):
+ The photo uri of the person suggestion.
+ destination_uri (str):
+ The destination uri of the person suggestion.
+ """
+
+ class PersonType(proto.Enum):
+ r"""Classifies the person by identity source and entity kind;
+ GOOGLE_GROUP takes precedence for groups regardless of their
+ identity source.
+
+ Values:
+ PERSON_TYPE_UNSPECIFIED (0):
+ Default value.
+ CLOUD_IDENTITY (1):
+ The suggestion is from a GOOGLE_IDENTITY source.
+ THIRD_PARTY_IDENTITY (2):
+ The suggestion is from a THIRD_PARTY_IDENTITY source.
+ GOOGLE_GROUP (3):
+ The suggestion is a group (e.g. a Google
+ Group), not an individual.
+ """
+
+ PERSON_TYPE_UNSPECIFIED = 0
+ CLOUD_IDENTITY = 1
+ THIRD_PARTY_IDENTITY = 2
+ GOOGLE_GROUP = 3
+
+ suggestion: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ person_type: "AdvancedCompleteQueryResponse.PersonSuggestion.PersonType" = (
+ proto.Field(
+ proto.ENUM,
+ number=2,
+ enum="AdvancedCompleteQueryResponse.PersonSuggestion.PersonType",
+ )
+ )
+ document: gcd_document.Document = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=gcd_document.Document,
+ )
+ data_store: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+ score: float = proto.Field(
+ proto.DOUBLE,
+ number=6,
+ )
+ display_photo_uri: str = proto.Field(
+ proto.STRING,
+ number=7,
+ )
+ destination_uri: str = proto.Field(
+ proto.STRING,
+ number=8,
+ )
+
+ class ContentSuggestion(proto.Message):
+ r"""Suggestions as content.
+
+ Attributes:
+ suggestion (str):
+ The suggestion for the query.
+ content_type (google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryResponse.ContentSuggestion.ContentType):
+ The type of the content suggestion.
+ document (google.cloud.discoveryengine_v1.types.Document):
+ The document data snippet in the suggestion.
+ Only a subset of fields will be populated.
+ data_store (str):
+ The name of the dataStore that this
+ suggestion belongs to.
+ score (float):
+ The score of each suggestion. The score is in the range of
+ [0, 1].
+ icon_uri (str):
+ The icon uri of the content suggestion.
+ destination_uri (str):
+ The destination uri of the content
+ suggestion.
+ """
+
+ class ContentType(proto.Enum):
+ r"""The type of the content returned for content suggestions.
+
+ Values:
+ CONTENT_TYPE_UNSPECIFIED (0):
+ Default value.
+ GOOGLE_WORKSPACE (1):
+ The suggestion is from a Google Workspace
+ source.
+ THIRD_PARTY (2):
+ The suggestion is from a third party source.
+ """
+
+ CONTENT_TYPE_UNSPECIFIED = 0
+ GOOGLE_WORKSPACE = 1
+ THIRD_PARTY = 2
+
+ suggestion: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ content_type: "AdvancedCompleteQueryResponse.ContentSuggestion.ContentType" = (
+ proto.Field(
+ proto.ENUM,
+ number=2,
+ enum="AdvancedCompleteQueryResponse.ContentSuggestion.ContentType",
+ )
+ )
+ document: gcd_document.Document = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=gcd_document.Document,
+ )
+ data_store: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+ score: float = proto.Field(
+ proto.DOUBLE,
+ number=6,
+ )
+ icon_uri: str = proto.Field(
+ proto.STRING,
+ number=7,
+ )
+ destination_uri: str = proto.Field(
+ proto.STRING,
+ number=8,
+ )
+
+ class RecentSearchSuggestion(proto.Message):
+ r"""Suggestions from recent search history.
+
+ Attributes:
+ suggestion (str):
+ The suggestion for the query.
+ recent_search_time (google.protobuf.timestamp_pb2.Timestamp):
+ The time when this recent rearch happened.
+ score (float):
+ The score of each suggestion. The score is in the range of
+ [0, 1].
+ """
+
+ suggestion: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ recent_search_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=timestamp_pb2.Timestamp,
+ )
+ score: float = proto.Field(
+ proto.DOUBLE,
+ number=3,
+ )
+
+ query_suggestions: MutableSequence[QuerySuggestion] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message=QuerySuggestion,
+ )
+ tail_match_triggered: bool = proto.Field(
+ proto.BOOL,
+ number=2,
+ )
+ people_suggestions: MutableSequence[PersonSuggestion] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=3,
+ message=PersonSuggestion,
+ )
+ content_suggestions: MutableSequence[ContentSuggestion] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=4,
+ message=ContentSuggestion,
+ )
+ recent_search_suggestions: MutableSequence[RecentSearchSuggestion] = (
+ proto.RepeatedField(
+ proto.MESSAGE,
+ number=5,
+ message=RecentSearchSuggestion,
+ )
+ )
+
+
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/conversational_search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/conversational_search_service.py
index 72fb3c79f2b0..4aa47940556a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/conversational_search_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/conversational_search_service.py
@@ -379,6 +379,13 @@ class AnswerQueryRequest(proto.Message):
``projects/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_serving_config``,
or
``projects/*/locations/global/collections/default_collection/dataStores/*/servingConfigs/default_serving_config``.
+
+ Or the resource name of the agent engine serving config,
+ such as:
+ ``projects/*/locations/global/collections/default_collection/engines/*/servingConfigs/default_agent_answer``.
+ (use when ``enable_agent_invocation`` set to true, and you
+ have custom ``AI_MODE`` agent engine configured)
+
This field is used to identify the serving configuration
name, set of models used to make the search.
query (google.cloud.discoveryengine_v1.types.Query):
@@ -1392,6 +1399,13 @@ class CreateSessionRequest(proto.Message):
``projects/{project}/locations/{location}/collections/{collection}/dataStores/{data_store_id}``
session (google.cloud.discoveryengine_v1.types.Session):
Required. The session to create.
+ session_id (str):
+ Optional. The ID to use for the session, which will become
+ the final component of the session's resource name.
+
+ This value should be 1-63 characters, and valid characters
+ are /[a-z0-9][a-z0-9-]{0,61}[a-z0-9]/. If not specified, a
+ unique ID will be generated.
"""
parent: str = proto.Field(
@@ -1403,6 +1417,10 @@ class CreateSessionRequest(proto.Message):
number=2,
message=gcd_session.Session,
)
+ session_id: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
class UpdateSessionRequest(proto.Message):
@@ -1487,7 +1505,9 @@ class ListSessionsRequest(proto.Message):
call. Provide this to retrieve the subsequent page.
filter (str):
A comma-separated list of fields to filter by, in EBNF
- grammar. The supported fields are:
+ grammar.
+
+ The supported fields are:
- ``user_pseudo_id``
- ``state``
@@ -1497,25 +1517,34 @@ class ListSessionsRequest(proto.Message):
- ``labels``
- ``create_time``
- ``update_time``
+ - ``collaborative_project``
+
+ Examples:
- Examples: "user_pseudo_id = some_id" "display_name =
- "some_name"" "starred = true" "is_pinned=true AND (NOT
- labels:hidden)" "create_time > "1970-01-01T12:00:00Z"".
+ - ``user_pseudo_id = some_id``
+ - ``display_name = "some_name"``
+ - ``starred = true``
+ - ``is_pinned=true AND (NOT labels:hidden)``
+ - ``create_time > "1970-01-01T12:00:00Z"``
+ - ``collaborative_project = "projects/123/locations/global/collections/default_collection/engines/" "default_engine/collaborative_projects/cp1"``
order_by (str):
A comma-separated list of fields to order by, sorted in
ascending order. Use "desc" after a field name for
- descending. Supported fields:
+ descending.
+
+ Supported fields:
- ``update_time``
- ``create_time``
- ``session_name``
- ``is_pinned``
+ - ``display_name``
Example:
- - "update_time desc"
- - "create_time"
- - "is_pinned desc,update_time desc": list sessions by
+ - ``update_time desc``
+ - ``create_time``
+ - ``is_pinned desc,update_time desc``: list sessions by
is_pinned first, then by update_time.
"""
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_connector.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_connector.py
new file mode 100644
index 000000000000..9068a0a0867f
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_connector.py
@@ -0,0 +1,1469 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 google.type.datetime_pb2 as datetime_pb2 # type: ignore
+import proto # type: ignore
+
+from google.cloud.discoveryengine_v1.types import common, schema
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "ConnectorType",
+ "DataConnector",
+ "DestinationConfig",
+ "ActionConfig",
+ "IdentityScheduleConfig",
+ "BAPConfig",
+ "CliConfig",
+ "AlertPolicyConfig",
+ "Tenant",
+ "DynamicTool",
+ },
+)
+
+
+class ConnectorType(proto.Enum):
+ r"""The type of connector.
+ New values may be added to this enum in the future.
+
+ Values:
+ CONNECTOR_TYPE_UNSPECIFIED (0):
+ Default value.
+ THIRD_PARTY (1):
+ Third party connector to connector to third
+ party application.
+ GCP_FHIR (2):
+ Data connector connects between FHIR store
+ and VAIS datastore.
+ BIG_QUERY (3):
+ Big query connector.
+ GCS (4):
+ Google Cloud Storage connector.
+ GOOGLE_MAIL (5):
+ Gmail connector.
+ GOOGLE_CALENDAR (6):
+ Google Calendar connector.
+ GOOGLE_DRIVE (7):
+ Google Drive connector.
+ NATIVE_CLOUD_IDENTITY (8):
+ Native Cloud Identity connector for people
+ search powered by People API.
+ THIRD_PARTY_FEDERATED (9):
+ Federated connector, it is a third party
+ connector that doesn't ingestion data, and
+ search is powered by third party application's
+ API.
+ THIRD_PARTY_EUA (10):
+ Connector utilized for End User
+ Authentication features.
+ GCNV (11):
+ Google Cloud NetApp Volumes connector.
+ GOOGLE_CHAT (12):
+ Google Chat connector.
+ GOOGLE_SITES (13):
+ Google Sites connector.
+ REMOTE_MCP (14):
+ Remote MCP based connector.
+ GOOGLE_WORKSPACE (15):
+ Google Workspace connector.
+ """
+
+ CONNECTOR_TYPE_UNSPECIFIED = 0
+ THIRD_PARTY = 1
+ GCP_FHIR = 2
+ BIG_QUERY = 3
+ GCS = 4
+ GOOGLE_MAIL = 5
+ GOOGLE_CALENDAR = 6
+ GOOGLE_DRIVE = 7
+ NATIVE_CLOUD_IDENTITY = 8
+ THIRD_PARTY_FEDERATED = 9
+ THIRD_PARTY_EUA = 10
+ GCNV = 11
+ GOOGLE_CHAT = 12
+ GOOGLE_SITES = 13
+ REMOTE_MCP = 14
+ GOOGLE_WORKSPACE = 15
+
+
+class DataConnector(proto.Message):
+ r"""Manages the connection to external data sources for all data stores
+ grouped under a
+ [Collection][google.cloud.discoveryengine.v1.Collection]. It's a
+ singleton resource of
+ [Collection][google.cloud.discoveryengine.v1.Collection]. The
+ initialization is only supported through
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, which will create a new
+ [Collection][google.cloud.discoveryengine.v1.Collection] and
+ initialize its
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector].
+
+ 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:
+ params (google.protobuf.struct_pb2.Struct):
+ Required data connector parameters in
+ structured json format.
+
+ This field is a member of `oneof`_ ``data_connector_params``.
+ json_params (str):
+ Required data connector parameters in json
+ string format.
+
+ This field is a member of `oneof`_ ``data_connector_params``.
+ name (str):
+ Identifier. The full resource name of the Data Connector.
+ Format:
+ ``projects/*/locations/*/collections/*/dataConnector``.
+ state (google.cloud.discoveryengine_v1.types.DataConnector.State):
+ Output only. State of the connector.
+ data_source (str):
+ Required. The identifier for the data source. For the full,
+ up-to-date list of supported connectors and their values,
+ see `Connect a third-party data
+ source `__.
+ remove_param_keys (MutableSequence[str]):
+ Optional. Specifies keys to be removed from the 'params'
+ field. This is only active when 'params' is included in the
+ 'update_mask' in an UpdateDataConnectorRequest. Deletion
+ takes precedence if a key is both in 'remove_param_keys' and
+ present in the 'params' field of the request.
+ refresh_interval (google.protobuf.duration_pb2.Duration):
+ Required. The refresh interval for data sync.
+ If duration is set to 0, the data will be synced
+ in real time. The streaming feature is not
+ supported yet. The minimum is 30 minutes and
+ maximum is 7 days. When the refresh interval is
+ set to the same value as the incremental refresh
+ interval, incremental sync will be disabled.
+ next_sync_time (google.type.datetime_pb2.DateTime):
+ Defines the scheduled time for the next data
+ synchronization. This field requires hour , minute, and
+ time_zone from the `IANA Time Zone
+ Database `__. This is
+ utilized when the data connector has a refresh interval
+ greater than 1 day. When the hours or minutes are not
+ specified, we will assume a sync time of 0:00. The user must
+ provide a time zone to avoid ambiguity.
+ entities (MutableSequence[google.cloud.discoveryengine_v1.types.DataConnector.SourceEntity]):
+ List of entities from the connected data
+ source to ingest.
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. Timestamp the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ was created at.
+ latest_pause_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. The most recent timestamp when this
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ was paused, affecting all functionalities such as data
+ synchronization. Pausing a connector has the following
+ effects:
+
+ - All functionalities, including data synchronization, are
+ halted.
+ - Any ongoing data synchronization job will be canceled.
+ - No future data synchronization runs will be scheduled nor
+ can be triggered.
+ last_sync_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. For periodic connectors only,
+ the last time a data sync was completed.
+ update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. Timestamp the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ was last updated.
+ errors (MutableSequence[google.rpc.status_pb2.Status]):
+ Output only. The errors from initialization
+ or from the latest connector run.
+ sync_mode (google.cloud.discoveryengine_v1.types.DataConnector.SyncMode):
+ The data synchronization mode supported by
+ the data connector.
+ kms_key_name (str):
+ Input only. The KMS key to be used to protect
+ the DataStores managed by this connector.
+
+ Must be set for requests that need to comply
+ with CMEK Org Policy protections.
+
+ If this field is set and processed successfully,
+ the DataStores created by this connector will be
+ protected by the KMS key.
+ destination_configs (MutableSequence[google.cloud.discoveryengine_v1.types.DestinationConfig]):
+ Optional. Any target destinations used to
+ connect to third-party services.
+ action_state (google.cloud.discoveryengine_v1.types.DataConnector.State):
+ Output only. State of the action connector.
+ This reflects whether the action connector is
+ initializing, active or has encountered errors.
+ action_config (google.cloud.discoveryengine_v1.types.ActionConfig):
+ Optional. Action configurations to make the
+ connector support actions.
+ end_user_config (google.cloud.discoveryengine_v1.types.DataConnector.EndUserConfig):
+ Optional. Any params and credentials used
+ specifically for EUA connectors.
+ federated_config (google.cloud.discoveryengine_v1.types.DataConnector.FederatedConfig):
+ Optional. Any params and credentials used
+ specifically for hybrid connectors supporting
+ FEDERATED mode. This field should only be set if
+ the connector is a hybrid connector and we want
+ to enable FEDERATED mode.
+ connector_modes (MutableSequence[google.cloud.discoveryengine_v1.types.DataConnector.ConnectorMode]):
+ Optional. The modes enabled for this connector. Default
+ state is CONNECTOR_MODE_UNSPECIFIED.
+ static_ip_enabled (bool):
+ Optional. Whether customer has enabled static
+ IP addresses for this connector.
+ static_ip_addresses (MutableSequence[str]):
+ Output only. The static IP addresses used by
+ this connector.
+ oauth_static_ip_addresses (MutableSequence[str]):
+ Output only. The static IP addresses used by this connector
+ for OAuth APIs (e.g. end user authentication). These are
+ surfaced separately from ``static_ip_addresses`` so that
+ customers can apply granular firewall settings for OAuth
+ endpoints. Only populated for connectors that have static IP
+ enabled and are used for actions and/or federated search.
+ blocking_reasons (MutableSequence[google.cloud.discoveryengine_v1.types.DataConnector.BlockingReason]):
+ Output only. User actions that must be
+ completed before the connector can start syncing
+ data.
+ identity_schedule_config (google.cloud.discoveryengine_v1.types.IdentityScheduleConfig):
+ The configuration for the identity data
+ synchronization runs. This contains the refresh
+ interval to sync the Access Control List
+ information for the documents ingested by this
+ connector.
+ private_connectivity_project_id (str):
+ Output only. The tenant project ID associated
+ with private connectivity connectors. This
+ project must be allowlisted by in order for the
+ connector to function.
+ bap_config (google.cloud.discoveryengine_v1.types.BAPConfig):
+ Optional. The configuration for establishing
+ a BAP connection.
+ connector_type (google.cloud.discoveryengine_v1.types.ConnectorType):
+ Output only. The type of connector. Each source can only map
+ to one type. For example, salesforce, confluence and jira
+ have THIRD_PARTY connector type. It is not mutable once set
+ by system.
+ realtime_state (google.cloud.discoveryengine_v1.types.DataConnector.State):
+ Output only. real-time sync state
+ alert_policy_configs (MutableSequence[google.cloud.discoveryengine_v1.types.AlertPolicyConfig]):
+ Optional. The connector level alert config.
+ realtime_sync_config (google.cloud.discoveryengine_v1.types.DataConnector.RealtimeSyncConfig):
+ Optional. The configuration for realtime
+ sync.
+ acl_enabled (bool):
+ Optional. Whether the connector will be
+ created with an ACL config. Currently this field
+ only affects Cloud Storage and BigQuery
+ connectors.
+ create_eua_saas (bool):
+ Optional. Whether the END USER AUTHENTICATION
+ connector is created in SaaS.
+ auto_run_disabled (bool):
+ Optional. Indicates whether the connector is disabled for
+ auto run. It can be used to pause periodical and real time
+ sync. Update: with the introduction of
+ incremental_sync_disabled, auto_run_disabled is used to
+ pause/disable only full syncs
+ incremental_sync_disabled (bool):
+ Optional. Indicates whether incremental syncs are paused for
+ this connector. This is independent of auto_run_disabled.
+ Applicable to only 3P connectors. When the refresh interval
+ is set to the same value as the incremental refresh
+ interval, incremental sync will be disabled, i.e. set to
+ true.
+ incremental_refresh_interval (google.protobuf.duration_pb2.Duration):
+ Optional. The refresh interval specifically
+ for incremental data syncs. If unset,
+ incremental syncs will use the default from env,
+ set to 3hrs. The minimum is 30 minutes and
+ maximum is 7 days. Applicable to only 3P
+ connectors. When the refresh interval is
+ set to the same value as the incremental refresh
+ interval, incremental sync will be disabled.
+ hybrid_ingestion_disabled (bool):
+ Optional. If the connector is a hybrid
+ connector, determines whether ingestion is
+ enabled and appropriate resources are
+ provisioned during connector creation. If the
+ connector is not a hybrid connector, this field
+ is ignored.
+ data_protection_policy (google.cloud.discoveryengine_v1.types.DataProtectionPolicy):
+ Optional. Specifies the data protection
+ policy for the connector.
+ egress_fqdns (MutableSequence[str]):
+ Output only. The list of FQDNs of the data
+ connector can egress to. This includes both FQDN
+ derived from the customer provided instance URL
+ and default per connector type FQDNs.
+ vpcsc_enabled (bool):
+ Output only. Whether the connector is created
+ with VPC-SC enabled.
+ dynamic_tools (MutableSequence[google.cloud.discoveryengine_v1.types.DynamicTool]):
+ Output only. The dynamic tools fetched for
+ this connector.
+ cli_config (google.cloud.discoveryengine_v1.types.CliConfig):
+ Optional. The configuration for establishing
+ a CLI connection.
+ connector_source_id (str):
+ Optional. If set, this value instead of ``data_source`` is
+ used to fetch the corresponding connector source.
+ tag (str):
+ Optional. Immutable. User-facing, version-independent label
+ for this connector. May be shared by multiple connectors
+ under the same (project, location, collection, data_source);
+ tag-based lookup returns the one with the greatest
+ create_time.
+
+ Optional at Create time. If the caller omits ``tag``, the
+ server auto-derives one from the collection_id (falling back
+ to data_source, else a time-based ``t-`` sentinel).
+ The auto-derived tag is subject to the same immutability
+ guarantee as a caller-supplied one, so callers who care
+ about the exact tag value should provide it explicitly
+ rather than relying on the server default.
+
+ Agent Designer resolves connectors via (data_source, tag)
+ when set, falling back to the legacy resource-name lookup
+ when unset, so connectors created before the tag-write
+ launch continue to work without a backfill.
+ metadata (google.cloud.discoveryengine_v1.types.DataConnector.ConnectorMetadata):
+ Optional. User-facing metadata for the connector. Populated
+ from the connector's generated metadata / registry
+ ``ConnectorSource``.
+ """
+
+ class State(proto.Enum):
+ r"""The state of connector.
+
+ Values:
+ STATE_UNSPECIFIED (0):
+ Default value.
+ CREATING (1):
+ The connector is being set up.
+ ACTIVE (2):
+ The connector is successfully set up and
+ awaiting next sync run.
+ FAILED (3):
+ The connector is in error. The error details can be found in
+ [DataConnector.errors][google.cloud.discoveryengine.v1.DataConnector.errors].
+ If the error is unfixable, the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ can be deleted by
+ [CollectionService.DeleteCollection][google.cloud.discoveryengine.v1.CollectionService.DeleteCollection]
+ API.
+ RUNNING (4):
+ The connector is actively syncing records
+ from the data source.
+ WARNING (5):
+ The connector has completed a sync run, but
+ encountered non-fatal errors.
+ INITIALIZATION_FAILED (6):
+ Connector initialization failed. Potential
+ causes include runtime errors or issues in the
+ asynchronous pipeline, preventing the request
+ from reaching downstream services (except for
+ some connector types).
+ UPDATING (7):
+ Connector is in the process of an update.
+ """
+
+ STATE_UNSPECIFIED = 0
+ CREATING = 1
+ ACTIVE = 2
+ FAILED = 3
+ RUNNING = 4
+ WARNING = 5
+ INITIALIZATION_FAILED = 6
+ UPDATING = 7
+
+ class SyncMode(proto.Enum):
+ r"""Defines the data synchronization mode supported by the data
+ connector.
+
+ Values:
+ PERIODIC (0):
+ The connector will sync data periodically based on the
+ refresh_interval. Use it with auto_run_disabled to pause the
+ periodic sync, or indicate a one-time sync.
+ STREAMING (1):
+ The data will be synced in real time.
+ UNSPECIFIED (2):
+ Connector that doesn't ingest data will have
+ this value
+ """
+
+ PERIODIC = 0
+ STREAMING = 1
+ UNSPECIFIED = 2
+
+ class ConnectorMode(proto.Enum):
+ r"""The modes enabled for this connector. INGESTION, ACTIONS,
+ FEDERATED, OR EUA
+
+ Values:
+ CONNECTOR_MODE_UNSPECIFIED (0):
+ Connector mode unspecified.
+ DATA_INGESTION (1):
+ Connector utilized for data ingestion.
+ ACTIONS (2):
+ Connector utilized for actions.
+ FEDERATED (3):
+ Connector utilized for federated search.
+ EUA (4):
+ Connector utilized for End User
+ Authentication.
+ FEDERATED_AND_EUA (5):
+ Hybrid connector utilized for federated
+ search and End User Authentication.
+ """
+
+ CONNECTOR_MODE_UNSPECIFIED = 0
+ DATA_INGESTION = 1
+ ACTIONS = 2
+ FEDERATED = 3
+ EUA = 4
+ FEDERATED_AND_EUA = 5
+
+ class BlockingReason(proto.Enum):
+ r"""User actions that must be completed before the connector can
+ start syncing data.
+
+ Values:
+ BLOCKING_REASON_UNSPECIFIED (0):
+ Default value.
+ ALLOWLIST_STATIC_IP (1):
+ Connector requires customer to allowlist
+ static IPs.
+ ALLOWLIST_IN_SERVICE_ATTACHMENT (2):
+ Connector requires customer to allowlist our
+ project in their service attachment.
+ ALLOWLIST_SERVICE_ACCOUNT (3):
+ Connector requires customer to allowlist
+ service account in their project.
+ """
+
+ BLOCKING_REASON_UNSPECIFIED = 0
+ ALLOWLIST_STATIC_IP = 1
+ ALLOWLIST_IN_SERVICE_ATTACHMENT = 2
+ ALLOWLIST_SERVICE_ACCOUNT = 3
+
+ class SourceEntity(proto.Message):
+ r"""Represents an entity in the data source. For example, the
+ ``Account`` object in Salesforce.
+
+ 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:
+ params (google.protobuf.struct_pb2.Struct):
+ The parameters for the entity to facilitate
+ data ingestion in structured json format.
+
+ This field is a member of `oneof`_ ``entity_params``.
+ json_params (str):
+ The parameters for the entity to facilitate
+ data ingestion in json string format.
+
+ This field is a member of `oneof`_ ``entity_params``.
+ entity_name (str):
+ The name of the entity. Supported values by data source:
+
+ - Salesforce: ``Lead``, ``Opportunity``, ``Contact``,
+ ``Account``, ``Case``, ``Contract``, ``Campaign``
+ - Jira: ``Issue``
+ - Confluence: ``Content``, ``Space``
+ key_property_mappings (MutableMapping[str, str]):
+ Attributes for indexing. Key: Field name. Value: The key
+ property to map a field to, such as ``title``, and
+ ``description``. Supported key properties:
+
+ - ``title``: The title for data record. This would be
+ displayed on search results.
+ - ``description``: The description for data record. This
+ would be displayed on search results.
+ data_store (str):
+ Output only. The full resource name of the associated data
+ store for the source entity. Format:
+ ``projects/*/locations/*/collections/*/dataStores/*``. When
+ the connector is initialized by the
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method, a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore] is
+ automatically created for each source entity.
+ starting_schema (google.cloud.discoveryengine_v1.types.Schema):
+ Optional. The start schema to use for the
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]
+ created from this SourceEntity. If unset, a default vertical
+ specialized schema will be used.
+
+ This field is only used by
+ [SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ API, and will be ignored if used in other APIs. This field
+ will be omitted from all API responses including
+ [GetDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.GetDataConnector]
+ API. To retrieve a schema of a
+ [DataStore][google.cloud.discoveryengine.v1.DataStore], use
+ [SchemaService.GetSchema][google.cloud.discoveryengine.v1.SchemaService.GetSchema]
+ API instead.
+
+ The provided schema will be validated against certain rules
+ on schema. Learn more from `this
+ doc `__.
+ healthcare_fhir_config (google.cloud.discoveryengine_v1.types.HealthcareFhirConfig):
+ Optional. Configuration for ``HEALTHCARE_FHIR`` vertical.
+ """
+
+ params: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ oneof="entity_params",
+ message=struct_pb2.Struct,
+ )
+ json_params: str = proto.Field(
+ proto.STRING,
+ number=10,
+ oneof="entity_params",
+ )
+ entity_name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ key_property_mappings: MutableMapping[str, str] = proto.MapField(
+ proto.STRING,
+ proto.STRING,
+ number=2,
+ )
+ data_store: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ starting_schema: schema.Schema = proto.Field(
+ proto.MESSAGE,
+ number=6,
+ message=schema.Schema,
+ )
+ healthcare_fhir_config: common.HealthcareFhirConfig = proto.Field(
+ proto.MESSAGE,
+ number=7,
+ message=common.HealthcareFhirConfig,
+ )
+
+ class EndUserConfig(proto.Message):
+ r"""Any params and credentials used specifically for EUA
+ connectors.
+
+ 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:
+ auth_params (google.protobuf.struct_pb2.Struct):
+ Optional. Any authentication parameters
+ specific to EUA connectors.
+
+ This field is a member of `oneof`_ ``auth_config``.
+ json_auth_params (str):
+ Optional. Any authentication parameters
+ specific to EUA connectors in json string
+ format.
+
+ This field is a member of `oneof`_ ``auth_config``.
+ additional_params (google.protobuf.struct_pb2.Struct):
+ Optional. Any additional parameters needed
+ for EUA.
+ tenant (google.cloud.discoveryengine_v1.types.Tenant):
+ Optional. The tenant project the connector is
+ connected to.
+ """
+
+ auth_params: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ oneof="auth_config",
+ message=struct_pb2.Struct,
+ )
+ json_auth_params: str = proto.Field(
+ proto.STRING,
+ number=4,
+ oneof="auth_config",
+ )
+ additional_params: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=struct_pb2.Struct,
+ )
+ tenant: "Tenant" = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message="Tenant",
+ )
+
+ class FederatedConfig(proto.Message):
+ r"""Any params and credentials used specifically for hybrid
+ connectors supporting FEDERATED mode.
+
+ 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:
+ auth_params (google.protobuf.struct_pb2.Struct):
+ Optional. Any authentication parameters
+ specific to FEDERATED connectors.
+
+ This field is a member of `oneof`_ ``auth_config``.
+ json_auth_params (str):
+ Optional. Any authentication parameters
+ specific to FEDERATED connectors in json string
+ format.
+
+ This field is a member of `oneof`_ ``auth_config``.
+ additional_params (google.protobuf.struct_pb2.Struct):
+ Optional. Any additional parameters needed
+ for FEDERATED.
+ """
+
+ auth_params: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ oneof="auth_config",
+ message=struct_pb2.Struct,
+ )
+ json_auth_params: str = proto.Field(
+ proto.STRING,
+ number=3,
+ oneof="auth_config",
+ )
+ additional_params: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=struct_pb2.Struct,
+ )
+
+ class RealtimeSyncConfig(proto.Message):
+ r"""The configuration for realtime sync to store additional
+ params for realtime sync.
+
+ Attributes:
+ webhook_uri (str):
+ Optional. Webhook url for the connector to
+ specify additional params for realtime sync.
+ realtime_sync_secret (str):
+ Optional. The ID of the Secret Manager secret
+ used for webhook secret.
+ streaming_error (google.cloud.discoveryengine_v1.types.DataConnector.RealtimeSyncConfig.StreamingError):
+ Optional. Streaming error details.
+ """
+
+ class StreamingError(proto.Message):
+ r"""Streaming error details.
+
+ Attributes:
+ streaming_error_reason (google.cloud.discoveryengine_v1.types.DataConnector.RealtimeSyncConfig.StreamingError.StreamingErrorReason):
+ Optional. Streaming error.
+ error (google.rpc.status_pb2.Status):
+ Optional. Error details.
+ """
+
+ class StreamingErrorReason(proto.Enum):
+ r"""Broad types of streaming errors.
+
+ Values:
+ STREAMING_ERROR_REASON_UNSPECIFIED (0):
+ Streaming error reason unspecified.
+ STREAMING_SETUP_ERROR (1):
+ Some error occurred while setting up
+ resources for realtime sync.
+ STREAMING_SYNC_ERROR (2):
+ Some error was encountered while running
+ realtime sync for the connector.
+ INGRESS_ENDPOINT_REQUIRED (3):
+ Ingress endpoint is required when setting up
+ realtime sync in private connectivity.
+ """
+
+ STREAMING_ERROR_REASON_UNSPECIFIED = 0
+ STREAMING_SETUP_ERROR = 1
+ STREAMING_SYNC_ERROR = 2
+ INGRESS_ENDPOINT_REQUIRED = 3
+
+ streaming_error_reason: "DataConnector.RealtimeSyncConfig.StreamingError.StreamingErrorReason" = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum="DataConnector.RealtimeSyncConfig.StreamingError.StreamingErrorReason",
+ )
+ error: status_pb2.Status = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=status_pb2.Status,
+ )
+
+ webhook_uri: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ realtime_sync_secret: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ streaming_error: "DataConnector.RealtimeSyncConfig.StreamingError" = (
+ proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message="DataConnector.RealtimeSyncConfig.StreamingError",
+ )
+ )
+
+ class ConnectorMetadata(proto.Message):
+ r"""User-facing metadata for the connector, shown on the connector
+ detail page (title, description, short_description, author, note).
+
+ Attributes:
+ title (str):
+ Optional. Display title of the connector.
+ description (str):
+ Optional. Human-readable description of the
+ connector, shown on the connector detail page.
+ One connector has a single description.
+ short_description (str):
+ Optional. Short, subtitle-length description
+ of the connector (e.g. shown beneath the
+ connector name in list and detail views).
+ author (str):
+ Optional. The party that authored the
+ connector, e.g. "Google" or a third-party
+ provider name. Lets end users see who authored a
+ connector.
+ note (str):
+ Optional. Free-form, multi-line note about
+ the connector's capabilities or a custom note
+ that can be set for the connector.
+ """
+
+ title: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ description: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ short_description: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ author: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ note: str = proto.Field(
+ proto.STRING,
+ number=6,
+ )
+
+ params: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ oneof="data_connector_params",
+ message=struct_pb2.Struct,
+ )
+ json_params: str = proto.Field(
+ proto.STRING,
+ number=43,
+ oneof="data_connector_params",
+ )
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ state: State = proto.Field(
+ proto.ENUM,
+ number=2,
+ enum=State,
+ )
+ data_source: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ remove_param_keys: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=38,
+ )
+ refresh_interval: duration_pb2.Duration = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ message=duration_pb2.Duration,
+ )
+ next_sync_time: datetime_pb2.DateTime = proto.Field(
+ proto.MESSAGE,
+ number=22,
+ message=datetime_pb2.DateTime,
+ )
+ entities: MutableSequence[SourceEntity] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=6,
+ message=SourceEntity,
+ )
+ create_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=7,
+ message=timestamp_pb2.Timestamp,
+ )
+ latest_pause_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=18,
+ message=timestamp_pb2.Timestamp,
+ )
+ last_sync_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=19,
+ message=timestamp_pb2.Timestamp,
+ )
+ update_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=20,
+ message=timestamp_pb2.Timestamp,
+ )
+ errors: MutableSequence[status_pb2.Status] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=8,
+ message=status_pb2.Status,
+ )
+ sync_mode: SyncMode = proto.Field(
+ proto.ENUM,
+ number=9,
+ enum=SyncMode,
+ )
+ kms_key_name: str = proto.Field(
+ proto.STRING,
+ number=32,
+ )
+ destination_configs: MutableSequence["DestinationConfig"] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=12,
+ message="DestinationConfig",
+ )
+ action_state: State = proto.Field(
+ proto.ENUM,
+ number=37,
+ enum=State,
+ )
+ action_config: "ActionConfig" = proto.Field(
+ proto.MESSAGE,
+ number=13,
+ message="ActionConfig",
+ )
+ end_user_config: EndUserConfig = proto.Field(
+ proto.MESSAGE,
+ number=30,
+ message=EndUserConfig,
+ )
+ federated_config: FederatedConfig = proto.Field(
+ proto.MESSAGE,
+ number=41,
+ message=FederatedConfig,
+ )
+ connector_modes: MutableSequence[ConnectorMode] = proto.RepeatedField(
+ proto.ENUM,
+ number=31,
+ enum=ConnectorMode,
+ )
+ static_ip_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=15,
+ )
+ static_ip_addresses: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=14,
+ )
+ oauth_static_ip_addresses: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=50,
+ )
+ blocking_reasons: MutableSequence[BlockingReason] = proto.RepeatedField(
+ proto.ENUM,
+ number=16,
+ enum=BlockingReason,
+ )
+ identity_schedule_config: "IdentityScheduleConfig" = proto.Field(
+ proto.MESSAGE,
+ number=23,
+ message="IdentityScheduleConfig",
+ )
+ private_connectivity_project_id: str = proto.Field(
+ proto.STRING,
+ number=17,
+ )
+ bap_config: "BAPConfig" = proto.Field(
+ proto.MESSAGE,
+ number=24,
+ message="BAPConfig",
+ )
+ connector_type: "ConnectorType" = proto.Field(
+ proto.ENUM,
+ number=25,
+ enum="ConnectorType",
+ )
+ realtime_state: State = proto.Field(
+ proto.ENUM,
+ number=26,
+ enum=State,
+ )
+ alert_policy_configs: MutableSequence["AlertPolicyConfig"] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=28,
+ message="AlertPolicyConfig",
+ )
+ realtime_sync_config: RealtimeSyncConfig = proto.Field(
+ proto.MESSAGE,
+ number=29,
+ message=RealtimeSyncConfig,
+ )
+ acl_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=33,
+ )
+ create_eua_saas: bool = proto.Field(
+ proto.BOOL,
+ number=34,
+ )
+ auto_run_disabled: bool = proto.Field(
+ proto.BOOL,
+ number=10,
+ )
+ incremental_sync_disabled: bool = proto.Field(
+ proto.BOOL,
+ number=35,
+ )
+ incremental_refresh_interval: duration_pb2.Duration = proto.Field(
+ proto.MESSAGE,
+ number=36,
+ message=duration_pb2.Duration,
+ )
+ hybrid_ingestion_disabled: bool = proto.Field(
+ proto.BOOL,
+ number=40,
+ )
+ data_protection_policy: common.DataProtectionPolicy = proto.Field(
+ proto.MESSAGE,
+ number=44,
+ message=common.DataProtectionPolicy,
+ )
+ egress_fqdns: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=45,
+ )
+ vpcsc_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=46,
+ )
+ dynamic_tools: MutableSequence["DynamicTool"] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=47,
+ message="DynamicTool",
+ )
+ cli_config: "CliConfig" = proto.Field(
+ proto.MESSAGE,
+ number=48,
+ message="CliConfig",
+ )
+ connector_source_id: str = proto.Field(
+ proto.STRING,
+ number=49,
+ )
+ tag: str = proto.Field(
+ proto.STRING,
+ number=51,
+ )
+ metadata: ConnectorMetadata = proto.Field(
+ proto.MESSAGE,
+ number=52,
+ message=ConnectorMetadata,
+ )
+
+
+class DestinationConfig(proto.Message):
+ r"""Defines target endpoints used to connect to third-party
+ sources.
+
+ 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:
+ params (google.protobuf.struct_pb2.Struct):
+ Optional. Additional parameters for this
+ destination config in structured json format.
+
+ This field is a member of `oneof`_ ``destination_config_params``.
+ json_params (str):
+ Additional parameters for this destination
+ config in json string format.
+
+ This field is a member of `oneof`_ ``destination_config_params``.
+ key (str):
+ Optional. Unique destination identifier that
+ is supported by the connector.
+ destinations (MutableSequence[google.cloud.discoveryengine_v1.types.DestinationConfig.Destination]):
+ Optional. The destinations for the
+ corresponding key.
+ """
+
+ class Destination(proto.Message):
+ r"""Defines a target endpoint
+
+ .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
+
+ Attributes:
+ host (str):
+ Publicly routable host.
+
+ This field is a member of `oneof`_ ``destination``.
+ port (int):
+ Optional. Target port number accepted by the
+ destination.
+ """
+
+ host: str = proto.Field(
+ proto.STRING,
+ number=1,
+ oneof="destination",
+ )
+ port: int = proto.Field(
+ proto.INT32,
+ number=2,
+ )
+
+ params: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ oneof="destination_config_params",
+ message=struct_pb2.Struct,
+ )
+ json_params: str = proto.Field(
+ proto.STRING,
+ number=4,
+ oneof="destination_config_params",
+ )
+ key: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ destinations: MutableSequence[Destination] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=2,
+ message=Destination,
+ )
+
+
+class ActionConfig(proto.Message):
+ r"""Informations to support actions on the connector.
+
+ 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:
+ action_params (google.protobuf.struct_pb2.Struct):
+ Optional. Action parameters in structured
+ json format.
+
+ This field is a member of `oneof`_ ``action_config_params``.
+ json_action_params (str):
+ Optional. Action parameters in json string
+ format.
+
+ This field is a member of `oneof`_ ``action_config_params``.
+ is_action_configured (bool):
+ Output only. The connector contains the
+ necessary parameters and is configured to
+ support actions.
+ service_name (str):
+ Optional. The Service Directory resource name
+ (projects/*/locations/*/namespaces/*/services/*)
+ representing a VPC network endpoint used to connect to the
+ data source's ``instance_uri``, defined in
+ [DataConnector.params][google.cloud.discoveryengine.v1.DataConnector.params].
+
+ Required when VPC Service Controls are enabled.
+ use_static_secrets (bool):
+ Optional. Whether to use static secrets for the connector.
+ If true, the secrets provided in the action_params will be
+ ignored.
+ create_bap_connection (bool):
+ Optional. Whether to create a BAP connection
+ for the connector.
+ user_defined_scopes_mapping (MutableMapping[str, google.cloud.discoveryengine_v1.types.ActionConfig.ScopeList]):
+ Optional. Mapping from operation name to the
+ list of scopes. Only be populated if there are
+ user specified scopes.
+ """
+
+ class ScopeList(proto.Message):
+ r"""Stores a list of scopes.
+
+ Attributes:
+ scopes (MutableSequence[str]):
+ Optional. The list of scopes.
+ """
+
+ scopes: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=1,
+ )
+
+ action_params: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ oneof="action_config_params",
+ message=struct_pb2.Struct,
+ )
+ json_action_params: str = proto.Field(
+ proto.STRING,
+ number=6,
+ oneof="action_config_params",
+ )
+ is_action_configured: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+ service_name: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ use_static_secrets: bool = proto.Field(
+ proto.BOOL,
+ number=4,
+ )
+ create_bap_connection: bool = proto.Field(
+ proto.BOOL,
+ number=5,
+ )
+ user_defined_scopes_mapping: MutableMapping[str, ScopeList] = proto.MapField(
+ proto.STRING,
+ proto.MESSAGE,
+ number=10,
+ message=ScopeList,
+ )
+
+
+class IdentityScheduleConfig(proto.Message):
+ r"""The configuration for the identity data synchronization runs.
+
+ Attributes:
+ refresh_interval (google.protobuf.duration_pb2.Duration):
+ Optional. The refresh interval to sync the
+ Access Control List information for the
+ documents ingested by this connector. If not
+ set, the access control list will be refreshed
+ at the default interval of 30 minutes. The
+ identity refresh interval can be at least 30
+ minutes and at most 7 days.
+ next_sync_time (google.type.datetime_pb2.DateTime):
+ Optional. The UTC time when the next data
+ sync is expected to start for the Data
+ Connector. Customers are only able to specify
+ the hour and minute to schedule the data sync.
+ This is utilized when the data connector has a
+ refresh interval greater than 1 day.
+ """
+
+ refresh_interval: duration_pb2.Duration = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=duration_pb2.Duration,
+ )
+ next_sync_time: datetime_pb2.DateTime = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=datetime_pb2.DateTime,
+ )
+
+
+class BAPConfig(proto.Message):
+ r"""The configuration for the BAP connector.
+
+ Attributes:
+ supported_connector_modes (MutableSequence[google.cloud.discoveryengine_v1.types.BAPConfig.ConnectorMode]):
+ Required. The supported connector modes for
+ the associated BAP connection.
+ enabled_actions (MutableSequence[str]):
+ Optional. The actions enabled on the
+ associated BAP connection.
+ toolspec_override (google.cloud.discoveryengine_v1.types.BAPConfig.ToolspecOverride):
+ Optional. Custom toolspec overrides for this connection. For
+ Enterprise BAP connectors that support admin-curated tool
+ definitions, this holds the (simplified) per-tool overrides.
+ On Get, populated by the server by merging persisted
+ overrides with live runtime tool definitions and trimming
+ the result for UI consumption. On Update, the supplied value
+ replaces the persisted overrides after server-side
+ validation and merging: the ``base_version`` field MUST
+ match the server's current base toolspec version (otherwise
+ the request is rejected with a user-facing error directing
+ the admin to re-download the latest tools first).
+ """
+
+ class ConnectorMode(proto.Enum):
+ r"""Use cases supported by this BAP connector.
+
+ Values:
+ CONNECTOR_MODE_UNSPECIFIED (0):
+ Connector mode unspecified.
+ DATA_INGESTION (1):
+ Connector utilized for data ingestion.
+ ACTIONS (2):
+ Connector utilized for Actions
+ END_USER_AUTHENTICATION (3):
+ Connector utilized for End User
+ Authentication.
+ """
+
+ CONNECTOR_MODE_UNSPECIFIED = 0
+ DATA_INGESTION = 1
+ ACTIONS = 2
+ END_USER_AUTHENTICATION = 3
+
+ class ToolspecOverride(proto.Message):
+ r"""Customer-facing view of the admin-curated toolspec for a BAP
+ connection. Holds the (simplified) per-tool definitions surfaced to
+ and editable by the admin in the Discovery Engine UI.
+
+ Mirrors the shape of the backend
+ ``google.cloud.connectorexecution.v1.ToolspecOverride`` message, but
+ is intentionally kept as a separate public type so the Discovery
+ Engine API surface can evolve independently of the fed-API surface
+ (AIP-215). Handlers convert between the two via helpers in
+ //cloud/ml/discoveryengine/external_service/v1main/data_connector_service/lib:bap_custom_tool_util.
+
+ Attributes:
+ tools (MutableSequence[google.protobuf.struct_pb2.Struct]):
+ Required. Tool definitions (one Struct per
+ tool) that the admin has customised on top of
+ the base toolspec returned by the fed API.
+ REQUIRED because it is the only user-editable
+ field in the modify API; the request must carry
+ at least one tool.
+ base_version (str):
+ Required. Base toolspec version against which ``tools`` were
+ authored. On Update, MUST match the server's current stable
+ toolspec version for the connection; mismatch is rejected
+ with a user-facing error directing the admin to re-download
+ the latest tools first.
+ """
+
+ tools: MutableSequence[struct_pb2.Struct] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message=struct_pb2.Struct,
+ )
+ base_version: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+ supported_connector_modes: MutableSequence[ConnectorMode] = proto.RepeatedField(
+ proto.ENUM,
+ number=1,
+ enum=ConnectorMode,
+ )
+ enabled_actions: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=2,
+ )
+ toolspec_override: ToolspecOverride = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message=ToolspecOverride,
+ )
+
+
+class CliConfig(proto.Message):
+ r"""The configuration for the CLI execution based connectors.
+
+ Attributes:
+ enabled_actions (MutableSequence[str]):
+ Optional. The actions enabled on the
+ associated CLI connection.
+ """
+
+ enabled_actions: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=1,
+ )
+
+
+class AlertPolicyConfig(proto.Message):
+ r"""The connector level alert config.
+
+ Attributes:
+ alert_policy_name (str):
+ Immutable. The fully qualified resource name
+ of the AlertPolicy.
+ alert_enrollments (MutableSequence[google.cloud.discoveryengine_v1.types.AlertPolicyConfig.AlertEnrollment]):
+ Optional. The enrollment states of each
+ alert.
+ """
+
+ class AlertEnrollment(proto.Message):
+ r"""The alert enrollment status.
+
+ Attributes:
+ alert_id (str):
+ Immutable. The id of an alert.
+ enroll_state (google.cloud.discoveryengine_v1.types.AlertPolicyConfig.AlertEnrollment.EnrollStates):
+ Required. The enrollment status of a
+ customer.
+ """
+
+ class EnrollStates(proto.Enum):
+ r"""The enrollment status enum for the alert.
+
+ Values:
+ ENROLL_STATES_UNSPECIFIED (0):
+ Default value. Used for customers who have
+ not responded to the alert policy.
+ ENROLLED (1):
+ Customer is enrolled in this policy.
+ DECLINED (2):
+ Customer declined this policy.
+ """
+
+ ENROLL_STATES_UNSPECIFIED = 0
+ ENROLLED = 1
+ DECLINED = 2
+
+ alert_id: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ enroll_state: "AlertPolicyConfig.AlertEnrollment.EnrollStates" = proto.Field(
+ proto.ENUM,
+ number=5,
+ enum="AlertPolicyConfig.AlertEnrollment.EnrollStates",
+ )
+
+ alert_policy_name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ alert_enrollments: MutableSequence[AlertEnrollment] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=2,
+ message=AlertEnrollment,
+ )
+
+
+class Tenant(proto.Message):
+ r"""Tenant information for a connector source. This includes some
+ of the same information stored in the Credential message, but is
+ limited to only what is needed to provide a list of accessible
+ tenants to the user.
+
+ Attributes:
+ id (str):
+ The tenant's instance ID. Examples: Jira
+ ("8594f221-9797-5f78-1fa4-485e198d7cd0"), Slack
+ ("T123456").
+ uri (str):
+ The URI of the tenant, if applicable. For
+ example, the URI of a Jira instance is
+ https://my-jira-instance.atlassian.net, and a
+ Slack tenant does not have a URI.
+ display_name (str):
+ Optional display name for the tenant, e.g.
+ "My Slack Team".
+ """
+
+ id: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ uri: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+
+class DynamicTool(proto.Message):
+ r"""Configuration for dynamic tools.
+
+ Attributes:
+ name (str):
+ Required. The name of the tool.
+ description (str):
+ Optional. The description of the tool.
+ enabled (bool):
+ Optional. Whether the tool is enabled.
+ display_name (str):
+ Optional. The display name of the tool.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ description: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ enabled: bool = proto.Field(
+ proto.BOOL,
+ number=3,
+ )
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_connector_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_connector_service.py
new file mode 100644
index 000000000000..4d9ed023439a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_connector_service.py
@@ -0,0 +1,196 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 proto # type: ignore
+
+from google.cloud.discoveryengine_v1.types import data_connector as gcd_data_connector
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "SetUpDataConnectorRequest",
+ "SetUpDataConnectorMetadata",
+ "GetDataConnectorRequest",
+ "UpdateDataConnectorRequest",
+ },
+)
+
+
+class SetUpDataConnectorRequest(proto.Message):
+ r"""Request for
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method.
+
+ Attributes:
+ parent (str):
+ Required. The parent of
+ [Collection][google.cloud.discoveryengine.v1.Collection], in
+ the format of ``projects/{project}/locations/{location}``.
+ collection_id (str):
+ Required. The ID to use for the
+ [Collection][google.cloud.discoveryengine.v1.Collection],
+ which will become the final component of the
+ [Collection][google.cloud.discoveryengine.v1.Collection]'s
+ resource name. A new
+ [Collection][google.cloud.discoveryengine.v1.Collection] is
+ created as part of the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ setup.
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ is a singleton resource under
+ [Collection][google.cloud.discoveryengine.v1.Collection],
+ managing all
+ [DataStore][google.cloud.discoveryengine.v1.DataStore]s of
+ the
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Should conform to
+ `RFC-1034 `__ standard
+ with a length limit of 63 characters. Otherwise, an
+ ``INVALID_ARGUMENT`` error is returned.
+ collection_display_name (str):
+ Required. The display name of the
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+
+ Should be human readable, used to display collections in the
+ Console Dashboard. UTF-8 encoded string with limit of 1024
+ characters.
+ data_connector (google.cloud.discoveryengine_v1.types.DataConnector):
+ Required. The
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ to initialize in the newly created
+ [Collection][google.cloud.discoveryengine.v1.Collection].
+ """
+
+ parent: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ collection_id: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ collection_display_name: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ data_connector: gcd_data_connector.DataConnector = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=gcd_data_connector.DataConnector,
+ )
+
+
+class SetUpDataConnectorMetadata(proto.Message):
+ r"""Metadata for
+ [DataConnectorService.SetUpDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector]
+ method.
+
+ """
+
+
+class GetDataConnectorRequest(proto.Message):
+ r"""Request for
+ [DataConnectorService.GetDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.GetDataConnector]
+ method.
+
+ Attributes:
+ name (str):
+ Required. Full resource name of
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector],
+ such as
+ ``projects/{project}/locations/{location}/collections/{collection_id}/dataConnector``.
+
+ If the caller does not have permission to access the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector],
+ regardless of whether or not it exists, a
+ ``PERMISSION_DENIED`` error is returned.
+
+ If the requested
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ does not exist, a ``NOT_FOUND`` error is returned.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class UpdateDataConnectorRequest(proto.Message):
+ r"""Request message for
+ [DataConnectorService.UpdateDataConnector][google.cloud.discoveryengine.v1.DataConnectorService.UpdateDataConnector]
+ method.
+
+ Attributes:
+ data_connector (google.cloud.discoveryengine_v1.types.DataConnector):
+ Required. The
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ to update.
+
+ If the caller does not have permission to update the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector],
+ regardless of whether or not it exists, a
+ ``PERMISSION_DENIED`` error is returned.
+
+ If the
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ does not exist, a ``NOT_FOUND`` error is returned.
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
+ Indicates which fields in the provided
+ [DataConnector][google.cloud.discoveryengine.v1.DataConnector]
+ to update.
+
+ Supported field paths include:
+
+ - ``refresh_interval``
+ - ``params``
+ - ``auto_run_disabled``
+ - ``action_config``
+ - ``action_config.action_params``
+ - ``action_config.service_name``
+ - ``destination_configs``
+ - ``blocking_reasons``
+ - ``sync_mode``
+ - ``incremental_sync_disabled``
+ - ``incremental_refresh_interval``
+ - ``data_protection_policy``
+
+ Note: Support for these fields may vary depending on the
+ connector type. For example, not all connectors support
+ ``destination_configs``.
+
+ If an unsupported or unknown field path is provided, the
+ request will return an ``INVALID_ARGUMENT`` error.
+ """
+
+ data_connector: gcd_data_connector.DataConnector = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_data_connector.DataConnector,
+ )
+ update_mask: field_mask_pb2.FieldMask = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=field_mask_pb2.FieldMask,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_store.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_store.py
index 07204e9bca28..0ba2a7c1b096 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_store.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/data_store.py
@@ -148,6 +148,9 @@ class DataStore(proto.Message):
doc `__.
healthcare_fhir_config (google.cloud.discoveryengine_v1.types.HealthcareFhirConfig):
Optional. Configuration for ``HEALTHCARE_FHIR`` vertical.
+ serving_config_data_store (google.cloud.discoveryengine_v1.types.DataStore.ServingConfigDataStore):
+ Optional. Stores serving config at DataStore
+ level.
identity_mapping_store (str):
Immutable. The fully qualified resource name of the
associated
@@ -155,6 +158,21 @@ class DataStore(proto.Message):
This field can only be set for acl_enabled DataStores with
``THIRD_PARTY`` or ``GSUITE`` IdP. Format:
``projects/{project}/locations/{location}/identityMappingStores/{identity_mapping_store}``.
+ is_infobot_faq_data_store (bool):
+ Optional. If set, this DataStore is an
+ Infobot FAQ DataStore.
+ federated_search_config (google.cloud.discoveryengine_v1.types.DataStore.FederatedSearchConfig):
+ Optional. If set, this DataStore is a
+ federated search DataStore.
+ configurable_billing_approach (google.cloud.discoveryengine_v1.types.DataStore.ConfigurableBillingApproach):
+ Optional. Configuration for configurable
+ billing approach. See
+ configurable_billing_approach_update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. The timestamp when
+ configurable_billing_approach was last updated.
+ data_protection_policy (google.cloud.discoveryengine_v1.types.DataProtectionPolicy):
+ Optional. Specifies the data protection
+ policy for the data store.
"""
class ContentConfig(proto.Enum):
@@ -184,6 +202,25 @@ class ContentConfig(proto.Enum):
PUBLIC_WEBSITE = 3
GOOGLE_WORKSPACE = 4
+ class ConfigurableBillingApproach(proto.Enum):
+ r"""Configuration for configurable billing approach.
+
+ Values:
+ CONFIGURABLE_BILLING_APPROACH_UNSPECIFIED (0):
+ Default value. For Spark and non-Spark
+ non-configurable billing approach.
+ CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE (1):
+ Use the subscription base + overage billing
+ for indexing core for non embedding storage.
+ CONFIGURABLE_CONSUMPTION_EMBEDDING (2):
+ Use the consumption pay-as-you-go billing for
+ embedding storage add-on.
+ """
+
+ CONFIGURABLE_BILLING_APPROACH_UNSPECIFIED = 0
+ CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE = 1
+ CONFIGURABLE_CONSUMPTION_EMBEDDING = 2
+
class BillingEstimation(proto.Message):
r"""Estimation of data size per data store.
@@ -232,6 +269,238 @@ class BillingEstimation(proto.Message):
message=timestamp_pb2.Timestamp,
)
+ class ServingConfigDataStore(proto.Message):
+ r"""Stores information regarding the serving configurations at
+ DataStore level.
+
+ Attributes:
+ disabled_for_serving (bool):
+ Optional. If set true, the DataStore will not
+ be available for serving search requests.
+ """
+
+ disabled_for_serving: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+
+ class FederatedSearchConfig(proto.Message):
+ r"""Stores information for federated search.
+
+ This message has `oneof`_ fields (mutually exclusive fields).
+ For each oneof, at most one member field can be set at the same time.
+ Setting any member of the oneof automatically clears all other
+ members.
+
+ .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
+
+ Attributes:
+ alloy_db_config (google.cloud.discoveryengine_v1.types.DataStore.FederatedSearchConfig.AlloyDbConfig):
+ AlloyDB config. If set, this DataStore is
+ connected to AlloyDB.
+
+ This field is a member of `oneof`_ ``data_source_config``.
+ third_party_oauth_config (google.cloud.discoveryengine_v1.types.DataStore.FederatedSearchConfig.ThirdPartyOauthConfig):
+ Third Party OAuth config. If set, this
+ DataStore is connected to a third party
+ application.
+
+ This field is a member of `oneof`_ ``data_source_config``.
+ notebooklm_config (google.cloud.discoveryengine_v1.types.DataStore.FederatedSearchConfig.NotebooklmConfig):
+ NotebookLM config. If set, this DataStore is
+ connected to NotebookLM Enterprise.
+
+ This field is a member of `oneof`_ ``data_source_config``.
+ """
+
+ class AlloyDbConfig(proto.Message):
+ r"""Stores information for connecting to AlloyDB.
+
+ Attributes:
+ alloydb_connection_config (google.cloud.discoveryengine_v1.types.DataStore.FederatedSearchConfig.AlloyDbConfig.AlloyDbConnectionConfig):
+ Required. Configuration for connecting to
+ AlloyDB.
+ alloydb_ai_nl_config (google.cloud.discoveryengine_v1.types.DataStore.FederatedSearchConfig.AlloyDbConfig.AlloyDbAiNaturalLanguageConfig):
+ Optional. Configuration for Magic.
+ returned_fields (MutableSequence[str]):
+ Optional. Fields to be returned in the search
+ results. If empty, all fields will be returned.
+ """
+
+ class AlloyDbConnectionConfig(proto.Message):
+ r"""Configuration for connecting to AlloyDB.
+
+ Attributes:
+ instance (str):
+ Required. The AlloyDB instance to connect to.
+ database (str):
+ Required. The AlloyDB database to connect to.
+ user (str):
+ Required. Database user.
+
+ If auth_mode = END_USER_ACCOUNT, it can be unset. In that
+ case, the user will be inferred on the AlloyDB side, based
+ on the authenticated user.
+ password (str):
+ Required. Database password.
+
+ If auth_mode = END_USER_ACCOUNT, it can be unset. In that
+ case, the password will be inferred on the AlloyDB side,
+ based on the authenticated user.
+ auth_mode (google.cloud.discoveryengine_v1.types.DataStore.FederatedSearchConfig.AlloyDbConfig.AlloyDbConnectionConfig.AuthMode):
+ Optional. Auth mode.
+ enable_psvs (bool):
+ Optional. If true, enable PSVS for AlloyDB.
+ """
+
+ class AuthMode(proto.Enum):
+ r"""Auth mode.
+
+ Values:
+ AUTH_MODE_UNSPECIFIED (0):
+ No description available.
+ AUTH_MODE_SERVICE_ACCOUNT (1):
+ Uses P4SA when VAIS talks to AlloyDB.
+ AUTH_MODE_END_USER_ACCOUNT (2):
+ Uses EUC when VAIS talks to AlloyDB.
+ """
+
+ AUTH_MODE_UNSPECIFIED = 0
+ AUTH_MODE_SERVICE_ACCOUNT = 1
+ AUTH_MODE_END_USER_ACCOUNT = 2
+
+ instance: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ database: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ user: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ password: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ auth_mode: "DataStore.FederatedSearchConfig.AlloyDbConfig.AlloyDbConnectionConfig.AuthMode" = proto.Field(
+ proto.ENUM,
+ number=5,
+ enum="DataStore.FederatedSearchConfig.AlloyDbConfig.AlloyDbConnectionConfig.AuthMode",
+ )
+ enable_psvs: bool = proto.Field(
+ proto.BOOL,
+ number=6,
+ )
+
+ class AlloyDbAiNaturalLanguageConfig(proto.Message):
+ r"""Configuration for AlloyDB AI Natural Language.
+
+ Attributes:
+ nl_config_id (str):
+ Optional. AlloyDb AI NL config id, i.e. the value that was
+ used for calling
+ ``SELECT alloydb_ai_nl.g_create_configuration(...)``. Can be
+ empty.
+ """
+
+ nl_config_id: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+ alloydb_connection_config: "DataStore.FederatedSearchConfig.AlloyDbConfig.AlloyDbConnectionConfig" = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message="DataStore.FederatedSearchConfig.AlloyDbConfig.AlloyDbConnectionConfig",
+ )
+ alloydb_ai_nl_config: "DataStore.FederatedSearchConfig.AlloyDbConfig.AlloyDbAiNaturalLanguageConfig" = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message="DataStore.FederatedSearchConfig.AlloyDbConfig.AlloyDbAiNaturalLanguageConfig",
+ )
+ returned_fields: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=3,
+ )
+
+ class ThirdPartyOauthConfig(proto.Message):
+ r"""Stores information for third party applicationOAuth.
+
+ Attributes:
+ app_name (str):
+ Optional. The type of the application. E.g.,
+ "jira", "box", etc.
+ instance_name (str):
+ Optional. The instance name identifying the 3P app, e.g.,
+ "-my". This is different from the instance_uri which is the
+ full URL of the 3P app e.g., "https://-my.sharepoint.com".
+ """
+
+ app_name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ instance_name: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+ class NotebooklmConfig(proto.Message):
+ r"""Config for connecting to NotebookLM Enterprise.
+
+ Attributes:
+ search_config (str):
+ Required. Search config name.
+
+ Format:
+ projects/*/locations/global/notebookLmSearchConfigs/*
+ notebooks (MutableSequence[str]):
+ Optional. Restricts this data store to the given notebooks.
+ When empty, the data store covers every notebook the
+ querying user can access, which is the existing behaviour.
+
+ Each entry is a full notebook resource name, such as
+ ``projects/*/locations/*/notebooks/*``.
+
+ Scoping is enforced on results as well as requested
+ upstream, so a notebook outside this list cannot appear in a
+ search response through this data store even if the backend
+ returns one.
+ """
+
+ search_config: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ notebooks: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=2,
+ )
+
+ alloy_db_config: "DataStore.FederatedSearchConfig.AlloyDbConfig" = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ oneof="data_source_config",
+ message="DataStore.FederatedSearchConfig.AlloyDbConfig",
+ )
+ third_party_oauth_config: "DataStore.FederatedSearchConfig.ThirdPartyOauthConfig" = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ oneof="data_source_config",
+ message="DataStore.FederatedSearchConfig.ThirdPartyOauthConfig",
+ )
+ notebooklm_config: "DataStore.FederatedSearchConfig.NotebooklmConfig" = (
+ proto.Field(
+ proto.MESSAGE,
+ number=3,
+ oneof="data_source_config",
+ message="DataStore.FederatedSearchConfig.NotebooklmConfig",
+ )
+ )
+
name: str = proto.Field(
proto.STRING,
number=1,
@@ -312,10 +581,39 @@ class BillingEstimation(proto.Message):
number=29,
message=common.HealthcareFhirConfig,
)
+ serving_config_data_store: ServingConfigDataStore = proto.Field(
+ proto.MESSAGE,
+ number=30,
+ message=ServingConfigDataStore,
+ )
identity_mapping_store: str = proto.Field(
proto.STRING,
number=31,
)
+ is_infobot_faq_data_store: bool = proto.Field(
+ proto.BOOL,
+ number=37,
+ )
+ federated_search_config: FederatedSearchConfig = proto.Field(
+ proto.MESSAGE,
+ number=38,
+ message=FederatedSearchConfig,
+ )
+ configurable_billing_approach: ConfigurableBillingApproach = proto.Field(
+ proto.ENUM,
+ number=45,
+ enum=ConfigurableBillingApproach,
+ )
+ configurable_billing_approach_update_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=46,
+ message=timestamp_pb2.Timestamp,
+ )
+ data_protection_policy: common.DataProtectionPolicy = proto.Field(
+ proto.MESSAGE,
+ number=48,
+ message=common.DataProtectionPolicy,
+ )
class AdvancedSiteSearchConfig(proto.Message):
@@ -396,7 +694,11 @@ class WorkspaceConfig(proto.Message):
type_ (google.cloud.discoveryengine_v1.types.WorkspaceConfig.Type):
The Google Workspace data source.
dasher_customer_id (str):
- Obfuscated Dasher customer ID.
+ Output only. Obfuscated Dasher customer ID.
+ Derived by the server from the project's GCP
+ organization at data store creation time; any
+ value supplied in the request payload is
+ ignored.
super_admin_service_account (str):
Optional. The super admin service account for
the workspace that will be used for access token
@@ -432,6 +734,9 @@ class Type(proto.Enum):
Workspace Data Store contains Keep data
GOOGLE_PEOPLE (8):
Workspace Data Store contains People data
+ GOOGLE_WORKSPACE (9):
+ Workspace Data Store contains all Workspace
+ apps data
"""
TYPE_UNSPECIFIED = 0
@@ -443,6 +748,7 @@ class Type(proto.Enum):
GOOGLE_GROUPS = 6
GOOGLE_KEEP = 7
GOOGLE_PEOPLE = 8
+ GOOGLE_WORKSPACE = 9
type_: Type = proto.Field(
proto.ENUM,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/document.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/document.py
index 15246316bd47..ff72ce86cd1e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/document.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/document.py
@@ -90,12 +90,16 @@ class Document(proto.Message):
acl_info (google.cloud.discoveryengine_v1.types.Document.AclInfo):
Access control information for the document.
index_time (google.protobuf.timestamp_pb2.Timestamp):
- Output only. The last time the document was indexed. If this
- field is set, the document could be returned in search
- results.
-
- This field is OUTPUT_ONLY. If this field is not populated,
- it means the document has never been indexed.
+ Output only. The time when the document was
+ last indexed.
+ If this field is populated, it means the
+ document has been indexed. While documents
+ typically become searchable within seconds of
+ indexing, it can sometimes take up to a few
+ hours.
+
+ If this field is not populated, it means the
+ document has never been indexed.
index_status (google.cloud.discoveryengine_v1.types.Document.IndexStatus):
Output only. The index status of the document.
@@ -241,7 +245,10 @@ class IndexStatus(proto.Message):
index_time (google.protobuf.timestamp_pb2.Timestamp):
The time when the document was indexed.
If this field is populated, it means the
- document has been indexed.
+ document has been indexed. While documents
+ typically become searchable within seconds of
+ indexing, it can sometimes take up to a few
+ hours.
error_samples (MutableSequence[google.rpc.status_pb2.Status]):
A sample of errors encountered while indexing
the document. If this field is populated, the
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/document_processing_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/document_processing_config.py
index 6d4857cb918f..ea95bd0b5ce2 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/document_processing_config.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/document_processing_config.py
@@ -175,6 +175,9 @@ class LayoutParsingConfig(proto.Message):
enable_image_annotation (bool):
Optional. If true, the LLM based annotation
is added to the image during parsing.
+ enable_llm_layout_parsing (bool):
+ Optional. If true, the pdf layout will be
+ refined using an LLM.
structured_content_types (MutableSequence[str]):
Optional. Contains the required structure types to extract
from the document. Supported values:
@@ -189,6 +192,10 @@ class LayoutParsingConfig(proto.Message):
exclude_html_ids (MutableSequence[str]):
Optional. List of HTML ids to exclude from
the parsed content.
+ enable_get_processed_document (bool):
+ Optional. If true, the processed document
+ will be made available for the
+ GetProcessedDocument API.
"""
enable_table_annotation: bool = proto.Field(
@@ -199,6 +206,10 @@ class LayoutParsingConfig(proto.Message):
proto.BOOL,
number=2,
)
+ enable_llm_layout_parsing: bool = proto.Field(
+ proto.BOOL,
+ number=5,
+ )
structured_content_types: MutableSequence[str] = proto.RepeatedField(
proto.STRING,
number=9,
@@ -215,6 +226,10 @@ class LayoutParsingConfig(proto.Message):
proto.STRING,
number=12,
)
+ enable_get_processed_document: bool = proto.Field(
+ proto.BOOL,
+ number=14,
+ )
digital_parsing_config: "DocumentProcessingConfig.ParsingConfig.DigitalParsingConfig" = proto.Field(
proto.MESSAGE,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/engine.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/engine.py
index 57693329ad8a..903e30594db7 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/engine.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/engine.py
@@ -20,7 +20,10 @@
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
import proto # type: ignore
-from google.cloud.discoveryengine_v1.types import common
+from google.cloud.discoveryengine_v1.types import (
+ agent_gateway_setting as gcd_agent_gateway_setting,
+)
+from google.cloud.discoveryengine_v1.types import cmek_config_service, common, logging
__protobuf__ = proto.module(
package="google.cloud.discoveryengine.v1",
@@ -131,11 +134,201 @@ class Engine(proto.Message):
common_config (google.cloud.discoveryengine_v1.types.Engine.CommonConfig):
Common config spec that specifies the
metadata of the engine.
+ knowledge_graph_config (google.cloud.discoveryengine_v1.types.Engine.KnowledgeGraphConfig):
+ Optional. Configurations for the Knowledge Graph. Only
+ applicable if
+ [solution_type][google.cloud.discoveryengine.v1.Engine.solution_type]
+ is
+ [SOLUTION_TYPE_SEARCH][google.cloud.discoveryengine.v1.SolutionType.SOLUTION_TYPE_SEARCH].
+ app_type (google.cloud.discoveryengine_v1.types.Engine.AppType):
+ Optional. Immutable. This the application
+ type which this engine resource represents.
+ NOTE: this is a new concept independ of existing
+ industry vertical or solution type.
disable_analytics (bool):
Optional. Whether to disable analytics for
searches performed on this engine.
+ session_config (google.cloud.discoveryengine_v1.types.SessionConfig):
+ Optional. Non-empty default. Session config
+ for the engine.
+ features (MutableMapping[str, google.cloud.discoveryengine_v1.types.Engine.FeatureState]):
+ Optional. Feature config for the engine to opt in or opt out
+ of features. Supported keys:
+
+ - ``*``: all features, if it's present, all other feature
+ state settings are ignored.
+ - ``agent-gallery``
+ - ``no-code-agent-builder``
+ - ``prompt-gallery``
+ - ``model-selector``
+ - ``notebook-lm``
+ - ``people-search``
+ - ``people-search-org-chart``
+ - ``bi-directional-audio``
+ - ``speech-to-text``
+ - ``feedback``
+ - ``session-sharing``
+ - ``personalization-memory``
+ - ``personalization-suggested-highlights``
+ - ``mobile-app-access``
+ - ``disable-agent-sharing``
+ - ``disable-image-generation``
+ - ``disable-video-generation``
+ - ``disable-onedrive-upload``
+ - ``disable-talk-to-content``
+ - ``disable-google-drive-upload``
+ - ``disable-welcome-emails``
+ - ``disable-canvas``
+ - ``canvas-workspace``
+ - ``canvas-app-builder``
+ - ``skills``
+ - ``skill-sharing``
+ - ``skill-sharing-without-admin-approval``
+ - ``disable-projects``
+ - ``sobi``
+ - ``enable-end-user-sharing-with-groups``
+ - ``single-agent-orchestration``
+ - ``multi-agent-orchestration``
+ - ``cross-product-intelligence``
+ - ``workflow-agents``
+ - ``in-app-notifications``
+ - ``code-extraction``
+ cmek_config (google.cloud.discoveryengine_v1.types.CmekConfig):
+ Output only. CMEK-related information for the
+ Engine.
+ configurable_billing_approach (google.cloud.discoveryengine_v1.types.Engine.ConfigurableBillingApproach):
+ Optional. Configuration for configurable
+ billing approach.
+ model_configs (MutableMapping[str, google.cloud.discoveryengine_v1.types.Engine.ModelState]):
+ Optional. Maps a model name to its specific configuration
+ for this engine. This allows admin users to turn on/off
+ individual models. This only stores models whose states are
+ overridden by the admin.
+
+ When the state is unspecified, or model_configs is empty for
+ this model, the system will decide if this model should be
+ available or not based on the default configuration. For
+ example, a preview model should be disabled by default if
+ the admin has not chosen to enable it.
+ observability_config (google.cloud.discoveryengine_v1.types.ObservabilityConfig):
+ Optional. Observability config for the
+ engine.
+ connector_tenant_info (MutableMapping[str, str]):
+ Optional. Maps a connector ID (e.g.,
+ "hybrid-github", "shopify") to tenant-specific
+ information required for that connector. The
+ structure of the tenant information string is
+ connector-dependent.
+ agent_gateway_setting (google.cloud.discoveryengine_v1.types.AgentGatewaySetting):
+ Optional. The agent gateway setting for the
+ engine.
+ marketplace_agent_visibility (google.cloud.discoveryengine_v1.types.Engine.MarketplaceAgentVisibility):
+ Optional. The visibility of marketplace
+ agents in the agent gallery.
+ procurement_contact_emails (MutableSequence[str]):
+ Optional. The emails of the procurement
+ contacts.
+ associated_agent_registry (str):
+ Output only. The Agent registry containing
+ the agents, MCP servers and tools associated
+ with this engine. Derived server-side from the
+ linked Agent Gateway's registry.
"""
+ class AppType(proto.Enum):
+ r"""The app of the engine.
+
+ Values:
+ APP_TYPE_UNSPECIFIED (0):
+ All non specified apps.
+ APP_TYPE_INTRANET (1):
+ App type for intranet search and Agentspace.
+ """
+
+ APP_TYPE_UNSPECIFIED = 0
+ APP_TYPE_INTRANET = 1
+
+ class FeatureState(proto.Enum):
+ r"""The state of the feature for the engine.
+
+ Values:
+ FEATURE_STATE_UNSPECIFIED (0):
+ The feature state is unspecified.
+ FEATURE_STATE_ON (1):
+ The feature is turned on to be accessible.
+ FEATURE_STATE_OFF (2):
+ The feature is turned off to be inaccessible.
+ """
+
+ FEATURE_STATE_UNSPECIFIED = 0
+ FEATURE_STATE_ON = 1
+ FEATURE_STATE_OFF = 2
+
+ class ConfigurableBillingApproach(proto.Enum):
+ r"""Configuration for configurable billing approach.
+
+ Values:
+ CONFIGURABLE_BILLING_APPROACH_UNSPECIFIED (0):
+ Default value. For Spark and non-Spark
+ non-configurable billing approach. General
+ pricing model.
+ CONFIGURABLE_BILLING_APPROACH_ENABLED (1):
+ The billing approach follows configurations
+ specified by customer.
+ """
+
+ CONFIGURABLE_BILLING_APPROACH_UNSPECIFIED = 0
+ CONFIGURABLE_BILLING_APPROACH_ENABLED = 1
+
+ class ModelState(proto.Enum):
+ r"""The status of the model for the engine.
+
+ Values:
+ MODEL_STATE_UNSPECIFIED (0):
+ The model state is unspecified.
+ MODEL_ENABLED (1):
+ The model is enabled by admin.
+ MODEL_DISABLED (2):
+ The model is disabled by admin.
+ """
+
+ MODEL_STATE_UNSPECIFIED = 0
+ MODEL_ENABLED = 1
+ MODEL_DISABLED = 2
+
+ class MarketplaceAgentVisibility(proto.Enum):
+ r"""Represents which marketplace agents are visible to any users
+ in agent gallery.
+
+ Values:
+ MARKETPLACE_AGENT_VISIBILITY_UNSPECIFIED (0):
+ Defaults to ``MARKETPLACE_AGENT_VISIBILITY_UNSPECIFIED``.
+ SHOW_AVAILABLE_AGENTS_ONLY (1):
+ Only agents that are currently available for
+ use by the user are visible.
+ SHOW_AGENTS_ALREADY_INTEGRATED (2):
+ Show marketplace agents that the user does not yet have
+ access to but are integrated into the engine. This level
+ also includes all agents visible with
+ ``SHOW_AVAILABLE_AGENTS_ONLY``.
+ SHOW_AGENTS_ALREADY_PURCHASED (3):
+ Show all agents visible with
+ ``SHOW_AGENTS_ALREADY_INTEGRATED``, plus agents that have
+ already been purchased by the project/organization, even if
+ they are not currently integrated into the engine.
+ SHOW_ALL_AGENTS (4):
+ All agents in the marketplace are visible,
+ regardless of access or purchase status. This
+ level encompasses all agents shown in the
+ previous levels.
+ """
+
+ MARKETPLACE_AGENT_VISIBILITY_UNSPECIFIED = 0
+ SHOW_AVAILABLE_AGENTS_ONLY = 1
+ SHOW_AGENTS_ALREADY_INTEGRATED = 2
+ SHOW_AGENTS_ALREADY_PURCHASED = 3
+ SHOW_ALL_AGENTS = 4
+
class SearchEngineConfig(proto.Message):
r"""Configurations for a Search Engine.
@@ -149,6 +342,16 @@ class SearchEngineConfig(proto.Message):
Defaults to
[SearchTier.SEARCH_TIER_STANDARD][google.cloud.discoveryengine.v1.SearchTier.SEARCH_TIER_STANDARD]
if not specified.
+ required_subscription_tier (google.cloud.discoveryengine_v1.types.SubscriptionTier):
+ Optional. The required subscription tier of this engine.
+
+ If the required subscription tier is search, user with
+ higher license tier like assist can still access the
+ standalone app associated with this engine.
+
+ Web grounding feature is only available on the app if it is
+ set as
+ [SubscriptionTier.SUBSCRIPTION_TIER_SEARCH_AND_ASSISTANT][google.cloud.discoveryengine.v1.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH_AND_ASSISTANT].
search_add_ons (MutableSequence[google.cloud.discoveryengine_v1.types.SearchAddOn]):
The add-on that this search engine enables.
"""
@@ -158,6 +361,11 @@ class SearchEngineConfig(proto.Message):
number=1,
enum=common.SearchTier,
)
+ required_subscription_tier: common.SubscriptionTier = proto.Field(
+ proto.ENUM,
+ number=3,
+ enum=common.SubscriptionTier,
+ )
search_add_ons: MutableSequence[common.SearchAddOn] = proto.RepeatedField(
proto.ENUM,
number=2,
@@ -484,6 +692,88 @@ class CommonConfig(proto.Message):
number=1,
)
+ class KnowledgeGraphConfig(proto.Message):
+ r"""Configuration message for the Knowledge Graph.
+
+ Attributes:
+ enable_cloud_knowledge_graph (bool):
+ Whether to enable the Cloud Knowledge Graph
+ for the engine.
+ Defaults to false if not specified.
+ cloud_knowledge_graph_types (MutableSequence[str]):
+ Specify entity types to support.
+ enable_private_knowledge_graph (bool):
+ Whether to enable the Private Knowledge Graph
+ for the engine.
+ Defaults to false if not specified.
+ private_knowledge_graph_types (MutableSequence[str]):
+ Specify entity types to support.
+ feature_config (google.cloud.discoveryengine_v1.types.Engine.KnowledgeGraphConfig.FeatureConfig):
+ Optional. Feature config for the Knowledge
+ Graph.
+ """
+
+ class FeatureConfig(proto.Message):
+ r"""Feature config for the Knowledge Graph.
+
+ Attributes:
+ disable_private_kg_query_understanding (bool):
+ Whether to disable the private KG query
+ understanding for the engine.
+ Defaults to false if not specified.
+ disable_private_kg_enrichment (bool):
+ Whether to disable the private KG enrichment
+ for the engine.
+ Defaults to false if not specified.
+ disable_private_kg_auto_complete (bool):
+ Whether to disable the private KG auto
+ complete for the engine.
+ Defaults to false if not specified.
+ disable_private_kg_query_ui_chips (bool):
+ Whether to disable the private KG for query
+ UI chips.
+ Defaults to false if not specified.
+ """
+
+ disable_private_kg_query_understanding: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+ disable_private_kg_enrichment: bool = proto.Field(
+ proto.BOOL,
+ number=2,
+ )
+ disable_private_kg_auto_complete: bool = proto.Field(
+ proto.BOOL,
+ number=3,
+ )
+ disable_private_kg_query_ui_chips: bool = proto.Field(
+ proto.BOOL,
+ number=4,
+ )
+
+ enable_cloud_knowledge_graph: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+ cloud_knowledge_graph_types: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=2,
+ )
+ enable_private_knowledge_graph: bool = proto.Field(
+ proto.BOOL,
+ number=3,
+ )
+ private_knowledge_graph_types: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=4,
+ )
+ feature_config: "Engine.KnowledgeGraphConfig.FeatureConfig" = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ message="Engine.KnowledgeGraphConfig.FeatureConfig",
+ )
+
class ChatEngineMetadata(proto.Message):
r"""Additional information of a Chat Engine.
Fields in this message are output only.
@@ -563,10 +853,75 @@ class ChatEngineMetadata(proto.Message):
number=15,
message=CommonConfig,
)
+ knowledge_graph_config: KnowledgeGraphConfig = proto.Field(
+ proto.MESSAGE,
+ number=23,
+ message=KnowledgeGraphConfig,
+ )
+ app_type: AppType = proto.Field(
+ proto.ENUM,
+ number=24,
+ enum=AppType,
+ )
disable_analytics: bool = proto.Field(
proto.BOOL,
number=26,
)
+ session_config: common.SessionConfig = proto.Field(
+ proto.MESSAGE,
+ number=29,
+ message=common.SessionConfig,
+ )
+ features: MutableMapping[str, FeatureState] = proto.MapField(
+ proto.STRING,
+ proto.ENUM,
+ number=30,
+ enum=FeatureState,
+ )
+ cmek_config: cmek_config_service.CmekConfig = proto.Field(
+ proto.MESSAGE,
+ number=32,
+ message=cmek_config_service.CmekConfig,
+ )
+ configurable_billing_approach: ConfigurableBillingApproach = proto.Field(
+ proto.ENUM,
+ number=36,
+ enum=ConfigurableBillingApproach,
+ )
+ model_configs: MutableMapping[str, ModelState] = proto.MapField(
+ proto.STRING,
+ proto.ENUM,
+ number=37,
+ enum=ModelState,
+ )
+ observability_config: logging.ObservabilityConfig = proto.Field(
+ proto.MESSAGE,
+ number=39,
+ message=logging.ObservabilityConfig,
+ )
+ connector_tenant_info: MutableMapping[str, str] = proto.MapField(
+ proto.STRING,
+ proto.STRING,
+ number=42,
+ )
+ agent_gateway_setting: gcd_agent_gateway_setting.AgentGatewaySetting = proto.Field(
+ proto.MESSAGE,
+ number=43,
+ message=gcd_agent_gateway_setting.AgentGatewaySetting,
+ )
+ marketplace_agent_visibility: MarketplaceAgentVisibility = proto.Field(
+ proto.ENUM,
+ number=44,
+ enum=MarketplaceAgentVisibility,
+ )
+ procurement_contact_emails: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=45,
+ )
+ associated_agent_registry: str = proto.Field(
+ proto.STRING,
+ number=50,
+ )
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/feedback.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/feedback.py
new file mode 100644
index 000000000000..c0197c67dda0
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/feedback.py
@@ -0,0 +1,258 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.cloud.discoveryengine_v1.types import session as gcd_session
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "Feedback",
+ },
+)
+
+
+class Feedback(proto.Message):
+ r"""Information about the user feedback. This information will be
+ used for logging and metrics purpose.
+
+ Attributes:
+ feedback_type (google.cloud.discoveryengine_v1.types.Feedback.FeedbackType):
+ Required. Indicate whether the user gives a
+ positive or negative feedback. If the user gives
+ a negative feedback, there might be more
+ feedback details.
+ reasons (MutableSequence[google.cloud.discoveryengine_v1.types.Feedback.Reason]):
+ Optional. The reason if user gives a thumb
+ down.
+ comment (str):
+ Optional. The additional user comment of the
+ feedback if user gives a thumb down.
+ conversation_info (google.cloud.discoveryengine_v1.types.Feedback.ConversationInfo):
+ The related conversation information when
+ user gives feedback.
+ llm_model_version (str):
+ The version of the LLM model that was used to
+ generate the response.
+ feedback_source (google.cloud.discoveryengine_v1.types.Feedback.FeedbackSource):
+ Optional. The UI component the user feedback comes from,
+ which could be GOOGLE_CONSOLE, GOOGLE_WIDGET, GOOGLE_WEBAPP.
+ component_version (str):
+ Optional. The version of the component that
+ this report is being sent from.
+ data_terms_accepted (bool):
+ Optional. Whether the customer accepted data
+ use terms.
+ """
+
+ class FeedbackType(proto.Enum):
+ r"""The type of the feedback user gives.
+
+ Values:
+ FEEDBACK_TYPE_UNSPECIFIED (0):
+ Unspecified feedback type.
+ LIKE (1):
+ The user gives a positive feedback.
+ DISLIKE (2):
+ The user gives a negative feedback.
+ """
+
+ FEEDBACK_TYPE_UNSPECIFIED = 0
+ LIKE = 1
+ DISLIKE = 2
+
+ class Reason(proto.Enum):
+ r"""The reason why user gives a negative feedback.
+
+ Values:
+ REASON_UNSPECIFIED (0):
+ Unspecified reason.
+ INACCURATE_RESPONSE (1):
+ The response is inaccurate.
+ NOT_RELEVANT (2):
+ The response is not relevant.
+ INCOMPREHENSIVE (3):
+ The response is incomprehensive.
+ OFFENSIVE_OR_UNSAFE (4):
+ The response is offensive or unsafe.
+ FORMAT_AND_STYLES (6):
+ The response is not well-formatted.
+ BAD_CITATION (7):
+ The response is not well-associated with the
+ query.
+ CANVAS_NOT_GENERATED (8):
+ The expected canvas was not generated for the
+ response.
+ CANVAS_QUALITY_BAD (9):
+ The generated canvas is of bad quality (e.g.
+ inaccurate, incomplete, poorly formatted).
+ CANVAS_EXPORT_FAILED (10):
+ Exporting the generated canvas failed (e.g.
+ download or external export action did not
+ complete successfully).
+ """
+
+ REASON_UNSPECIFIED = 0
+ INACCURATE_RESPONSE = 1
+ NOT_RELEVANT = 2
+ INCOMPREHENSIVE = 3
+ OFFENSIVE_OR_UNSAFE = 4
+ FORMAT_AND_STYLES = 6
+ BAD_CITATION = 7
+ CANVAS_NOT_GENERATED = 8
+ CANVAS_QUALITY_BAD = 9
+ CANVAS_EXPORT_FAILED = 10
+
+ class FeedbackSource(proto.Enum):
+ r"""Source of the feedback as per integration.
+
+ Values:
+ FEEDBACK_SOURCE_UNSPECIFIED (0):
+ Unspecified feedback source.
+ GOOGLE_CONSOLE (1):
+ Feedback source is Google Console.
+ GOOGLE_WIDGET (2):
+ Feedback source is Google Widget.
+ GOOGLE_WEBAPP (3):
+ Feedback source is Google Webapp.
+ GOOGLE_AGENTSPACE_MOBILE (4):
+ Feedback source is Google AgentSpace Mobile
+ app.
+ GOOGLE_AGENTSPACE_DESKTOP (5):
+ Feedback source is Google AgentSpace Desktop
+ app.
+ """
+
+ FEEDBACK_SOURCE_UNSPECIFIED = 0
+ GOOGLE_CONSOLE = 1
+ GOOGLE_WIDGET = 2
+ GOOGLE_WEBAPP = 3
+ GOOGLE_AGENTSPACE_MOBILE = 4
+ GOOGLE_AGENTSPACE_DESKTOP = 5
+
+ class ConversationInfo(proto.Message):
+ r"""The conversation information such as the question index and
+ session name.
+
+ Attributes:
+ question_index (int):
+ The index of the user input within the
+ conversation messages.
+ session (str):
+ Name of the newly generated or continued
+ session.
+ query (google.cloud.discoveryengine_v1.types.Query):
+ Required. The user's search query.
+ assist_token (str):
+ Optional. The token which could be used to
+ fetch the assistant log.
+ answer_query_token (str):
+ Optional. The token which could be used to
+ fetch the answer log.
+ task_name (str):
+ Optional. The full resource name of the Sobi
+ task if the conversation was handled by a
+ long-running agent task. Format (canonical, or
+ the short alias the Task API also accepts):
+
+ projects/{project}/locations/{location}/agents/{agent}/tasks/{task}
+ projects/{project}/locations/{location}/tasks/{task}
+ trajectory_id (str):
+ Optional. The runtime trajectory id of the rated agent task
+ turn, as set on ``TaskServerEvent.trajectory_id``. Shared by
+ all steps of the turn.
+ step_seq_num (int):
+ Optional. The ``TaskServerEvent.seq_num`` of the step that
+ opened the rated agent task reply.
+ """
+
+ question_index: int = proto.Field(
+ proto.INT32,
+ number=1,
+ )
+ session: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ query: gcd_session.Query = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message=gcd_session.Query,
+ )
+ assist_token: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ answer_query_token: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+ task_name: str = proto.Field(
+ proto.STRING,
+ number=6,
+ )
+ trajectory_id: str = proto.Field(
+ proto.STRING,
+ number=7,
+ )
+ step_seq_num: int = proto.Field(
+ proto.INT64,
+ number=8,
+ )
+
+ feedback_type: FeedbackType = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum=FeedbackType,
+ )
+ reasons: MutableSequence[Reason] = proto.RepeatedField(
+ proto.ENUM,
+ number=2,
+ enum=Reason,
+ )
+ comment: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ conversation_info: ConversationInfo = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=ConversationInfo,
+ )
+ llm_model_version: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+ feedback_source: FeedbackSource = proto.Field(
+ proto.ENUM,
+ number=6,
+ enum=FeedbackSource,
+ )
+ component_version: str = proto.Field(
+ proto.STRING,
+ number=7,
+ )
+ data_terms_accepted: bool = proto.Field(
+ proto.BOOL,
+ number=8,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/grounded_generation_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/grounded_generation_service.py
index 966b1b3281ee..386baff6f89e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/grounded_generation_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/grounded_generation_service.py
@@ -17,6 +17,7 @@
from typing import MutableMapping, MutableSequence
+import google.type.date_pb2 as date_pb2 # type: ignore
import proto # type: ignore
from google.cloud.discoveryengine_v1.types import grounding
@@ -30,6 +31,8 @@
"CheckGroundingSpec",
"CheckGroundingRequest",
"CheckGroundingResponse",
+ "CitationMetadata",
+ "Citation",
},
)
@@ -175,8 +178,31 @@ class GenerationSpec(proto.Message):
tokens will be used.
This field is a member of `oneof`_ ``_max_output_tokens``.
+ provisioned_throughput_setting (google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest.GenerationSpec.ProvisionedThroughputSetting):
+ Optional. Setting for provisioned throughput.
"""
+ class ProvisionedThroughputSetting(proto.Enum):
+ r"""Setting for provisioned throughput.
+
+ Values:
+ PROVISIONED_THROUGHPUT_SETTING_UNSPECIFIED (0):
+ Default value. If the user has remaining
+ provisioned throughput, provisioned throughput
+ will be used. Otherwise, pay as you go will be
+ used.
+ PROVISIONED_THROUGHPUT_ONLY (1):
+ Only use provisioned throughput. If the user
+ has no remaining provisioned throughput, an
+ error will be returned.
+ PAY_AS_YOU_GO_ONLY (2):
+ Disables provisioned throughput.
+ """
+
+ PROVISIONED_THROUGHPUT_SETTING_UNSPECIFIED = 0
+ PROVISIONED_THROUGHPUT_ONLY = 1
+ PAY_AS_YOU_GO_ONLY = 2
+
model_id: str = proto.Field(
proto.STRING,
number=3,
@@ -220,6 +246,11 @@ class GenerationSpec(proto.Message):
number=10,
optional=True,
)
+ provisioned_throughput_setting: "GenerateGroundedContentRequest.GenerationSpec.ProvisionedThroughputSetting" = proto.Field(
+ proto.ENUM,
+ number=13,
+ enum="GenerateGroundedContentRequest.GenerationSpec.ProvisionedThroughputSetting",
+ )
class DynamicRetrievalConfiguration(proto.Message):
r"""Describes the options to customize dynamic retrieval.
@@ -387,6 +418,13 @@ class GoogleSearchSource(proto.Message):
dynamic_retrieval_config (google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest.DynamicRetrievalConfiguration):
Optional. Specifies the dynamic retrieval
configuration for the given source.
+ exclude_domains (MutableSequence[str]):
+ Optional. List of domains to be excluded from
+ the search results.
+ blocking_confidence (google.cloud.discoveryengine_v1.types.Citation.PhishBlockThreshold):
+ Optional. Sites with confidence level chosen
+ & above this value will be blocked from the
+ search results.
"""
dynamic_retrieval_config: "GenerateGroundedContentRequest.DynamicRetrievalConfiguration" = proto.Field(
@@ -394,13 +432,40 @@ class GoogleSearchSource(proto.Message):
number=2,
message="GenerateGroundedContentRequest.DynamicRetrievalConfiguration",
)
+ exclude_domains: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=5,
+ )
+ blocking_confidence: "Citation.PhishBlockThreshold" = proto.Field(
+ proto.ENUM,
+ number=6,
+ enum="Citation.PhishBlockThreshold",
+ )
class EnterpriseWebRetrievalSource(proto.Message):
r"""Params for using enterprise web retrieval as grounding
source.
+ Attributes:
+ exclude_domains (MutableSequence[str]):
+ Optional. List of domains to be excluded from
+ the search results.
+ blocking_confidence (google.cloud.discoveryengine_v1.types.Citation.PhishBlockThreshold):
+ Optional. Sites with confidence level chosen
+ & above this value will be blocked from the
+ search results.
"""
+ exclude_domains: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=1,
+ )
+ blocking_confidence: "Citation.PhishBlockThreshold" = proto.Field(
+ proto.ENUM,
+ number=2,
+ enum="Citation.PhishBlockThreshold",
+ )
+
inline_source: "GenerateGroundedContentRequest.GroundingSource.InlineSource" = (
proto.Field(
proto.MESSAGE,
@@ -531,6 +596,8 @@ class GroundingMetadata(proto.Message):
that the claim is supported by the fact.
images (MutableSequence[google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.ImageMetadata]):
Images from the web search.
+ videos (MutableSequence[google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse.Candidate.GroundingMetadata.VideoMetadata]):
+ Videos from the web search.
"""
class RetrievalMetadata(proto.Message):
@@ -715,6 +782,8 @@ class WebsiteInfo(proto.Message):
The url of the website.
title (str):
The title of the website.
+ site_display_name (str):
+ The display name of the website.
"""
uri: str = proto.Field(
@@ -725,6 +794,10 @@ class WebsiteInfo(proto.Message):
proto.STRING,
number=2,
)
+ site_display_name: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
class Image(proto.Message):
r"""Metadata about the image.
@@ -767,6 +840,19 @@ class Image(proto.Message):
message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.ImageMetadata.WebsiteInfo",
)
+ class VideoMetadata(proto.Message):
+ r"""Metadata about a video from the web search.
+
+ Attributes:
+ youtube_external_id (str):
+ The external id of the video.
+ """
+
+ youtube_external_id: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
retrieval_metadata: MutableSequence[
"GenerateGroundedContentResponse.Candidate.GroundingMetadata.RetrievalMetadata"
] = proto.RepeatedField(
@@ -802,6 +888,13 @@ class Image(proto.Message):
number=9,
message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.ImageMetadata",
)
+ videos: MutableSequence[
+ "GenerateGroundedContentResponse.Candidate.GroundingMetadata.VideoMetadata"
+ ] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=11,
+ message="GenerateGroundedContentResponse.Candidate.GroundingMetadata.VideoMetadata",
+ )
index: int = proto.Field(
proto.INT32,
@@ -1088,4 +1181,103 @@ class Claim(proto.Message):
)
+class CitationMetadata(proto.Message):
+ r"""A collection of source attributions for a piece of content.
+
+ Attributes:
+ citations (MutableSequence[google.cloud.discoveryengine_v1.types.Citation]):
+ Output only. List of citations.
+ """
+
+ citations: MutableSequence["Citation"] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message="Citation",
+ )
+
+
+class Citation(proto.Message):
+ r"""Source attributions for content.
+
+ Attributes:
+ start_index (int):
+ Output only. Start index into the content.
+ end_index (int):
+ Output only. End index into the content.
+ uri (str):
+ Output only. Url reference of the
+ attribution.
+ title (str):
+ Output only. Title of the attribution.
+ license_ (str):
+ Output only. License of the attribution.
+ publication_date (google.type.date_pb2.Date):
+ Output only. Publication date of the
+ attribution.
+ """
+
+ class PhishBlockThreshold(proto.Enum):
+ r"""These are available confidence level user can set to block
+ malicious urls with chosen confidence and above. For
+ understanding different confidence of webrisk, please refer to
+ https://cloud.google.com/web-risk/docs/reference/rpc/google.cloud.webrisk.v1eap1#confidencelevel
+
+ Values:
+ PHISH_BLOCK_THRESHOLD_UNSPECIFIED (0):
+ Defaults to unspecified.
+ BLOCK_LOW_AND_ABOVE (30):
+ Blocks Low and above confidence URL that is
+ risky.
+ BLOCK_MEDIUM_AND_ABOVE (40):
+ Blocks Medium and above confidence URL that
+ is risky.
+ BLOCK_HIGH_AND_ABOVE (50):
+ Blocks High and above confidence URL that is
+ risky.
+ BLOCK_HIGHER_AND_ABOVE (55):
+ Blocks Higher and above confidence URL that
+ is risky.
+ BLOCK_VERY_HIGH_AND_ABOVE (60):
+ Blocks Very high and above confidence URL
+ that is risky.
+ BLOCK_ONLY_EXTREMELY_HIGH (100):
+ Blocks Extremely high confidence URL that is
+ risky.
+ """
+
+ PHISH_BLOCK_THRESHOLD_UNSPECIFIED = 0
+ BLOCK_LOW_AND_ABOVE = 30
+ BLOCK_MEDIUM_AND_ABOVE = 40
+ BLOCK_HIGH_AND_ABOVE = 50
+ BLOCK_HIGHER_AND_ABOVE = 55
+ BLOCK_VERY_HIGH_AND_ABOVE = 60
+ BLOCK_ONLY_EXTREMELY_HIGH = 100
+
+ start_index: int = proto.Field(
+ proto.INT32,
+ number=1,
+ )
+ end_index: int = proto.Field(
+ proto.INT32,
+ number=2,
+ )
+ uri: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ title: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ license_: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+ publication_date: date_pb2.Date = proto.Field(
+ proto.MESSAGE,
+ number=6,
+ message=date_pb2.Date,
+ )
+
+
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/identity_mapping_store.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/identity_mapping_store.py
index 12bcf937c180..f8046fe5bf5a 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/identity_mapping_store.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/identity_mapping_store.py
@@ -101,6 +101,8 @@ class IdentityMappingEntry(proto.Message):
Required. Identity outside the customer
identity provider. The length limit of external
identity will be of 100 characters.
+ external_identity_name (str):
+ Optional. The name of the external identity.
"""
user_id: str = proto.Field(
@@ -117,6 +119,10 @@ class IdentityMappingEntry(proto.Message):
proto.STRING,
number=1,
)
+ external_identity_name: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/import_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/import_config.py
index b6cbc2b841e5..aa9888ffd042 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/import_config.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/import_config.py
@@ -824,8 +824,9 @@ class ImportUserEventsMetadata(proto.Message):
create_time (google.protobuf.timestamp_pb2.Timestamp):
Operation create time.
update_time (google.protobuf.timestamp_pb2.Timestamp):
- Operation last update time. If the operation
- is done, this is also the finish time.
+ Output only. Operation last update time. If
+ the operation is done, this is also the finish
+ time.
success_count (int):
Count of entries that were processed
successfully.
@@ -1031,7 +1032,6 @@ class ImportDocumentsRequest(proto.Message):
INVALID_ARGUMENT error is thrown.
- [SpannerSource][google.cloud.discoveryengine.v1.SpannerSource].
- [CloudSqlSource][google.cloud.discoveryengine.v1.CloudSqlSource].
- - [FirestoreSource][google.cloud.discoveryengine.v1.FirestoreSource].
- [BigtableSource][google.cloud.discoveryengine.v1.BigtableSource].
force_refresh_content (bool):
Optional. Whether to force refresh the unstructured content
@@ -1056,7 +1056,11 @@ class ReconciliationMode(proto.Enum):
Calculates diff and replaces the entire
document dataset. Existing documents may be
deleted if they are not present in the source
- location.
+ location. When using this mode, there won't be
+ any downtime on the dataset targeted. Any
+ document that should remain unchanged or that
+ should be updated will continue serving while
+ the operation is running.
"""
RECONCILIATION_MODE_UNSPECIFIED = 0
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/license_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/license_config.py
new file mode 100644
index 000000000000..f8ddba8726c6
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/license_config.py
@@ -0,0 +1,176 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.type.date_pb2 as date_pb2 # type: ignore
+import proto # type: ignore
+
+from google.cloud.discoveryengine_v1.types import common
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "LicenseConfig",
+ },
+)
+
+
+class LicenseConfig(proto.Message):
+ r"""Information about users' licenses.
+
+ Attributes:
+ name (str):
+ Immutable. Identifier. The fully qualified resource name of
+ the license config. Format:
+ ``projects/{project}/locations/{location}/licenseConfigs/{license_config}``
+ license_count (int):
+ Required. Number of licenses purchased.
+ subscription_tier (google.cloud.discoveryengine_v1.types.SubscriptionTier):
+ Required. Subscription tier information for
+ the license config.
+ state (google.cloud.discoveryengine_v1.types.LicenseConfig.State):
+ Output only. The state of the license config.
+ auto_renew (bool):
+ Optional. Whether the license config should
+ be auto renewed when it reaches the end date.
+ start_date (google.type.date_pb2.Date):
+ Required. The start date.
+ end_date (google.type.date_pb2.Date):
+ Optional. The planed end date.
+ subscription_term (google.cloud.discoveryengine_v1.types.SubscriptionTerm):
+ Required. Subscription term.
+ free_trial (bool):
+ Optional. Whether the license config is for
+ free trial.
+ gemini_bundle (bool):
+ Output only. Whether the license config is
+ for Gemini bundle.
+ early_terminated (bool):
+ Output only. Indication of whether the
+ subscription is terminated earlier than the
+ expiration date.
+ early_termination_date (google.type.date_pb2.Date):
+ Output only. The date when the subscription
+ is terminated earlier than the expiration date.
+ last_user_update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Optional. Timestamp of the most recent user-initiated update
+ (seat count change or subscription term change). Unlike
+ ``update_time``, this field is only stamped when a customer
+ explicitly updates the license (e.g. via the UI), and is not
+ touched by system-driven writes (subscription pipeline, BALC
+ propagation, etc.).
+ """
+
+ class State(proto.Enum):
+ r"""License config state enumeration.
+
+ Values:
+ STATE_UNSPECIFIED (0):
+ Default value. The license config does not
+ exist.
+ ACTIVE (1):
+ The license config is effective and being
+ used.
+ EXPIRED (2):
+ The license config has expired.
+ NOT_STARTED (3):
+ The license config has not started yet, and
+ its start date is in the future.
+ WITHDRAWN (4):
+ This is when a sub license config has
+ returned all its seats back to
+ BillingAccountLicenseConfig that it belongs to.
+ Similar to EXPIRED.
+ DEACTIVATING (5):
+ The license config is in a grace period. Its
+ subscription has ended, either through early
+ termination or by reaching its end date, but the
+ customer keeps access for a limited time. It
+ becomes EXPIRED when the grace period ends.
+ """
+
+ STATE_UNSPECIFIED = 0
+ ACTIVE = 1
+ EXPIRED = 2
+ NOT_STARTED = 3
+ WITHDRAWN = 4
+ DEACTIVATING = 5
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ license_count: int = proto.Field(
+ proto.INT64,
+ number=2,
+ )
+ subscription_tier: common.SubscriptionTier = proto.Field(
+ proto.ENUM,
+ number=3,
+ enum=common.SubscriptionTier,
+ )
+ state: State = proto.Field(
+ proto.ENUM,
+ number=4,
+ enum=State,
+ )
+ auto_renew: bool = proto.Field(
+ proto.BOOL,
+ number=5,
+ )
+ start_date: date_pb2.Date = proto.Field(
+ proto.MESSAGE,
+ number=6,
+ message=date_pb2.Date,
+ )
+ end_date: date_pb2.Date = proto.Field(
+ proto.MESSAGE,
+ number=7,
+ message=date_pb2.Date,
+ )
+ subscription_term: common.SubscriptionTerm = proto.Field(
+ proto.ENUM,
+ number=8,
+ enum=common.SubscriptionTerm,
+ )
+ free_trial: bool = proto.Field(
+ proto.BOOL,
+ number=9,
+ )
+ gemini_bundle: bool = proto.Field(
+ proto.BOOL,
+ number=11,
+ )
+ early_terminated: bool = proto.Field(
+ proto.BOOL,
+ number=12,
+ )
+ early_termination_date: date_pb2.Date = proto.Field(
+ proto.MESSAGE,
+ number=13,
+ message=date_pb2.Date,
+ )
+ last_user_update_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=16,
+ message=timestamp_pb2.Timestamp,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/license_config_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/license_config_service.py
new file mode 100644
index 000000000000..57a775a77ba8
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/license_config_service.py
@@ -0,0 +1,346 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 proto # type: ignore
+
+from google.cloud.discoveryengine_v1.types import license_config as gcd_license_config
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "CreateLicenseConfigRequest",
+ "UpdateLicenseConfigRequest",
+ "GetLicenseConfigRequest",
+ "ListLicenseConfigsRequest",
+ "ListLicenseConfigsResponse",
+ "DistributeLicenseConfigRequest",
+ "DistributeLicenseConfigResponse",
+ "RetractLicenseConfigRequest",
+ "RetractLicenseConfigResponse",
+ },
+)
+
+
+class CreateLicenseConfigRequest(proto.Message):
+ r"""Request message for
+ [LicenseConfigService.CreateLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.CreateLicenseConfig]
+ method.
+
+ Attributes:
+ parent (str):
+ Required. The parent resource name, such as
+ ``projects/{project}/locations/{location}``.
+ license_config (google.cloud.discoveryengine_v1.types.LicenseConfig):
+ Required. The
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ to create.
+ license_config_id (str):
+ Optional. The ID to use for the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig],
+ which will become the final component of the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]'s
+ resource name. We are using the tier (product edition) name
+ as the license config id such as ``search`` or
+ ``search_and_assistant``.
+ """
+
+ parent: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ license_config: gcd_license_config.LicenseConfig = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=gcd_license_config.LicenseConfig,
+ )
+ license_config_id: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+
+class UpdateLicenseConfigRequest(proto.Message):
+ r"""Request message for
+ [LicenseConfigService.UpdateLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.UpdateLicenseConfig]
+ method.
+
+ Attributes:
+ license_config (google.cloud.discoveryengine_v1.types.LicenseConfig):
+ Required. The
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ to update.
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
+ Optional. Indicates which fields in the provided
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ to update.
+
+ If an unsupported or unknown field is provided, an
+ INVALID_ARGUMENT error is returned.
+ """
+
+ license_config: gcd_license_config.LicenseConfig = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_license_config.LicenseConfig,
+ )
+ update_mask: field_mask_pb2.FieldMask = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=field_mask_pb2.FieldMask,
+ )
+
+
+class GetLicenseConfigRequest(proto.Message):
+ r"""Request message for
+ [LicenseConfigService.GetLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.GetLicenseConfig]
+ method.
+
+ Attributes:
+ name (str):
+ Required. Full resource name of
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig],
+ such as
+ ``projects/{project}/locations/{location}/licenseConfigs/*``.
+
+ If the caller does not have permission to access the
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig],
+ regardless of whether or not it exists, a PERMISSION_DENIED
+ error is returned.
+
+ If the requested
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ does not exist, a NOT_FOUND error is returned.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class ListLicenseConfigsRequest(proto.Message):
+ r"""Request message for
+ [LicenseConfigService.ListLicenseConfigs][google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs]
+ method.
+
+ Attributes:
+ parent (str):
+ Required. The parent branch resource name, such as
+ ``projects/{project}/locations/{location}``.
+ page_size (int):
+ Optional. Not supported.
+ page_token (str):
+ Optional. Not supported.
+ filter (str):
+ Optional. The filter to apply to the list results.
+
+ The supported fields are:
+
+ - ``subscription_tier``
+ - ``state``
+
+ Examples:
+
+ - ``subscription_tier=SUBSCRIPTION_TIER_SEARCH,state=ACTIVE``
+ - Lists all active search license configs.
+ - ``state=ACTIVE`` - Lists all active license configs.
+
+ The filter string should be a comma-separated list of
+ field=value pairs.
+ """
+
+ 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,
+ )
+
+
+class ListLicenseConfigsResponse(proto.Message):
+ r"""Response message for
+ [LicenseConfigService.ListLicenseConfigs][google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs]
+ method.
+
+ Attributes:
+ license_configs (MutableSequence[google.cloud.discoveryengine_v1.types.LicenseConfig]):
+ All the customer's
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]s.
+ next_page_token (str):
+ Not supported.
+ """
+
+ @property
+ def raw_page(self):
+ return self
+
+ license_configs: MutableSequence[gcd_license_config.LicenseConfig] = (
+ proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_license_config.LicenseConfig,
+ )
+ )
+ next_page_token: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+
+class DistributeLicenseConfigRequest(proto.Message):
+ r"""Request message for
+ [LicenseConfigService.DistributeLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig]
+ method.
+
+ Attributes:
+ billing_account_license_config (str):
+ Required. Full resource name of
+ [BillingAccountLicenseConfig][].
+
+ Format:
+ ``billingAccounts/{billing_account}/billingAccountLicenseConfigs/{billing_account_license_config_id}``.
+ project_number (int):
+ Required. The target GCP project number to
+ distribute the license config to.
+ location (str):
+ Required. The target GCP project region to
+ distribute the license config to.
+ license_count (int):
+ Required. The number of licenses to
+ distribute.
+ license_config_id (str):
+ Optional. Distribute seats to this license
+ config instead of creating a new one. If not
+ specified, a new license config will be created
+ from the billing account license config.
+ """
+
+ billing_account_license_config: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ project_number: int = proto.Field(
+ proto.INT64,
+ number=2,
+ )
+ location: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ license_count: int = proto.Field(
+ proto.INT64,
+ number=4,
+ )
+ license_config_id: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+
+
+class DistributeLicenseConfigResponse(proto.Message):
+ r"""Response message for
+ [LicenseConfigService.DistributeLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig]
+ method.
+
+ Attributes:
+ license_config (google.cloud.discoveryengine_v1.types.LicenseConfig):
+ The updated or created LicenseConfig.
+ """
+
+ license_config: gcd_license_config.LicenseConfig = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_license_config.LicenseConfig,
+ )
+
+
+class RetractLicenseConfigRequest(proto.Message):
+ r"""Request message for
+ [LicenseConfigService.RetractLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig]
+ method.
+
+ Attributes:
+ billing_account_license_config (str):
+ Required. Full resource name of
+ [BillingAccountLicenseConfig][].
+
+ Format:
+ ``billingAccounts/{billing_account}/billingAccountLicenseConfigs/{billing_account_license_config_id}``.
+ license_config (str):
+ Required. Full resource name of
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig].
+
+ Format:
+ ``projects/{project}/locations/{location}/licenseConfigs/{license_config_id}``.
+ full_retract (bool):
+ Optional. If set to true, retract the entire
+ license config. Otherwise, retract the specified
+ license count.
+ license_count (int):
+ Optional. The number of licenses to retract. Only used when
+ full_retract is false.
+ """
+
+ billing_account_license_config: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ license_config: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ full_retract: bool = proto.Field(
+ proto.BOOL,
+ number=3,
+ )
+ license_count: int = proto.Field(
+ proto.INT64,
+ number=4,
+ )
+
+
+class RetractLicenseConfigResponse(proto.Message):
+ r"""Response message for
+ [LicenseConfigService.RetractLicenseConfig][google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig]
+ method.
+
+ Attributes:
+ license_config (google.cloud.discoveryengine_v1.types.LicenseConfig):
+ The updated LicenseConfig.
+ """
+
+ license_config: gcd_license_config.LicenseConfig = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_license_config.LicenseConfig,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/logging.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/logging.py
new file mode 100644
index 000000000000..630d8ea7b85a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/logging.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.
+#
+from __future__ import annotations
+
+from typing import MutableMapping, MutableSequence
+
+import proto # type: ignore
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "ObservabilityConfig",
+ },
+)
+
+
+class ObservabilityConfig(proto.Message):
+ r"""Observability config for a resource.
+
+ Attributes:
+ observability_enabled (bool):
+ Optional. Enables observability. If ``false``, all other
+ flags are ignored.
+ sensitive_logging_enabled (bool):
+ Optional. Enables sensitive logging. Sensitive logging
+ includes customer core content (e.g. prompts, responses). If
+ ``false``, will sanitize all sensitive fields.
+ """
+
+ observability_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+ sensitive_logging_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=2,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/project.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/project.py
index 80dc3a5298ba..1f3360be980f 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/project.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/project.py
@@ -20,6 +20,8 @@
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
import proto # type: ignore
+from google.cloud.discoveryengine_v1.types import logging
+
__protobuf__ = proto.module(
package="google.cloud.discoveryengine.v1",
manifest={
@@ -50,6 +52,11 @@ class Project(proto.Message):
Output only. A map of terms of services. The key is the
``id`` of
[ServiceTerms][google.cloud.discoveryengine.v1.Project.ServiceTerms].
+ customer_provided_config (google.cloud.discoveryengine_v1.types.Project.CustomerProvidedConfig):
+ Optional. Customer provided configurations.
+ configurable_billing_status (google.cloud.discoveryengine_v1.types.Project.ConfigurableBillingStatus):
+ Output only. The current status of the
+ project's configurable billing.
"""
class ServiceTerms(proto.Message):
@@ -128,6 +135,364 @@ class State(proto.Enum):
message=timestamp_pb2.Timestamp,
)
+ class CustomerProvidedConfig(proto.Message):
+ r"""Customer provided configurations.
+
+ Attributes:
+ notebooklm_config (google.cloud.discoveryengine_v1.types.Project.CustomerProvidedConfig.NotebooklmConfig):
+ Optional. Configuration for NotebookLM
+ settings.
+ resource_access_control_config (google.cloud.discoveryengine_v1.types.Project.CustomerProvidedConfig.ResourceAccessControlConfig):
+ Optional. Resource-level access control
+ config for Gemini Enterprise users.
+ """
+
+ class NotebooklmConfig(proto.Message):
+ r"""Configuration for NotebookLM.
+
+ Attributes:
+ model_armor_config (google.cloud.discoveryengine_v1.types.Project.CustomerProvidedConfig.NotebooklmConfig.ModelArmorConfig):
+ Model Armor configuration to be used for
+ sanitizing user prompts and LLM responses.
+ opt_out_notebook_sharing (bool):
+ Optional. Whether to disable the notebook
+ sharing feature for the project. Default to
+ false if not specified.
+ data_protection_policy (google.cloud.discoveryengine_v1.types.Project.CustomerProvidedConfig.NotebooklmConfig.DataProtectionPolicy):
+ Optional. Specifies the data protection
+ policy for NotebookLM.
+ observability_config (google.cloud.discoveryengine_v1.types.ObservabilityConfig):
+ Optional. Observability config for
+ NotebookLM.
+ """
+
+ class ModelArmorConfig(proto.Message):
+ r"""Configuration for customer defined Model Armor templates to
+ be used for sanitizing user prompts and LLM responses.
+
+ Attributes:
+ user_prompt_template (str):
+ Optional. The resource name of the Model Armor Template for
+ sanitizing user prompts. Format:
+ projects/{project}/locations/{location}/templates/{template_id}
+ If not specified, no sanitization will be applied to the
+ user prompt.
+ response_template (str):
+ Optional. The resource name of the Model Armor Template for
+ sanitizing LLM responses. Format:
+ projects/{project}/locations/{location}/templates/{template_id}
+ If not specified, no sanitization will be applied to the LLM
+ response.
+ """
+
+ user_prompt_template: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ response_template: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+ class DataProtectionPolicy(proto.Message):
+ r"""Data protection policy config for NotebookLM.
+
+ Attributes:
+ sensitive_data_protection_policy (google.cloud.discoveryengine_v1.types.Project.CustomerProvidedConfig.NotebooklmConfig.DataProtectionPolicy.SensitiveDataProtectionPolicy):
+ Optional. The sensitive data protection
+ policy.
+ """
+
+ class SensitiveDataProtectionPolicy(proto.Message):
+ r"""Specifies a Sensitive Data Protection
+ (https://cloud.google.com/sensitive-data-protection/docs/sensitive-data-protection-overview)
+ policy.
+
+ Attributes:
+ policy (str):
+ Optional. The Sensitive Data Protection
+ policy resource name.
+ """
+
+ policy: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+ sensitive_data_protection_policy: "Project.CustomerProvidedConfig.NotebooklmConfig.DataProtectionPolicy.SensitiveDataProtectionPolicy" = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message="Project.CustomerProvidedConfig.NotebooklmConfig.DataProtectionPolicy.SensitiveDataProtectionPolicy",
+ )
+
+ model_armor_config: "Project.CustomerProvidedConfig.NotebooklmConfig.ModelArmorConfig" = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message="Project.CustomerProvidedConfig.NotebooklmConfig.ModelArmorConfig",
+ )
+ opt_out_notebook_sharing: bool = proto.Field(
+ proto.BOOL,
+ number=2,
+ )
+ data_protection_policy: "Project.CustomerProvidedConfig.NotebooklmConfig.DataProtectionPolicy" = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ message="Project.CustomerProvidedConfig.NotebooklmConfig.DataProtectionPolicy",
+ )
+ observability_config: logging.ObservabilityConfig = proto.Field(
+ proto.MESSAGE,
+ number=6,
+ message=logging.ObservabilityConfig,
+ )
+
+ class ResourceAccessControlConfig(proto.Message):
+ r"""Controls resource-level access control for Gemini Enterprise
+ users.
+
+ Attributes:
+ data_store_access_control_enabled (bool):
+ Optional. If ``true``, the data stores and data connectors
+ shown to Gemini Enterprise users are filtered to those the
+ user has the required resource-level ``.get`` IAM permission
+ on.
+ """
+
+ data_store_access_control_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+
+ notebooklm_config: "Project.CustomerProvidedConfig.NotebooklmConfig" = (
+ proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message="Project.CustomerProvidedConfig.NotebooklmConfig",
+ )
+ )
+ resource_access_control_config: "Project.CustomerProvidedConfig.ResourceAccessControlConfig" = proto.Field(
+ proto.MESSAGE,
+ number=6,
+ message="Project.CustomerProvidedConfig.ResourceAccessControlConfig",
+ )
+
+ class ConfigurableBillingStatus(proto.Message):
+ r"""Represents the currently effective configurable billing parameters.
+ These values are derived from the customer's subscription history
+ stored internally and reflect the thresholds actively being used for
+ billing purposes at the time of the GetProject call. This includes
+ the start_time of the subscription and may differ from the values in
+ ``customer_provided_config`` due to billing rules (e.g., scale-downs
+ taking effect only at the start of a new month). We also include the
+ update type to indicate the type of update performed on the
+ configurable billing configuration in the UpdateProject operation.
+
+ Attributes:
+ effective_search_qpm_threshold (int):
+ Optional. The currently effective Search QPM
+ threshold in queries per minute. This is the
+ threshold against which QPM usage is compared
+ for overage calculations.
+ effective_indexing_core_threshold (int):
+ Optional. The currently effective Indexing
+ Core threshold. This is the threshold against
+ which Indexing Core usage is compared for
+ overage calculations.
+ start_time (google.protobuf.timestamp_pb2.Timestamp):
+ Optional. The start time of the currently
+ active billing subscription.
+ terminate_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. The latest terminate effective
+ time of search qpm and indexing core
+ subscriptions.
+ search_qpm_threshold_next_update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. The earliest next update time for the search
+ QPM subscription threshold. This is based on the
+ next_update_time returned by the underlying Cloud Billing
+ Subscription V3 API. This field is populated only if an
+ update QPM subscription threshold request is succeeded.
+ indexing_core_threshold_next_update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. The earliest next update time for the indexing
+ core subscription threshold. This is based on the
+ next_update_time returned by the underlying Cloud Billing
+ Subscription V3 API. This field is populated only if an
+ update indexing core subscription threshold request is
+ succeeded.
+ update_type (google.cloud.discoveryengine_v1.types.Project.ConfigurableBillingStatus.UpdateType):
+ Output only. The type of update performed in
+ this operation. This field is populated in the
+ response of UpdateProject.
+ agent_search_token_subscription_statuses (MutableSequence[google.cloud.discoveryengine_v1.types.Project.ConfigurableBillingStatus.AgentSearchTokenSubscriptionStatus]):
+ Output only. Per-model Agent Search TPM
+ subscription status.
+ """
+
+ class UpdateType(proto.Enum):
+ r"""The type of update performed on the configurable billing
+ configuration.
+
+ Values:
+ UPDATE_TYPE_UNSPECIFIED (0):
+ Unspecified update type.
+ CREATE (1):
+ Configurable billing was created/enabled.
+ DELETE (2):
+ Configurable billing was deleted/disabled.
+ SCALE_UP (3):
+ Subscription was scaled up (thresholds
+ increased).
+ SCALE_DOWN (4):
+ Subscription was scaled down (thresholds
+ decreased).
+ """
+
+ UPDATE_TYPE_UNSPECIFIED = 0
+ CREATE = 1
+ DELETE = 2
+ SCALE_UP = 3
+ SCALE_DOWN = 4
+
+ class AgentSearchTokenSubscriptionStatus(proto.Message):
+ r"""Per-model Agent Search TPM subscription status. One entry per active
+ ``core_subscription.agent_search_token_subscriptions[*]`` entry in
+ the customer-provided config; populated by UpdateProject and
+ GetProject.
+
+ The lifecycle scalars on this message (``start_time``,
+ ``terminate_time``, ``update_type``,
+ ``tpm_threshold_next_update_time``) are per (project, model_version)
+ — siblings of the whole-relationship ``start_time`` /
+ ``terminate_time`` / ``update_type`` on the enclosing
+ ConfigurableBillingStatus, but scoped to this specific Agent Search
+ TPM subscription instead of to the overall customer-configurable-
+ pricing relationship. This per-instance granularity is intentional:
+ the underlying SubV3 storage is per-(project, model_version), so
+ each model has its own activation, termination, and deferred-update
+ clock; surfacing that on the response gives customers the
+ granularity they need to manage per-model commitments independently.
+ QPM / IndexingCore differ — their storage is one row per (project,
+ location), so their lifecycle is represented only by the whole-
+ relationship scalars on ConfigurableBillingStatus.
+
+ Attributes:
+ model_version (str):
+ Output only. The Gemini model version this status
+ corresponds to. Matches
+ CoreSubscription.AgentSearchTokenSubscription.model_version
+ (a stable Gemini model version from the Gemini Enterprise
+ Agent Platform model-versions registry; see
+ https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/model-versions#gemini-models).
+ effective_tpm_threshold (int):
+ Output only. The currently effective TPM threshold. Reflects
+ scale-up immediately and scale-down at the next billing
+ cycle, matching ``effective_search_qpm_threshold``
+ semantics.
+ tpm_threshold_next_update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. The earliest next update time for the TPM
+ subscription threshold for this (project, model_version).
+ Populated only after a successful update.
+ start_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. When this (project, model_version) Agent Search
+ TPM subscription was first activated. Set once on first
+ activation of this model version and never moved by
+ subsequent threshold updates; on termination + re-activation
+ a new value is recorded. Does NOT move the
+ whole-relationship ``start_time`` on the enclosing
+ ConfigurableBillingStatus, which continues to represent the
+ first activation of the overall
+ customer-configurable-pricing relationship.
+ terminate_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. If set, the scheduled effective time at which
+ this (project, model_version) Agent Search TPM subscription
+ will terminate. Populated when the customer removes this
+ entry from
+ ``core_subscription.agent_search_token_subscriptions[*]``.
+ Does NOT move the whole-relationship ``terminate_time`` on
+ the enclosing ConfigurableBillingStatus, which is populated
+ only when the entire customer-configurable-pricing
+ relationship is being torn down.
+ update_type (google.cloud.discoveryengine_v1.types.Project.ConfigurableBillingStatus.UpdateType):
+ Output only. The type of the most recent update to this
+ (project, model_version) subscription, as performed by the
+ most recent UpdateProject call. ``UPDATE_TYPE_UNSPECIFIED``
+ indicates this model_version was not touched by the most
+ recent UpdateProject (its ``effective_tpm_threshold``
+ reflects an earlier update). The whole-relationship
+ ``update_type`` on the enclosing ConfigurableBillingStatus
+ continues to summarize the direction of the most recent
+ update across all surfaces in the project (QPM,
+ IndexingCore, and Agent Search TPM together).
+ """
+
+ model_version: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ effective_tpm_threshold: int = proto.Field(
+ proto.INT64,
+ number=2,
+ )
+ tpm_threshold_next_update_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message=timestamp_pb2.Timestamp,
+ )
+ start_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=timestamp_pb2.Timestamp,
+ )
+ terminate_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ message=timestamp_pb2.Timestamp,
+ )
+ update_type: "Project.ConfigurableBillingStatus.UpdateType" = proto.Field(
+ proto.ENUM,
+ number=6,
+ enum="Project.ConfigurableBillingStatus.UpdateType",
+ )
+
+ effective_search_qpm_threshold: int = proto.Field(
+ proto.INT64,
+ number=1,
+ )
+ effective_indexing_core_threshold: int = proto.Field(
+ proto.INT64,
+ number=2,
+ )
+ start_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message=timestamp_pb2.Timestamp,
+ )
+ terminate_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=timestamp_pb2.Timestamp,
+ )
+ search_qpm_threshold_next_update_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ message=timestamp_pb2.Timestamp,
+ )
+ indexing_core_threshold_next_update_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=6,
+ message=timestamp_pb2.Timestamp,
+ )
+ update_type: "Project.ConfigurableBillingStatus.UpdateType" = proto.Field(
+ proto.ENUM,
+ number=7,
+ enum="Project.ConfigurableBillingStatus.UpdateType",
+ )
+ agent_search_token_subscription_statuses: MutableSequence[
+ "Project.ConfigurableBillingStatus.AgentSearchTokenSubscriptionStatus"
+ ] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=8,
+ message="Project.ConfigurableBillingStatus.AgentSearchTokenSubscriptionStatus",
+ )
+
name: str = proto.Field(
proto.STRING,
number=1,
@@ -148,6 +513,16 @@ class State(proto.Enum):
number=4,
message=ServiceTerms,
)
+ customer_provided_config: CustomerProvidedConfig = proto.Field(
+ proto.MESSAGE,
+ number=6,
+ message=CustomerProvidedConfig,
+ )
+ configurable_billing_status: ConfigurableBillingStatus = proto.Field(
+ proto.MESSAGE,
+ number=10,
+ message=ConfigurableBillingStatus,
+ )
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/project_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/project_service.py
index 383e4280470e..25b88631caec 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/project_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/project_service.py
@@ -49,8 +49,33 @@ class ProvisionProjectRequest(proto.Message):
Acceptable version is ``2022-11-23``, and this may change
over time.
+ saas_params (google.cloud.discoveryengine_v1.types.ProvisionProjectRequest.SaasParams):
+ Optional. Parameters for Agentspace.
"""
+ class SaasParams(proto.Message):
+ r"""Parameters for Agentspace.
+
+ Attributes:
+ accept_biz_qos (bool):
+ Optional. Set to ``true`` to specify that caller has read
+ and would like to give consent to the [Terms for Agent Space
+ quality of service].
+ is_biz (bool):
+ Optional. Indicates if the current request is
+ for Biz edition (= true) or not
+ (= false).
+ """
+
+ accept_biz_qos: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+ is_biz: bool = proto.Field(
+ proto.BOOL,
+ number=2,
+ )
+
name: str = proto.Field(
proto.STRING,
number=1,
@@ -63,6 +88,11 @@ class ProvisionProjectRequest(proto.Message):
proto.STRING,
number=3,
)
+ saas_params: SaasParams = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=SaasParams,
+ )
class ProvisionProjectMetadata(proto.Message):
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/purge_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/purge_config.py
index 317ab56a77c8..28e1e97131e3 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/purge_config.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/purge_config.py
@@ -434,7 +434,9 @@ class PurgeCompletionSuggestionsRequest(proto.Message):
class PurgeCompletionSuggestionsResponse(proto.Message):
r"""Response message for
[CompletionService.PurgeCompletionSuggestions][google.cloud.discoveryengine.v1.CompletionService.PurgeCompletionSuggestions]
- method.
+ method. If the long running operation is successfully done, then
+ this message is returned by the
+ google.longrunning.Operations.response field.
Attributes:
purge_succeeded (bool):
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/rank_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/rank_service.py
index d8f7c47d9ec6..dc9d1a2fa599 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/rank_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/rank_service.py
@@ -52,8 +52,8 @@ class RankingRecord(proto.Message):
score (float):
The score of this record based on the given
query and selected model. The score will be
- rounded to 2 decimal places. If the score is
- close to 0, it will be rounded to 0.0001 to
+ rounded to 4 decimal places. If the score is
+ close to 0, it will be rounded to 0.00001 to
avoid returning unset.
"""
@@ -100,8 +100,7 @@ class RankRequest(proto.Message):
query (str):
The query to use.
records (MutableSequence[google.cloud.discoveryengine_v1.types.RankingRecord]):
- Required. A list of records to rank. At most
- 200 records to rank.
+ Required. A list of records to rank.
ignore_record_details_in_response (bool):
If true, the response will contain only
record ID and score. By default, it is false,
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py
index 083f2b9cb232..20f9924bfa1b 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py
@@ -129,6 +129,13 @@ class SearchRequest(proto.Message):
the specs directly under
[SearchRequest][google.cloud.discoveryengine.v1.SearchRequest]
should be used.
+
+ On an engine with multiple data stores, this field is
+ optional. If it's empty, all of the engine's data stores are
+ searched (blended search). Unless it specifies exactly one
+ data store, some request fields, such as ``order_by`` and
+ ``query_expansion_spec``, aren't supported and return an
+ ``INVALID_ARGUMENT`` error.
num_results_per_data_store (int):
Optional. The maximum number of results to retrieve from
each data store. If not specified, it will use the
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/serving_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/serving_config.py
index 313fa1c3da05..d68670327a5c 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/serving_config.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/serving_config.py
@@ -26,6 +26,7 @@
package="google.cloud.discoveryengine.v1",
manifest={
"ServingConfig",
+ "AnswerGenerationSpec",
},
)
@@ -202,6 +203,9 @@ class ServingConfig(proto.Message):
Condition promote specifications.
Maximum number of specifications is 100.
+ answer_generation_spec (google.cloud.discoveryengine_v1.types.AnswerGenerationSpec):
+ Optional. The specification for answer
+ generation.
"""
class MediaConfig(proto.Message):
@@ -392,6 +396,90 @@ class GenericConfig(proto.Message):
proto.STRING,
number=26,
)
+ answer_generation_spec: "AnswerGenerationSpec" = proto.Field(
+ proto.MESSAGE,
+ number=27,
+ message="AnswerGenerationSpec",
+ )
+
+
+class AnswerGenerationSpec(proto.Message):
+ r"""The specification for answer generation.
+
+ Attributes:
+ user_defined_classifier_spec (google.cloud.discoveryengine_v1.types.AnswerGenerationSpec.UserDefinedClassifierSpec):
+ Optional. The specification for user
+ specified classifier spec.
+ """
+
+ class UserDefinedClassifierSpec(proto.Message):
+ r"""The specification for user defined classifier.
+
+ Attributes:
+ enable_user_defined_classifier (bool):
+ Optional. Whether or not to enable and
+ include user defined classifier.
+ preamble (str):
+ Optional. The preamble to be used for the
+ user defined classifier.
+ model_id (str):
+ Optional. The model id to be used for the
+ user defined classifier.
+ task_marker (str):
+ Optional. The task marker to be used for the
+ user defined classifier.
+ top_p (float):
+ Optional. The top-p value to be used for the
+ user defined classifier.
+ top_k (int):
+ Optional. The top-k value to be used for the
+ user defined classifier.
+ temperature (float):
+ Optional. The temperature value to be used
+ for the user defined classifier.
+ seed (int):
+ Optional. The seed value to be used for the
+ user defined classifier.
+ """
+
+ enable_user_defined_classifier: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+ preamble: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ model_id: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ task_marker: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ top_p: float = proto.Field(
+ proto.DOUBLE,
+ number=5,
+ )
+ top_k: int = proto.Field(
+ proto.INT64,
+ number=6,
+ )
+ temperature: float = proto.Field(
+ proto.DOUBLE,
+ number=7,
+ )
+ seed: int = proto.Field(
+ proto.INT32,
+ number=8,
+ )
+
+ user_defined_classifier_spec: UserDefinedClassifierSpec = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=UserDefinedClassifierSpec,
+ )
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/serving_config_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/serving_config_service.py
index c14b94f2a164..6567da434498 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/serving_config_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/serving_config_service.py
@@ -25,11 +25,49 @@
__protobuf__ = proto.module(
package="google.cloud.discoveryengine.v1",
manifest={
+ "CreateServingConfigRequest",
"UpdateServingConfigRequest",
+ "DeleteServingConfigRequest",
+ "GetServingConfigRequest",
+ "ListServingConfigsRequest",
+ "ListServingConfigsResponse",
},
)
+class CreateServingConfigRequest(proto.Message):
+ r"""Request for CreateServingConfig method.
+
+ Attributes:
+ parent (str):
+ Required. Full resource name of parent. Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}``
+ serving_config (google.cloud.discoveryengine_v1.types.ServingConfig):
+ Required. The ServingConfig to create.
+ serving_config_id (str):
+ Required. The ID to use for the ServingConfig, which will
+ become the final component of the ServingConfig's resource
+ name.
+
+ This value should be 4-63 characters, and valid characters
+ are /[a-zA-Z0-9][a-zA-Z0-9\_-]+/.
+ """
+
+ parent: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ serving_config: gcd_serving_config.ServingConfig = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=gcd_serving_config.ServingConfig,
+ )
+ serving_config_id: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+
class UpdateServingConfigRequest(proto.Message):
r"""Request for UpdateServingConfig method.
@@ -58,4 +96,96 @@ class UpdateServingConfigRequest(proto.Message):
)
+class DeleteServingConfigRequest(proto.Message):
+ r"""Request for DeleteServingConfig method.
+
+ Attributes:
+ name (str):
+ Required. The resource name of the ServingConfig to delete.
+ Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_id}``
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class GetServingConfigRequest(proto.Message):
+ r"""Request for GetServingConfig method.
+
+ Attributes:
+ name (str):
+ Required. The resource name of the ServingConfig to get.
+ Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}/servingConfigs/{serving_config_id}``
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class ListServingConfigsRequest(proto.Message):
+ r"""Request for ListServingConfigs method.
+
+ Attributes:
+ parent (str):
+ Required. Full resource name of the parent resource. Format:
+ ``projects/{project}/locations/{location}/collections/{collection}/engines/{engine}``
+ page_size (int):
+ Optional. Maximum number of results to
+ return. If unspecified, defaults to 100. If a
+ value greater than 100 is provided, at most 100
+ results are returned.
+ page_token (str):
+ Optional. A page token, received from a previous
+ ``ListServingConfigs`` call. Provide this to retrieve the
+ subsequent page.
+ """
+
+ parent: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ page_size: int = proto.Field(
+ proto.INT32,
+ number=2,
+ )
+ page_token: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+
+class ListServingConfigsResponse(proto.Message):
+ r"""Response for ListServingConfigs method.
+
+ Attributes:
+ serving_configs (MutableSequence[google.cloud.discoveryengine_v1.types.ServingConfig]):
+ All the ServingConfigs for a given dataStore.
+ next_page_token (str):
+ Pagination token, if not returned indicates
+ the last page.
+ """
+
+ @property
+ def raw_page(self):
+ return self
+
+ serving_configs: MutableSequence[gcd_serving_config.ServingConfig] = (
+ proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_serving_config.ServingConfig,
+ )
+ )
+ next_page_token: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/session.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/session.py
index fbe55635028c..491ba88d398e 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/session.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/session.py
@@ -62,6 +62,11 @@ class Session(proto.Message):
Optional. Whether the session is pinned,
pinned session will be displayed on the top of
the session list.
+ pending_async_assist_operation_id (str):
+ Output only. Full resource name of an in-progress
+ AsyncAssist operation for this session, e.g.
+ ``projects/*/locations/*/collections/*/engines/*/sessions/*/operations/*``.
+ Set when the operation starts and cleared when it finishes.
"""
class State(proto.Enum):
@@ -111,6 +116,9 @@ class Turn(proto.Message):
used, model parameters (temperature, grounding
parameters, etc.). The prefix "google." is
reserved for Google-developed functionality.
+ live (bool):
+ Optional. Indicates whether this turn is a
+ live turn.
"""
query: "Query" = proto.Field(
@@ -137,6 +145,10 @@ class Turn(proto.Message):
proto.STRING,
number=16,
)
+ live: bool = proto.Field(
+ proto.BOOL,
+ number=20,
+ )
name: str = proto.Field(
proto.STRING,
@@ -178,6 +190,10 @@ class Turn(proto.Message):
proto.BOOL,
number=8,
)
+ pending_async_assist_operation_id: str = proto.Field(
+ proto.STRING,
+ number=22,
+ )
class Query(proto.Message):
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_event.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_event.py
index 88fe2cea3f9e..b772781c5f36 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_event.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_event.py
@@ -22,6 +22,7 @@
import proto # type: ignore
from google.cloud.discoveryengine_v1.types import common
+from google.cloud.discoveryengine_v1.types import feedback as gcd_feedback
__protobuf__ = proto.module(
package="google.cloud.discoveryengine.v1",
@@ -56,7 +57,6 @@ class UserEvent(proto.Message):
- ``view-home-page``: View of the home page.
- ``view-category-page``: View of a category page, e.g. Home
> Men > Jeans
- - ``add-feedback``: Add a user feedback.
Retail-related values:
@@ -193,9 +193,9 @@ class UserEvent(proto.Message):
[RecommendResponse.attribution_token][google.cloud.discoveryengine.v1.RecommendResponse.attribution_token]
to this field.
filter (str):
- The filter syntax consists of an expression language for
- constructing a predicate from one or more fields of the
- documents being filtered.
+ Optional. The filter syntax consists of an expression
+ language for constructing a predicate from one or more
+ fields of the documents being filtered.
One example is for ``search`` events, the associated
[SearchRequest][google.cloud.discoveryengine.v1.SearchRequest]
@@ -262,10 +262,10 @@ class UserEvent(proto.Message):
associated with promotions. Currently, this
field is restricted to at most one ID.
attributes (MutableMapping[str, google.cloud.discoveryengine_v1.types.CustomAttribute]):
- Extra user event features to include in the recommendation
- model. These attributes must NOT contain data that needs to
- be parsed or processed further, e.g. JSON or other
- encodings.
+ Optional. Extra user event features to include in the
+ recommendation model. These attributes must NOT contain data
+ that needs to be parsed or processed further, e.g. JSON or
+ other encodings.
If you provide custom attributes for ingested user events,
also include them in the user events that you associate with
@@ -295,6 +295,16 @@ class UserEvent(proto.Message):
panels (MutableSequence[google.cloud.discoveryengine_v1.types.PanelInfo]):
Optional. List of panels associated with this
event. Used for page-level impression data.
+ feedback (google.cloud.discoveryengine_v1.types.Feedback):
+ Optional. This field is optional except for the
+ ``add-feedback`` event types.
+ entity (str):
+ Optional. Represents the entity for customers that may run
+ multiple different entities, domains, sites or regions, for
+ example, ``Google US``, ``Google Ads``, ``Waymo``,
+ ``google.com``, ``youtube.com``, etc. We recommend that you
+ set ``entity`` to get better per-entity search, completion,
+ and prediction results.
"""
event_type: str = proto.Field(
@@ -397,6 +407,15 @@ class UserEvent(proto.Message):
number=22,
message="PanelInfo",
)
+ feedback: gcd_feedback.Feedback = proto.Field(
+ proto.MESSAGE,
+ number=23,
+ message=gcd_feedback.Feedback,
+ )
+ entity: str = proto.Field(
+ proto.STRING,
+ number=25,
+ )
class PageInfo(proto.Message):
@@ -473,7 +492,7 @@ class SearchInfo(proto.Message):
Attributes:
search_query (str):
- The user's search query.
+ Optional. The user's search query.
See
[SearchRequest.query][google.cloud.discoveryengine.v1.SearchRequest.query]
@@ -544,7 +563,7 @@ class CompletionInfo(proto.Message):
Attributes:
selected_suggestion (str):
- End user selected
+ Optional. End user selected
[CompleteQueryResponse.QuerySuggestion.suggestion][google.cloud.discoveryengine.v1.CompleteQueryResponse.QuerySuggestion.suggestion].
selected_position (int):
End user selected
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_license.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_license.py
index a41ea3e238f7..6754d9369012 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_license.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_license.py
@@ -24,6 +24,7 @@
package="google.cloud.discoveryengine.v1",
manifest={
"UserLicense",
+ "LicenseConfigUsageStats",
},
)
@@ -45,8 +46,8 @@ class UserLicense(proto.Message):
license_assignment_state (google.cloud.discoveryengine_v1.types.UserLicense.LicenseAssignmentState):
Output only. License assignment state of the
user. If the user is assigned with a license
- config, the user loggin will be assigned with
- the license;
+ config, the user login will be assigned with the
+ license;
If the user's license assignment state is
unassigned or unspecified, no license config
will be associated to the user;
@@ -83,6 +84,8 @@ class LicenseAssignmentState(proto.Enum):
but cannot get license assigned. Users already logged in but
cannot get license assigned will be assigned NO_LICENSE
state(License could be unassigned by admin).
+ BLOCKED (5):
+ User is blocked from assigning a license.
"""
LICENSE_ASSIGNMENT_STATE_UNSPECIFIED = 0
@@ -90,6 +93,7 @@ class LicenseAssignmentState(proto.Enum):
UNASSIGNED = 2
NO_LICENSE = 3
NO_LICENSE_ATTEMPTED_LOGIN = 4
+ BLOCKED = 5
user_principal: str = proto.Field(
proto.STRING,
@@ -125,4 +129,24 @@ class LicenseAssignmentState(proto.Enum):
)
+class LicenseConfigUsageStats(proto.Message):
+ r"""Stats about users' licenses.
+
+ Attributes:
+ license_config (str):
+ Required. The LicenseConfig name.
+ used_license_count (int):
+ Required. The number of licenses used.
+ """
+
+ license_config: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ used_license_count: int = proto.Field(
+ proto.INT64,
+ number=2,
+ )
+
+
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_license_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_license_service.py
index 858075eb25b1..2e309460bdde 100644
--- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_license_service.py
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_license_service.py
@@ -29,6 +29,8 @@
manifest={
"ListUserLicensesRequest",
"ListUserLicensesResponse",
+ "ListLicenseConfigsUsageStatsRequest",
+ "ListLicenseConfigsUsageStatsResponse",
"BatchUpdateUserLicensesRequest",
"BatchUpdateUserLicensesMetadata",
"BatchUpdateUserLicensesResponse",
@@ -42,12 +44,14 @@ class ListUserLicensesRequest(proto.Message):
Attributes:
parent (str):
- Required. The parent [UserStore][] resource name, format:
+ Required. The parent
+ [UserStore][google.cloud.discoveryengine.v1.UserStore]
+ resource name, format:
``projects/{project}/locations/{location}/userStores/{user_store_id}``.
page_size (int):
Optional. Requested page size. Server may return fewer items
- than requested. If unspecified, defaults to 10. The maximum
- value is 50; values above 50 will be coerced to 50.
+ than requested. If unspecified, defaults to 100. The maximum
+ value is 1000; values above 1000 will be coerced to 1000.
If this field is negative, an INVALID_ARGUMENT error is
returned.
@@ -65,6 +69,8 @@ class ListUserLicensesRequest(proto.Message):
Supported fields:
- ``license_assignment_state``
+ - ``user_principal``
+ -
Examples:
@@ -77,6 +83,29 @@ class ListUserLicensesRequest(proto.Message):
- ``license_assignment_state != NO_LICENSE_ATTEMPTED_LOGIN``
to filter out users who attempted login but no license
assigned.
+ - ``user_principal = user1@example.com`` to list user
+ license for ``user1@example.com``.
+ order_by (str):
+ Optional. The order in which the
+ [UserLicense][google.cloud.discoveryengine.v1.UserLicense]s
+ are listed. The value must be a comma-separated list of
+ fields. Default sorting order is ascending. To specify
+ descending order for a field, append a " desc" suffix.
+ Redundant space characters in the syntax are insignificant.
+
+ Supported fields (only ``user_principal`` is supported for
+ now):
+
+ - ``user_principal``
+
+ If not set, the default ordering is by ``user_principal``.
+
+ Examples:
+
+ - ``user_principal`` to order by ``user_principal`` in
+ ascending order.
+ - ``user_principal desc`` to order by ``user_principal`` in
+ descending order.
"""
parent: str = proto.Field(
@@ -95,6 +124,10 @@ class ListUserLicensesRequest(proto.Message):
proto.STRING,
number=4,
)
+ order_by: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
class ListUserLicensesResponse(proto.Message):
@@ -126,6 +159,43 @@ def raw_page(self):
)
+class ListLicenseConfigsUsageStatsRequest(proto.Message):
+ r"""Request message for
+ [UserLicenseService.ListLicenseConfigsUsageStats][google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats]
+ method.
+
+ Attributes:
+ parent (str):
+ Required. The parent branch resource name, such as
+ ``projects/{project}/locations/{location}/userStores/{user_store_id}``.
+ """
+
+ parent: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class ListLicenseConfigsUsageStatsResponse(proto.Message):
+ r"""Response message for
+ [UserLicenseService.ListLicenseConfigsUsageStats][google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats]
+ method.
+
+ Attributes:
+ license_config_usage_stats (MutableSequence[google.cloud.discoveryengine_v1.types.LicenseConfigUsageStats]):
+ All the customer's
+ [LicenseConfigUsageStats][google.cloud.discoveryengine.v1.LicenseConfigUsageStats].
+ """
+
+ license_config_usage_stats: MutableSequence[
+ user_license.LicenseConfigUsageStats
+ ] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message=user_license.LicenseConfigUsageStats,
+ )
+
+
class BatchUpdateUserLicensesRequest(proto.Message):
r"""Request message for
[UserLicenseService.BatchUpdateUserLicenses][google.cloud.discoveryengine.v1.UserLicenseService.BatchUpdateUserLicenses]
@@ -137,11 +207,13 @@ class BatchUpdateUserLicensesRequest(proto.Message):
Attributes:
inline_source (google.cloud.discoveryengine_v1.types.BatchUpdateUserLicensesRequest.InlineSource):
The inline source for the input content for
- document embeddings.
+ license assignment.
This field is a member of `oneof`_ ``source``.
parent (str):
- Required. The parent [UserStore][] resource name, format:
+ Required. The parent
+ [UserStore][google.cloud.discoveryengine.v1.UserStore]
+ resource name, format:
``projects/{project}/locations/{location}/userStores/{user_store_id}``.
delete_unassigned_user_licenses (bool):
Optional. If true, if user licenses removed
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_store.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_store.py
new file mode 100644
index 000000000000..815c34c41a24
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_store.py
@@ -0,0 +1,94 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.discoveryengine.v1",
+ manifest={
+ "UserStore",
+ },
+)
+
+
+class UserStore(proto.Message):
+ r"""Configures metadata that is used for End User entities.
+
+ Attributes:
+ name (str):
+ Immutable. The full resource name of the User Store, in the
+ format of
+ ``projects/{project}/locations/{location}/userStores/{user_store}``.
+
+ This field must be a UTF-8 encoded string with a length
+ limit of 1024 characters.
+ display_name (str):
+ The display name of the User Store.
+ default_license_config (str):
+ Optional. The default subscription
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ for the UserStore, if
+ [UserStore.enable_license_auto_register][google.cloud.discoveryengine.v1.UserStore.enable_license_auto_register]
+ is true, new users will automatically register under the
+ default subscription.
+
+ If default
+ [LicenseConfig][google.cloud.discoveryengine.v1.LicenseConfig]
+ doesn't have remaining license seats left, new users will
+ not be assigned with license and will be blocked for Vertex
+ AI Search features. This is used if
+ ``license_assignment_tier_rules`` is not configured.
+ enable_license_auto_register (bool):
+ Optional. Whether to enable license auto
+ register for users in this User Store. If true,
+ new users will automatically register under the
+ default license config as long as the default
+ license config has seats left.
+ enable_expired_license_auto_update (bool):
+ Optional. Whether to enable license auto
+ update for users in this User Store. If true,
+ users with expired licenses will automatically
+ be updated to use the default license config as
+ long as the default license config has seats
+ left.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ default_license_config: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+ enable_license_auto_register: bool = proto.Field(
+ proto.BOOL,
+ number=6,
+ )
+ enable_expired_license_auto_update: bool = proto.Field(
+ proto.BOOL,
+ number=7,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_store_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_store_service.py
new file mode 100644
index 000000000000..fff157eea28d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/user_store_service.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 proto # type: ignore
+
+from google.cloud.discoveryengine_v1.types import user_store as gcd_user_store
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "GetUserStoreRequest",
+ "UpdateUserStoreRequest",
+ },
+)
+
+
+class GetUserStoreRequest(proto.Message):
+ r"""Request message for
+ [UserStoreService.GetUserStore][google.cloud.discoveryengine.v1.UserStoreService.GetUserStore]
+
+ Attributes:
+ name (str):
+ Required. The name of the User Store to get. Format:
+ ``projects/{project}/locations/{location}/userStores/{user_store_id}``
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+
+
+class UpdateUserStoreRequest(proto.Message):
+ r"""Request message for
+ [UserStoreService.UpdateUserStore][google.cloud.discoveryengine.v1.UserStoreService.UpdateUserStore]
+ method.
+
+ Attributes:
+ user_store (google.cloud.discoveryengine_v1.types.UserStore):
+ Required. The User Store to update. Format:
+ ``projects/{project}/locations/{location}/userStores/{user_store_id}``
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
+ Optional. The list of fields to update.
+ """
+
+ user_store: gcd_user_store.UserStore = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_user_store.UserStore,
+ )
+ update_mask: field_mask_pb2.FieldMask = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=field_mask_pb2.FieldMask,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/widget_config.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/widget_config.py
new file mode 100644
index 000000000000..da775f025069
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/widget_config.py
@@ -0,0 +1,1739 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.struct_pb2 as struct_pb2 # type: ignore
+import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
+import proto # type: ignore
+
+from google.cloud.discoveryengine_v1.types import common, data_connector
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "ModelInfoView",
+ "WidgetConfig",
+ },
+)
+
+
+class ModelInfoView(proto.Enum):
+ r"""Selects which "view" of the model selector configuration the backend
+ computes for ``WidgetConfig.UiSettings.ModelConfigInfo``.
+
+ The end-user views (``END_USER_WEB``, ``END_USER_MOBILE``) return
+ the user-facing model selector for their respective surface; the
+ ``ADMIN`` view returns the set surfaced on the Cloud Console admin
+ "Feature Control" page, with
+ ``ModelConfigInfo.ResolvedModel.admin_view`` populated on each
+ entry.
+
+ Values:
+ MODEL_INFO_VIEW_UNSPECIFIED (0):
+ Not specified.
+ END_USER_WEB (1):
+ The end-user web model selector view.
+ ADMIN (2):
+ The Cloud Console admin "Feature Control" view that displays
+ model toggles. Returns admin-surfaced models with
+ ``ResolvedModel.admin_view`` populated.
+ END_USER_MOBILE (3):
+ The end-user model selector view for the
+ Gemini Enterprise mobile app. Returns only
+ mobile-surfaced models, with the mobile default
+ selected. Set explicitly by the mobile client.
+ """
+
+ MODEL_INFO_VIEW_UNSPECIFIED = 0
+ END_USER_WEB = 1
+ ADMIN = 2
+ END_USER_MOBILE = 3
+
+
+class WidgetConfig(proto.Message):
+ r"""WidgetConfig captures configs at the Widget level.
+
+ Attributes:
+ name (str):
+ Immutable. The full resource name of the widget config.
+ Format:
+ ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/widgetConfigs/{widget_config_id}``.
+
+ This field must be a UTF-8 encoded string with a length
+ limit of 1024 characters.
+ display_name (str):
+ Required. The human readable widget config display name.
+ Used in Discovery UI.
+
+ This field must be a UTF-8 encoded string with a length
+ limit of 128 characters. Otherwise, an INVALID_ARGUMENT
+ error is returned.
+ create_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. Timestamp the
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ was created.
+ update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. Timestamp the
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ was updated.
+ data_store_type (google.cloud.discoveryengine_v1.types.WidgetConfig.DataStoreType):
+ Output only. The type of the parent data
+ store.
+ config_id (str):
+ Output only. Unique obfuscated identifier of a
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig].
+ solution_type (google.cloud.discoveryengine_v1.types.SolutionType):
+ Required. Immutable. Specifies the solution
+ type that this WidgetConfig can be used for.
+ industry_vertical (google.cloud.discoveryengine_v1.types.IndustryVertical):
+ Output only. The industry vertical that the WidgetConfig
+ registers. The WidgetConfig industry vertical is based on
+ the associated
+ [Engine][google.cloud.discoveryengine.v1.Engine].
+ llm_enabled (bool):
+ Output only. Whether LLM is enabled in the
+ corresponding data store.
+ enable_result_score (bool):
+ Whether to show the result score.
+ minimum_data_term_accepted (bool):
+ Output only. Whether the customer accepted
+ data use terms.
+ collection_components (MutableSequence[google.cloud.discoveryengine_v1.types.WidgetConfig.CollectionComponent]):
+ Output only. Collection components that lists all
+ collections and child data stores associated with the widget
+ config, those data sources can be used for filtering in
+ widget service APIs, users can return results that from
+ selected data sources.
+
+ For SaaS / Business engines, when ``LookupWidgetConfig`` is
+ called with ``view = WITH_AVAILABLE_CONNECTORS``, this list
+ is additionally augmented with synthetic placeholder entries
+ for connectors the caller may attach but has not yet
+ attached (see ``CollectionComponent`` for the placeholder
+ contract). The frontend can therefore render a unified list
+ of already-attached and available-to-attach sources by
+ iterating this single field. For Enterprise engines and for
+ the default ``view``, only already-attached connectors are
+ returned (today's behavior).
+ ui_settings (google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings):
+ Describes general widget search settings as
+ seen in cloud console widget configuration page.
+ Replaces top deprecated top level properties.
+ access_settings (google.cloud.discoveryengine_v1.types.WidgetConfig.AccessSettings):
+ Will be used for all widget access settings
+ seen in cloud console integration page. Replaces
+ top deprecated top level properties.
+ ui_branding (google.cloud.discoveryengine_v1.types.WidgetConfig.UiBrandingSettings):
+ Describes search widget UI branding settings,
+ such as the widget title, logo, favicons, and
+ colors.
+ homepage_setting (google.cloud.discoveryengine_v1.types.WidgetConfig.HomepageSetting):
+ Optional. Describes the homepage settings of
+ the widget.
+ assistant_settings (google.cloud.discoveryengine_v1.types.WidgetConfig.AssistantSettings):
+ Optional. Output only. Describes the
+ assistant settings of the widget.
+ customer_provided_config (google.cloud.discoveryengine_v1.types.WidgetConfig.CustomerProvidedConfig):
+ Optional. Output only. Describes the customer
+ related configurations, currently only used for
+ government customers. This field cannot be
+ modified after project onboarding.
+ enable_private_knowledge_graph (bool):
+ Optional. Output only. Whether to enable
+ private knowledge graph.
+ gemini_bundle (bool):
+ Output only. Whether the subscription is
+ gemini bundle or not.
+ batch_auth_statuses (MutableSequence[google.cloud.discoveryengine_v1.types.WidgetConfig.BatchAuthStatus]):
+ Output only. The batch authorization statuses
+ for the widget's connectors.
+ nodes (MutableSequence[google.cloud.discoveryengine_v1.types.WidgetConfig.Node]):
+ Output only. The nodes associated with the
+ Widget Config.
+ """
+
+ class DataStoreType(proto.Enum):
+ r"""The type of the widget's parent data store.
+
+ Values:
+ DATA_STORE_TYPE_UNSPECIFIED (0):
+ Unspecified data store type.
+ SITE_SEARCH (1):
+ The parent data store contains a site search
+ engine.
+ STRUCTURED (2):
+ The parent data store contains a search
+ engine for structured data.
+ UNSTRUCTURED (3):
+ The parent data store contains a search
+ engine for unstructured data.
+ BLENDED (4):
+ The parent data store is served for blended
+ search with multiple data stores.
+ """
+
+ DATA_STORE_TYPE_UNSPECIFIED = 0
+ SITE_SEARCH = 1
+ STRUCTURED = 2
+ UNSTRUCTURED = 3
+ BLENDED = 4
+
+ class ResultDisplayType(proto.Enum):
+ r"""The type of result to display in the ucs widget.
+
+ Values:
+ RESULT_DISPLAY_TYPE_UNSPECIFIED (0):
+ Unspecified display type (default to showing
+ snippet).
+ SNIPPET (1):
+ Display results from the snippet field.
+ EXTRACTIVE_ANSWER (2):
+ Display results from extractive answers
+ field.
+ """
+
+ RESULT_DISPLAY_TYPE_UNSPECIFIED = 0
+ SNIPPET = 1
+ EXTRACTIVE_ANSWER = 2
+
+ class UIComponentField(proto.Message):
+ r"""Facet field that maps to a UI Component.
+
+ Attributes:
+ field (str):
+ Required. Registered field name. The format is
+ ``field.abc``.
+ device_visibility (MutableSequence[google.cloud.discoveryengine_v1.types.WidgetConfig.UIComponentField.DeviceVisibility]):
+ The field visibility on different types of
+ devices.
+ display_template (str):
+ The template to customize how the field is
+ displayed. An example value would be a string
+ that looks like: "Price: {value}".
+ """
+
+ class DeviceVisibility(proto.Enum):
+ r"""The visibility of the field on different type of devices.
+
+ Values:
+ DEVICE_VISIBILITY_UNSPECIFIED (0):
+ Default value when not specified. Server returns
+ INVALID_ARGUMENT if used in requests.
+ MOBILE (1):
+ The UI component is visible on Mobile
+ devices.
+ DESKTOP (2):
+ The UI component is visible on Browser-based
+ client.
+ """
+
+ DEVICE_VISIBILITY_UNSPECIFIED = 0
+ MOBILE = 1
+ DESKTOP = 2
+
+ field: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ device_visibility: MutableSequence[
+ "WidgetConfig.UIComponentField.DeviceVisibility"
+ ] = proto.RepeatedField(
+ proto.ENUM,
+ number=2,
+ enum="WidgetConfig.UIComponentField.DeviceVisibility",
+ )
+ display_template: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+ class FacetField(proto.Message):
+ r"""Facet fields that store the mapping of fields to end user
+ widget appearance.
+
+ Attributes:
+ field (str):
+ Required. Registered field name. The format is
+ ``field.abc``.
+ display_name (str):
+ Optional. The field name that end users will
+ see.
+ """
+
+ field: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+
+ class DataStoreUiConfig(proto.Message):
+ r"""UI component configuration for data store.
+
+ Attributes:
+ name (str):
+ The name of the data store. It should be data store resource
+ name Format:
+ ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``.
+ For APIs under
+ [WidgetService][google.cloud.discoveryengine.v1.WidgetService],
+ such as
+ [WidgetService.LookupWidgetConfig][google.cloud.discoveryengine.v1.WidgetService.LookupWidgetConfig],
+ the project number and location part is erased in this
+ field.
+ id (str):
+ Output only. the identifier of the data store, used for
+ widget service. For now it refers to data_store_id, in the
+ future we will migrate the field to encrypted data store
+ name UUID.
+ facet_field (MutableSequence[google.cloud.discoveryengine_v1.types.WidgetConfig.FacetField]):
+ Facet fields that store the mapping of fields
+ to end user widget appearance.
+ fields_ui_components_map (MutableMapping[str, google.cloud.discoveryengine_v1.types.WidgetConfig.UIComponentField]):
+ The key is the UI component. Mock. Currently supported
+ ``title``, ``thumbnail``, ``url``, ``custom1``, ``custom2``,
+ ``custom3``.
+
+ The value is the name of the field along with its device
+ visibility.
+
+ The 3 custom fields are optional and can be added or
+ removed. ``title``, ``thumbnail``, ``url`` are required UI
+ components that cannot be removed.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ id: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ facet_field: MutableSequence["WidgetConfig.FacetField"] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=3,
+ message="WidgetConfig.FacetField",
+ )
+ fields_ui_components_map: MutableMapping[
+ str, "WidgetConfig.UIComponentField"
+ ] = proto.MapField(
+ proto.STRING,
+ proto.MESSAGE,
+ number=4,
+ message="WidgetConfig.UIComponentField",
+ )
+
+ class DataStoreComponent(proto.Message):
+ r"""Read-only data store component that contains data stores fields that
+ may be used for filtering, it's the child of
+ ``CollectionComponent``.
+
+ Attributes:
+ name (str):
+ The name of the data store. It should be data store resource
+ name Format:
+ ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}``.
+ For APIs under
+ [WidgetService][google.cloud.discoveryengine.v1.WidgetService],
+ such as
+ [WidgetService.LookupWidgetConfig][google.cloud.discoveryengine.v1.WidgetService.LookupWidgetConfig],
+ the project number and location part is erased in this
+ field.
+ id (str):
+ Output only. the identifier of the data store, used for
+ widget service. For now it refers to data_store_id, in the
+ future we will migrate the field to encrypted data store
+ name UUID.
+ display_name (str):
+ The display name of the data store.
+ entity_name (str):
+ The name of the entity, retrieved from
+ ``Collection.data_connector.entities.entityName``.
+ data_store_config_type (google.cloud.discoveryengine_v1.types.WidgetConfig.DataStoreComponent.DataStoreConfigType):
+ Output only. The type of the data store
+ config.
+ """
+
+ class DataStoreConfigType(proto.Enum):
+ r"""The type of the data store config.
+
+ Values:
+ DATA_STORE_CONFIG_TYPE_UNSPECIFIED (0):
+ Default value. This value is unused.
+ ALLOW_DB_CONFIG (1):
+ The data store is connected to AlloyDB
+ THIRD_PARTY_OAUTH_CONFIG (2):
+ The data store is a connected to a third
+ party data source.
+ NOTEBOOKLM_CONFIG (3):
+ The data store is a connected to NotebookLM
+ Enterprise.
+ """
+
+ DATA_STORE_CONFIG_TYPE_UNSPECIFIED = 0
+ ALLOW_DB_CONFIG = 1
+ THIRD_PARTY_OAUTH_CONFIG = 2
+ NOTEBOOKLM_CONFIG = 3
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ id: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ entity_name: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ data_store_config_type: "WidgetConfig.DataStoreComponent.DataStoreConfigType" = proto.Field(
+ proto.ENUM,
+ number=8,
+ enum="WidgetConfig.DataStoreComponent.DataStoreConfigType",
+ )
+
+ class ConnectorAuthState(proto.Message):
+ r"""Read-only connector in CollectionComponent auth state.
+
+ Attributes:
+ auth_state (google.cloud.discoveryengine_v1.types.WidgetConfig.ConnectorAuthState.AuthState):
+ Output only. The authorization state of the
+ data connector.
+ authorization_uri (str):
+ Output only. The authorization uri for the data connector.
+
+ For synthetic placeholder ``CollectionComponent`` entries
+ (returned by ``LookupWidgetConfig`` with
+ ``view = WITH_AVAILABLE_CONNECTORS`` on SaaS / Business
+ engines), this field is left empty. The widget should call
+ ``WidgetService.WidgetBuildAuthorizationUrl`` on the user's
+ "Connect" click to obtain a freshly-built authorization URL.
+ update_time (google.protobuf.timestamp_pb2.Timestamp):
+ Output only. The authorization state update
+ timestamp.
+ """
+
+ class AuthState(proto.Enum):
+ r"""The authorization state of the data connector.
+
+ Values:
+ AUTH_STATE_UNSPECIFIED (0):
+ Default value. Also returned for synthetic placeholder
+ ``CollectionComponent`` entries surfaced by
+ ``LookupWidgetConfig`` with
+ ``view = WITH_AVAILABLE_CONNECTORS`` (SaaS / Business only)
+ — those entries represent connectors the caller may attach
+ but has not yet attached.
+ AUTHORIZED (1):
+ The user has authorized the data connector.
+ EXPIRED (2):
+ The user authorization for the data connector
+ has expired.
+ ACTIONS_DISABLED (3):
+ The user can still make search requests but
+ actions need to be enabled.
+ NO_AUTH (4):
+ The data connector does not require any
+ authorization. Also used for placeholder entries
+ whose underlying connector does not require user
+ OAuth.
+ """
+
+ AUTH_STATE_UNSPECIFIED = 0
+ AUTHORIZED = 1
+ EXPIRED = 2
+ ACTIONS_DISABLED = 3
+ NO_AUTH = 4
+
+ auth_state: "WidgetConfig.ConnectorAuthState.AuthState" = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum="WidgetConfig.ConnectorAuthState.AuthState",
+ )
+ authorization_uri: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ update_time: timestamp_pb2.Timestamp = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=timestamp_pb2.Timestamp,
+ )
+
+ class BatchAuthStatus(proto.Message):
+ r"""Describes the batch authorization status for a
+ batch_authorization_group.
+
+ Attributes:
+ placeholder (str):
+ Output only. It is the batch authorization group placeholder
+ full resource name. This is not a real data connector
+ resource. E.g.
+ projects/{project}/locations/{location}/collections/oauth_placeholder_google_workspace/dataStores/dataConnector.
+ batch_authorization_group (str):
+ Output only. The batch authorization group
+ the placeholder belongs to.
+ connector_auth_state (google.cloud.discoveryengine_v1.types.WidgetConfig.ConnectorAuthState):
+ Output only. The current authorization state
+ for this connector.
+ """
+
+ placeholder: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ batch_authorization_group: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ connector_auth_state: "WidgetConfig.ConnectorAuthState" = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message="WidgetConfig.ConnectorAuthState",
+ )
+
+ class CollectionComponent(proto.Message):
+ r"""Read-only collection component that contains data store collections
+ fields that may be used for filtering.
+
+ For SaaS / Business engines, when ``LookupWidgetConfig`` is called
+ with ``view = WITH_AVAILABLE_CONNECTORS``, instances of this message
+ are also used to represent synthetic placeholder entries for
+ connectors the caller may attach but has not yet attached.
+ Placeholder entries have
+ ``connector_auth_state.auth_state == AUTH_STATE_UNSPECIFIED`` (or
+ ``NO_AUTH``), an empty ``connector_auth_state.authorization_uri``
+ (the widget calls ``WidgetBuildAuthorizationUrl`` on the user's
+ "Connect" click), and synthetic placeholder values in ``name`` /
+ ``id`` (see field comments). Fields that only make sense for
+ materialized connectors (``data_store_components``, ``tenant``,
+ ``action_connector``) are left unset for placeholder entries.
+
+ Attributes:
+ name (str):
+ The name of the collection. It should be collection resource
+ name. Format:
+ ``projects/{project}/locations/{location}/collections/{collection_id}``.
+ For APIs under
+ [WidgetService][google.cloud.discoveryengine.v1.WidgetService],
+ such as
+ [WidgetService.LookupWidgetConfig][google.cloud.discoveryengine.v1.WidgetService.LookupWidgetConfig],
+ the project number and location part is erased in this
+ field.
+
+ For synthetic placeholder entries (see message-level
+ comment) this carries a synthetic placeholder collection id
+ that does not correspond to a real collection. Callers must
+ not attempt to resolve / GET this resource until the user
+ authorizes the connector.
+ id (str):
+ Output only. the identifier of the collection, used for
+ widget service. For now it refers to collection_id, in the
+ future we will migrate the field to encrypted collection
+ name UUID.
+
+ For synthetic placeholder entries (see message-level
+ comment) this is a synthetic placeholder id, not a real
+ collection_id.
+ display_name (str):
+ The display name of the collection.
+ data_store_components (MutableSequence[google.cloud.discoveryengine_v1.types.WidgetConfig.DataStoreComponent]):
+ For the data store collection, list of the
+ children data stores.
+ data_source (str):
+ The name of the data source, retrieved from
+ ``Collection.data_connector.data_source``.
+ data_source_version (float):
+ Output only. The version of the connector definition backing
+ this collection, mirroring
+ ``DataConnector.data_source_version``.
+ data_source_display_name (str):
+ Output only. The display name of the data
+ source.
+ data_source_end_user_display_name (str):
+ Output only. The end-user-facing display name of the data
+ source, sourced from
+ ``ConnectorSource.end_user_display_name``. When unset,
+ clients fall back to ``data_source_display_name``.
+ connector_icon_link (str):
+ Output only. The icon link of the connector
+ source.
+ connector_auth_state (google.cloud.discoveryengine_v1.types.WidgetConfig.ConnectorAuthState):
+ Output only. The auth uri of the connector
+ source.
+ metadata (google.cloud.discoveryengine_v1.types.DataConnector.ConnectorMetadata):
+ Output only. User-facing connector metadata (``title``,
+ ``description``, ``short_description``, ``author``,
+ ``note``), retrieved from the registry
+ ``ConnectorSource.metadata`` (joined by data source). Shown
+ on the connector detail page.
+ is_first_party (bool):
+ Output only. Whether this is a first-party
+ (Google-owned) connector, as opposed to a
+ third-party connector.
+ tag (str):
+ Output only. The version-independent label of the connector
+ backing this collection, mirroring ``DataConnector.tag``.
+ Unlike the version-pinned data store id it survives a
+ connector version upgrade, so an upgraded connector keeps
+ the same tag.
+
+ Not a unique key. As ``DataConnector.tag`` documents,
+ several connectors may share a tag under the same (project,
+ location, collection, data_source), and tag-based lookup
+ resolves to the one with the greatest create_time. Clients
+ must not treat this as a connector identifier.
+
+ Empty when the connector was created before the tag-write
+ launch, and for synthetic placeholder entries, which have no
+ underlying ``DataConnector``. Populated only when
+ ``ConnectorsFeature.enable_connector_tag`` is on.
+ """
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ id: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ data_store_components: MutableSequence["WidgetConfig.DataStoreComponent"] = (
+ proto.RepeatedField(
+ proto.MESSAGE,
+ number=4,
+ message="WidgetConfig.DataStoreComponent",
+ )
+ )
+ data_source: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+ data_source_version: float = proto.Field(
+ proto.DOUBLE,
+ number=16,
+ )
+ data_source_display_name: str = proto.Field(
+ proto.STRING,
+ number=9,
+ )
+ data_source_end_user_display_name: str = proto.Field(
+ proto.STRING,
+ number=15,
+ )
+ connector_icon_link: str = proto.Field(
+ proto.STRING,
+ number=6,
+ )
+ connector_auth_state: "WidgetConfig.ConnectorAuthState" = proto.Field(
+ proto.MESSAGE,
+ number=8,
+ message="WidgetConfig.ConnectorAuthState",
+ )
+ metadata: data_connector.DataConnector.ConnectorMetadata = proto.Field(
+ proto.MESSAGE,
+ number=13,
+ message=data_connector.DataConnector.ConnectorMetadata,
+ )
+ is_first_party: bool = proto.Field(
+ proto.BOOL,
+ number=14,
+ )
+ tag: str = proto.Field(
+ proto.STRING,
+ number=19,
+ )
+
+ class UiSettings(proto.Message):
+ r"""Describes general widget (or web app) UI settings as seen
+ in the cloud console UI configuration page.
+
+
+ .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
+
+ Attributes:
+ interaction_type (google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings.InteractionType):
+ Describes widget (or web app) interaction
+ type
+ generative_answer_config (google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings.GenerativeAnswerConfig):
+ Describes generative answer configuration.
+ result_description_type (google.cloud.discoveryengine_v1.types.WidgetConfig.ResultDisplayType):
+ Controls whether result extract is display
+ and how (snippet or extractive answer). Default
+ to no result if unspecified.
+ enable_autocomplete (bool):
+ Whether or not to enable autocomplete.
+ enable_safe_search (bool):
+ Whether to enable safe search.
+ enable_quality_feedback (bool):
+ Turn on or off collecting the search result
+ quality feedback from end users.
+ enable_search_as_you_type (bool):
+ Whether to enable search-as-you-type behavior
+ for the search widget.
+ default_search_request_order_by (str):
+ The default ordering for search results if specified.
+
+ Used to set SearchRequest#order_by on applicable requests.
+ https://cloud.google.com/generative-ai-app-builder/docs/reference/rest/v1alpha/projects.locations.dataStores.servingConfigs/search#request-body
+ data_store_ui_configs (MutableSequence[google.cloud.discoveryengine_v1.types.WidgetConfig.DataStoreUiConfig]):
+ Per data store configuration.
+ disable_user_events_collection (bool):
+ If set to true, the widget will not collect
+ user events.
+ enable_visual_content_summary (bool):
+ If set to true, the widget will enable visual
+ content summary on applicable search requests.
+ Only used by healthcare search.
+ enable_people_search (bool):
+ Optional. If set to true, the widget will
+ enable people search.
+ enable_create_agent_button (bool):
+ Optional. If set to true, the widget will
+ enable the create agent button.
+ features (MutableMapping[str, google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings.FeatureState]):
+ Output only. Feature config for the engine to opt in or opt
+ out of features. Supported keys:
+
+ - ``agent-gallery``
+ - ``no-code-agent-builder``
+ - ``prompt-gallery``
+ - ``model-selector``
+ - ``notebook-lm``
+ - ``people-search``
+ - ``people-search-org-chart``
+ - ``bi-directional-audio``
+ - ``speech-to-text``
+ - ``feedback``
+ - ``session-sharing``
+ - ``personalization-memory``
+ - ``personalization-suggested-highlights``
+ - ``mobile-app-access``
+ - ``disable-agent-sharing``
+ - ``disable-image-generation``
+ - ``disable-video-generation``
+ - ``disable-onedrive-upload``
+ - ``disable-talk-to-content``
+ - ``disable-google-drive-upload``
+ - ``disable-welcome-emails``
+ - ``disable-canvas``
+ - ``canvas-workspace``
+ - ``canvas-app-builder``
+ - ``skills``
+ - ``skill-sharing``
+ - ``skill-sharing-without-admin-approval``
+ - ``disable-projects``
+ - ``sobi``
+ - ``enable-end-user-sharing-with-groups``
+ - ``single-agent-orchestration``
+ - ``multi-agent-orchestration``
+ - ``cross-product-intelligence``
+ - ``workflow-agents``
+ - ``in-app-notifications``
+ - ``code-extraction``
+ - ``remote-vm``
+ - ``license-tier-badge``
+ model_configs (MutableMapping[str, google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings.ModelState]):
+ Output only. Maps a model name to its specific configuration
+ for this engine. This allows admin users to turn on/off
+ individual models. This only stores models whose states are
+ overridden by the admin.
+
+ When the state is unspecified, or model_configs is empty for
+ this model, the system will decide if this model should be
+ available or not based on the default configuration. For
+ example, a preview model should be disabled by default if
+ the admin has not chosen to enable it.
+ search_addon_spec (google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings.SearchAddonSpec):
+ Optional. SearchAddonSpec is used to disable
+ add-ons for search. This field is only supported
+ for search requests.
+ onedrive_picker_enabled (bool):
+ Output only. Whether the OneDrive file picker is available
+ to end-users. Computed by the backend from admin connector
+ enablement (Business edition) or attached OneDrive
+ connectors (Enterprise edition), combined with the existing
+ ``disable-onedrive-upload`` admin feature.
+
+ Declared ``optional`` so an explicitly-computed ``false`` is
+ serialized with field presence. A plain proto3 ``bool``
+ drops a default ``false`` on the wire, which prevented
+ clients from distinguishing "picker disabled" (``false``)
+ from "field not populated" (unset).
+
+ This field is a member of `oneof`_ ``_onedrive_picker_enabled``.
+ google_drive_picker_enabled (bool):
+ Output only. Whether the Google Drive file picker is
+ available to end-users. Declared ``optional`` for the same
+ field-presence reason as ``onedrive_picker_enabled`` above.
+
+ This field is a member of `oneof`_ ``_google_drive_picker_enabled``.
+ model_config_info (google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings.ModelConfigInfo):
+ Output only. The resolved, server-side view of model
+ selector configuration. Holds both the ordered list of
+ models that should appear in the model selector dropdown and
+ the model that should be selected by default.
+
+ Clients should render this directly without applying their
+ own filtering, ordering, or localization. The legacy
+ ``model_configs`` map above is retained for backward
+ compatibility with clients that have not yet migrated to
+ consuming this field.
+ source_admin_display_name_enabled (bool):
+ Optional. Whether to show the
+ admin-configured display name for data
+ connectors in the widget sources UI (instead of
+ the connector kind). Opt-in; defaults to false.
+ """
+
+ class InteractionType(proto.Enum):
+ r"""Describes interaction type.
+
+ Values:
+ INTERACTION_TYPE_UNSPECIFIED (0):
+ Not specified. Defaults to SEARCH_ONLY.
+ SEARCH_ONLY (1):
+ Search without a generative answer.
+ SEARCH_WITH_ANSWER (2):
+ Search with the generative answer.
+ SEARCH_WITH_FOLLOW_UPS (3):
+ Search with the generative answer that
+ supports follow up questions. Also known as
+ multi-turn search.
+ """
+
+ INTERACTION_TYPE_UNSPECIFIED = 0
+ SEARCH_ONLY = 1
+ SEARCH_WITH_ANSWER = 2
+ SEARCH_WITH_FOLLOW_UPS = 3
+
+ class FeatureState(proto.Enum):
+ r"""The state of the feature for the engine.
+
+ Values:
+ FEATURE_STATE_UNSPECIFIED (0):
+ The feature state is unspecified.
+ FEATURE_STATE_ON (1):
+ The feature is turned on to be accessible.
+ FEATURE_STATE_OFF (2):
+ The feature is turned off to be inaccessible.
+ """
+
+ FEATURE_STATE_UNSPECIFIED = 0
+ FEATURE_STATE_ON = 1
+ FEATURE_STATE_OFF = 2
+
+ class ModelState(proto.Enum):
+ r"""The state of the model for the engine.
+
+ Values:
+ MODEL_STATE_UNSPECIFIED (0):
+ The model state is unspecified.
+ MODEL_ENABLED (1):
+ The model is enabled by admin.
+ MODEL_DISABLED (2):
+ The model is disabled by admin.
+ """
+
+ MODEL_STATE_UNSPECIFIED = 0
+ MODEL_ENABLED = 1
+ MODEL_DISABLED = 2
+
+ class GenerativeAnswerConfig(proto.Message):
+ r"""Describes configuration for generative answer.
+
+ Attributes:
+ result_count (int):
+ The number of top results to generate the
+ answer from. Up to 10.
+ model_version (str):
+ The model version used to generate the
+ answer.
+ model_prompt_preamble (str):
+ Text at the beginning of the prompt that
+ instructs the model that generates the answer.
+ max_rephrase_steps (int):
+ Max rephrase steps.
+ The max number is 5 steps.
+ If not set or set to < 1, it will be set to 1 by
+ default.
+ language_code (str):
+ Language code for Summary. Use language tags defined by
+ `BCP47 `__.
+ Note: This is an experimental feature.
+ disable_related_questions (bool):
+ Whether generated answer contains suggested
+ related questions.
+ ignore_non_answer_seeking_query (bool):
+ Optional. Specifies whether to filter out queries that are
+ not answer-seeking. The default value is ``false``.
+
+ No answer is returned if the search query is classified as a
+ non-answer seeking query. If this field is set to ``true``,
+ we skip generating answers for non-answer seeking queries
+ and return fallback messages instead.
+ ignore_adversarial_query (bool):
+ Optional. Specifies whether to filter out
+ queries that are adversarial.
+ ignore_low_relevant_content (bool):
+ Optional. Specifies whether to filter out
+ queries that are not relevant to the content.
+ image_source (google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings.GenerativeAnswerConfig.ImageSource):
+ Optional. Source of image returned in the
+ answer.
+ """
+
+ class ImageSource(proto.Enum):
+ r"""Source of image returned in the answer.
+
+ Values:
+ IMAGE_SOURCE_UNSPECIFIED (0):
+ Unspecified image source (multimodal feature
+ is disabled by default)
+ ALL_AVAILABLE_SOURCES (1):
+ Behavior when service determines the pick
+ from all available sources.
+ CORPUS_IMAGE_ONLY (2):
+ Include image from corpus in the answer.
+ FIGURE_GENERATION_ONLY (3):
+ Triggers figure generation in the answer.
+ """
+
+ IMAGE_SOURCE_UNSPECIFIED = 0
+ ALL_AVAILABLE_SOURCES = 1
+ CORPUS_IMAGE_ONLY = 2
+ FIGURE_GENERATION_ONLY = 3
+
+ result_count: int = proto.Field(
+ proto.INT32,
+ number=3,
+ )
+ model_version: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ model_prompt_preamble: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+ max_rephrase_steps: int = proto.Field(
+ proto.INT32,
+ number=6,
+ )
+ language_code: str = proto.Field(
+ proto.STRING,
+ number=7,
+ )
+ disable_related_questions: bool = proto.Field(
+ proto.BOOL,
+ number=8,
+ )
+ ignore_non_answer_seeking_query: bool = proto.Field(
+ proto.BOOL,
+ number=9,
+ )
+ ignore_adversarial_query: bool = proto.Field(
+ proto.BOOL,
+ number=10,
+ )
+ ignore_low_relevant_content: bool = proto.Field(
+ proto.BOOL,
+ number=11,
+ )
+ image_source: "WidgetConfig.UiSettings.GenerativeAnswerConfig.ImageSource" = proto.Field(
+ proto.ENUM,
+ number=12,
+ enum="WidgetConfig.UiSettings.GenerativeAnswerConfig.ImageSource",
+ )
+
+ class ModelConfigInfo(proto.Message):
+ r"""The resolved, server-side view of model selector configuration for
+ the end-user. The backend computes this per-request by applying, in
+ order: Mendel flag evaluation, regional availability rules based on
+ the engine's location, and admin-panel overrides from
+ ``model_configs``.
+
+ The backend is the single source of truth for this configuration;
+ clients should render ``resolved_models`` directly in the model
+ selector dropdown, in the order provided, without applying their own
+ filtering, ordering, or localization.
+
+ Attributes:
+ resolved_models (MutableSequence[google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings.ModelConfigInfo.ResolvedModel]):
+ Output only. The list of models that are
+ available to the end-user in the model selector,
+ in the order in which they should be displayed.
+ default_model_id (str):
+ Output only. The ``model_id`` of the model that should be
+ selected by default in the model selector when the end-user
+ has not made an explicit choice. The value is always one of
+ the ``model_id``\ s present in ``resolved_models``.
+ auto_model_id (str):
+ Output only. The ``model_id`` a client must send when the
+ end-user picks the "Auto" entry (the empty ``model_id``).
+
+ Populated only for surfaces known to have no true "Auto"
+ mode, where leaving the model unset would fall back to a
+ platform default rather than a backend-chosen model. Empty
+ on every other surface, where "Auto" is resolved
+ server-side, and when none of the surface's ranked models is
+ available. When set, it is always one of the non-empty
+ ``model_id``\ s present in ``resolved_models``.
+ """
+
+ class ResolvedModel(proto.Message):
+ r"""A single model that is resolved to be available to the
+ end-user in the model selector, with all of its localized
+ display metadata.
+
+ Attributes:
+ model_id (str):
+ Output only. Unique identifier of the model (e.g.
+ ``gemini-2.5-flash``, ``gemini-3.1-pro-preview``).
+
+ This is the same identifier that clients pass back to the
+ assistant service to select this model. Virtual / "pseudo"
+ models (e.g. ``gemini-fast``) are also valid values here;
+ they are resolved to the underlying concrete model on the
+ backend.
+ display_name (str):
+ Output only. Localized display name of the model (e.g.
+ ``Gemini 3.1 Pro``). Localized server-side based on the
+ [LookupWidgetConfigRequest.language_code][google.cloud.discoveryengine.v1.LookupWidgetConfigRequest.language_code]
+ and
+ [LookupWidgetConfigRequest.region_code][google.cloud.discoveryengine.v1.LookupWidgetConfigRequest.region_code]
+ of the request.
+ icon (str):
+ Output only. GM3-compatible icon token associated with the
+ model (e.g. ``rocket_launch``, ``bolt``, ``graph_5``).
+ description (str):
+ Output only. Localized description text (e.g.
+ ``State-of-the-art reasoning``). Localized using the same
+ locale as ``display_name``.
+ is_preview (bool):
+ Output only. Whether the model is currently
+ in preview. Clients should surface this via a
+ "Preview" badge in the selector UI.
+ label (str):
+ Output only. Short label shown in the compact selector bar
+ chip (e.g. ``3.x Flash``) as opposed to the full
+ ``display_name`` (``Gemini 3.x Flash``). Falls back to
+ ``display_name`` when the backend registry does not specify
+ a distinct short label.
+ admin_view (google.cloud.discoveryengine_v1.types.WidgetConfig.UiSettings.ModelConfigInfo.ResolvedModel.AdminView):
+ Output only. Admin-surface metadata; populated only for the
+ Console admin Feature Control page (see ``AdminView``).
+ Unset for end-user surfaces.
+ promoted (bool):
+ Output only. Whether this model should be
+ promoted in the GE chat homepage banner.
+ icon_url (str):
+ Output only. Absolute URL of a brand mark to render instead
+ of ``icon``, for models whose vendor logo is not a GM3
+ glyph.
+
+ ``icon`` stays populated as the fallback, so a client that
+ does not render images, or that fails to fetch this one,
+ shows the glyph instead of nothing.
+ family (str):
+ Output only. Groups models that render
+ together in the selector. Models sharing a value
+ form one group; empty means the model belongs to
+ no group.
+
+ Compared for equality only -- never parsed, and
+ never shown to a user, so it is not localized.
+ """
+
+ class AdminView(proto.Message):
+ r"""Admin-surface metadata. Populated only when the request
+ originates from the Cloud Console admin "Feature Control" page;
+ left unset for end-user surfaces (Web, Mobile). Lets the admin
+ page render its toggle table directly from the backend instead
+ of a hardcoded client-side registry.
+
+ Attributes:
+ admin_overridable (bool):
+ Output only. Whether the admin can toggle this model's
+ enabled/disabled state via ``UiSettings.model_configs``.
+ Derived from ``MODEL_TAG_ADMIN_OVERRIDABLE``. When false,
+ the model is "forced" and its state is governed by
+ ``enabled_by_default``.
+ enabled_by_default (bool):
+ Output only. Whether the model is enabled when the admin has
+ set no explicit override in ``UiSettings.model_configs``.
+ Derived from ``MODEL_TAG_ENABLED_BY_DEFAULT``.
+ regions (MutableSequence[str]):
+ Output only. Regions where this model is
+ launched.
+ """
+
+ admin_overridable: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+ enabled_by_default: bool = proto.Field(
+ proto.BOOL,
+ number=2,
+ )
+ regions: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=3,
+ )
+
+ model_id: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ icon: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ description: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ is_preview: bool = proto.Field(
+ proto.BOOL,
+ number=5,
+ )
+ label: str = proto.Field(
+ proto.STRING,
+ number=7,
+ )
+ admin_view: "WidgetConfig.UiSettings.ModelConfigInfo.ResolvedModel.AdminView" = proto.Field(
+ proto.MESSAGE,
+ number=6,
+ message="WidgetConfig.UiSettings.ModelConfigInfo.ResolvedModel.AdminView",
+ )
+ promoted: bool = proto.Field(
+ proto.BOOL,
+ number=8,
+ )
+ icon_url: str = proto.Field(
+ proto.STRING,
+ number=9,
+ )
+ family: str = proto.Field(
+ proto.STRING,
+ number=10,
+ )
+
+ resolved_models: MutableSequence[
+ "WidgetConfig.UiSettings.ModelConfigInfo.ResolvedModel"
+ ] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message="WidgetConfig.UiSettings.ModelConfigInfo.ResolvedModel",
+ )
+ default_model_id: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ auto_model_id: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+ class SearchAddonSpec(proto.Message):
+ r"""SearchAddonSpec is used to disable add-ons for search. By
+ default, if this field is not specified, add-ons are enabled
+ wherever applicable.
+
+ Attributes:
+ semantic_add_on_disabled (bool):
+ Optional. If true, semantic add-on is
+ disabled. Semantic add-on includes embeddings
+ and jetstream.
+ kpi_personalization_add_on_disabled (bool):
+ Optional. If true, disables event re-ranking
+ and personalization to optimize KPIs &
+ personalize results.
+ generative_answer_add_on_disabled (bool):
+ Optional. If true, generative answer add-on
+ is disabled. Generative answer add-on includes
+ natural language to filters and simple answers.
+ """
+
+ semantic_add_on_disabled: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+ kpi_personalization_add_on_disabled: bool = proto.Field(
+ proto.BOOL,
+ number=2,
+ )
+ generative_answer_add_on_disabled: bool = proto.Field(
+ proto.BOOL,
+ number=3,
+ )
+
+ interaction_type: "WidgetConfig.UiSettings.InteractionType" = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum="WidgetConfig.UiSettings.InteractionType",
+ )
+ generative_answer_config: "WidgetConfig.UiSettings.GenerativeAnswerConfig" = (
+ proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message="WidgetConfig.UiSettings.GenerativeAnswerConfig",
+ )
+ )
+ result_description_type: "WidgetConfig.ResultDisplayType" = proto.Field(
+ proto.ENUM,
+ number=3,
+ enum="WidgetConfig.ResultDisplayType",
+ )
+ enable_autocomplete: bool = proto.Field(
+ proto.BOOL,
+ number=4,
+ )
+ enable_safe_search: bool = proto.Field(
+ proto.BOOL,
+ number=5,
+ )
+ enable_quality_feedback: bool = proto.Field(
+ proto.BOOL,
+ number=6,
+ )
+ enable_search_as_you_type: bool = proto.Field(
+ proto.BOOL,
+ number=7,
+ )
+ default_search_request_order_by: str = proto.Field(
+ proto.STRING,
+ number=8,
+ )
+ data_store_ui_configs: MutableSequence["WidgetConfig.DataStoreUiConfig"] = (
+ proto.RepeatedField(
+ proto.MESSAGE,
+ number=9,
+ message="WidgetConfig.DataStoreUiConfig",
+ )
+ )
+ disable_user_events_collection: bool = proto.Field(
+ proto.BOOL,
+ number=10,
+ )
+ enable_visual_content_summary: bool = proto.Field(
+ proto.BOOL,
+ number=11,
+ )
+ enable_people_search: bool = proto.Field(
+ proto.BOOL,
+ number=12,
+ )
+ enable_create_agent_button: bool = proto.Field(
+ proto.BOOL,
+ number=13,
+ )
+ features: MutableMapping[str, "WidgetConfig.UiSettings.FeatureState"] = (
+ proto.MapField(
+ proto.STRING,
+ proto.ENUM,
+ number=30,
+ enum="WidgetConfig.UiSettings.FeatureState",
+ )
+ )
+ model_configs: MutableMapping[str, "WidgetConfig.UiSettings.ModelState"] = (
+ proto.MapField(
+ proto.STRING,
+ proto.ENUM,
+ number=45,
+ enum="WidgetConfig.UiSettings.ModelState",
+ )
+ )
+ search_addon_spec: "WidgetConfig.UiSettings.SearchAddonSpec" = proto.Field(
+ proto.MESSAGE,
+ number=31,
+ message="WidgetConfig.UiSettings.SearchAddonSpec",
+ )
+ onedrive_picker_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=48,
+ optional=True,
+ )
+ google_drive_picker_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=49,
+ optional=True,
+ )
+ model_config_info: "WidgetConfig.UiSettings.ModelConfigInfo" = proto.Field(
+ proto.MESSAGE,
+ number=50,
+ message="WidgetConfig.UiSettings.ModelConfigInfo",
+ )
+ source_admin_display_name_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=51,
+ )
+
+ class AccessSettings(proto.Message):
+ r"""Describes widget access settings.
+
+ Attributes:
+ allow_public_access (bool):
+ Whether public unauthenticated access is
+ allowed.
+ allowlisted_domains (MutableSequence[str]):
+ List of domains that are allowed to integrate
+ the search widget.
+ enable_web_app (bool):
+ Whether web app access is enabled.
+ workforce_identity_pool_provider (str):
+ Optional. The workforce identity pool
+ provider used to access the widget.
+ language_code (str):
+ Optional. Language code for user interface. Use language
+ tags defined by
+ `BCP47 `__. If
+ unset, the default language code is "en-US".
+ """
+
+ allow_public_access: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+ allowlisted_domains: MutableSequence[str] = proto.RepeatedField(
+ proto.STRING,
+ number=2,
+ )
+ enable_web_app: bool = proto.Field(
+ proto.BOOL,
+ number=3,
+ )
+ workforce_identity_pool_provider: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ language_code: str = proto.Field(
+ proto.STRING,
+ number=5,
+ )
+
+ class Image(proto.Message):
+ r"""Options to store an image.
+
+ .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
+
+ Attributes:
+ url (str):
+ Image URL.
+
+ This field is a member of `oneof`_ ``storage_method``.
+ """
+
+ url: str = proto.Field(
+ proto.STRING,
+ number=1,
+ oneof="storage_method",
+ )
+
+ class UiBrandingSettings(proto.Message):
+ r"""Describes widget UI branding settings.
+
+ Attributes:
+ logo (google.cloud.discoveryengine_v1.types.WidgetConfig.Image):
+ Logo image.
+ """
+
+ logo: "WidgetConfig.Image" = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message="WidgetConfig.Image",
+ )
+
+ class HomepageSetting(proto.Message):
+ r"""Describes the homepage setting of the widget. It includes all
+ homepage related settings and configurations, such as shortcuts.
+
+ Attributes:
+ shortcuts (MutableSequence[google.cloud.discoveryengine_v1.types.WidgetConfig.HomepageSetting.Shortcut]):
+ Optional. The shortcuts to display on the
+ homepage.
+ """
+
+ class Shortcut(proto.Message):
+ r"""Describes an entity of shortcut (aka pinned content) on the
+ homepage. The home page will render these shortcuts in the same
+ order as what the API returns. If a customer wants to reorder or
+ remove a shortcut, the UI should always provide the new full
+ list of shortcuts.
+
+ Attributes:
+ title (str):
+ Optional. Title of the shortcut.
+ icon (google.cloud.discoveryengine_v1.types.WidgetConfig.Image):
+ Optional. Icon URL of shortcut.
+ destination_uri (str):
+ Optional. Destination URL of shortcut.
+ """
+
+ title: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ icon: "WidgetConfig.Image" = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message="WidgetConfig.Image",
+ )
+ destination_uri: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+ shortcuts: MutableSequence["WidgetConfig.HomepageSetting.Shortcut"] = (
+ proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message="WidgetConfig.HomepageSetting.Shortcut",
+ )
+ )
+
+ class AssistantSettings(proto.Message):
+ r"""Describes the assistant settings of the widget.
+
+ Attributes:
+ web_grounding_type (google.cloud.discoveryengine_v1.types.WidgetConfig.AssistantSettings.WebGroundingType):
+ Optional. The type of web grounding to use.
+ default_web_grounding_toggle_off (bool):
+ Output only. This field controls the default web grounding
+ toggle for end users if ``web_grounding_type`` is set to
+ ``WEB_GROUNDING_TYPE_GOOGLE_SEARCH`` or
+ ``WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH``. By default,
+ this field is set to false. If ``web_grounding_type`` is
+ ``WEB_GROUNDING_TYPE_GOOGLE_SEARCH`` or
+ ``WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH``, end users will
+ have web grounding enabled by default on UI. If true,
+ grounding toggle will be disabled by default on UI. End
+ users can still enable web grounding in the UI if web
+ grounding is enabled.
+ disable_location_context (bool):
+ Optional. Output only. Whether to disable
+ user location context.
+ """
+
+ class WebGroundingType(proto.Enum):
+ r"""The type of web grounding to use.
+
+ Values:
+ WEB_GROUNDING_TYPE_UNSPECIFIED (0):
+ Default, unspecified setting. This is the
+ same as disabled.
+ WEB_GROUNDING_TYPE_DISABLED (1):
+ Web grounding is disabled.
+ WEB_GROUNDING_TYPE_GOOGLE_SEARCH (2):
+ Grounding with Google Search is enabled.
+ WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH (3):
+ Grounding with Enterprise Web Search is
+ enabled.
+ """
+
+ WEB_GROUNDING_TYPE_UNSPECIFIED = 0
+ WEB_GROUNDING_TYPE_DISABLED = 1
+ WEB_GROUNDING_TYPE_GOOGLE_SEARCH = 2
+ WEB_GROUNDING_TYPE_ENTERPRISE_WEB_SEARCH = 3
+
+ web_grounding_type: "WidgetConfig.AssistantSettings.WebGroundingType" = (
+ proto.Field(
+ proto.ENUM,
+ number=2,
+ enum="WidgetConfig.AssistantSettings.WebGroundingType",
+ )
+ )
+ default_web_grounding_toggle_off: bool = proto.Field(
+ proto.BOOL,
+ number=3,
+ )
+ disable_location_context: bool = proto.Field(
+ proto.BOOL,
+ number=5,
+ )
+
+ class CustomerProvidedConfig(proto.Message):
+ r"""Customer provided configurations.
+
+ Attributes:
+ customer_type (google.cloud.discoveryengine_v1.types.WidgetConfig.CustomerProvidedConfig.CustomerType):
+ Customer type.
+ compliance_level (google.cloud.discoveryengine_v1.types.WidgetConfig.CustomerProvidedConfig.ComplianceLevel):
+ Output only. The customer's Assured Workloads compliance
+ level.
+
+ ``customer_type`` collapses every compliance level into a
+ single ``GOVERNMENT_CUSTOMER`` value, so a client that gates
+ a feature on one specific level rather than on government
+ status as a whole must read this field instead.
+ """
+
+ class CustomerType(proto.Enum):
+ r"""Customer type.
+
+ Values:
+ DEFAULT_CUSTOMER (0):
+ Default customer type.
+ GOVERNMENT_CUSTOMER (1):
+ Government customer type. Some features are
+ disabled for government customers due to legal
+ requirements.
+ """
+
+ DEFAULT_CUSTOMER = 0
+ GOVERNMENT_CUSTOMER = 1
+
+ class ComplianceLevel(proto.Enum):
+ r"""Assured Workloads compliance level of the customer's project.
+
+ Not frozen: further levels may be added as more compliance
+ regimes are supported, so a client must treat an unrecognized
+ value as government-restricted rather than as unrestricted.
+
+ Values:
+ COMPLIANCE_LEVEL_UNSPECIFIED (0):
+ The project has no Assured Workloads
+ compliance level, or reports one that this API
+ version does not model.
+ COMPLIANCE_LEVEL_FEDRAMP_HIGH (1):
+ FedRAMP High compliance level.
+ COMPLIANCE_LEVEL_IL4 (2):
+ Impact Level 4 (IL4) compliance level.
+ COMPLIANCE_LEVEL_IL5 (3):
+ Impact Level 5 (IL5) compliance level.
+ """
+
+ COMPLIANCE_LEVEL_UNSPECIFIED = 0
+ COMPLIANCE_LEVEL_FEDRAMP_HIGH = 1
+ COMPLIANCE_LEVEL_IL4 = 2
+ COMPLIANCE_LEVEL_IL5 = 3
+
+ customer_type: "WidgetConfig.CustomerProvidedConfig.CustomerType" = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum="WidgetConfig.CustomerProvidedConfig.CustomerType",
+ )
+ compliance_level: "WidgetConfig.CustomerProvidedConfig.ComplianceLevel" = (
+ proto.Field(
+ proto.ENUM,
+ number=2,
+ enum="WidgetConfig.CustomerProvidedConfig.ComplianceLevel",
+ )
+ )
+
+ class Node(proto.Message):
+ r"""Represents a single reusable computational or logical unit.
+
+ Attributes:
+ display_name (str):
+ Output only. A human readable name for the
+ node.
+ icon_url (str):
+ Output only. An identifier or URL pointing to
+ an icon representing this node type.
+ description (str):
+ Output only. A detailed description of what
+ the node does.
+ parameter_schema (google.protobuf.struct_pb2.Struct):
+ Output only. The parameter schema of the
+ tool.
+ This schema is expected to conform to the
+ OpenAPI Schema standard (see
+ https://spec.openapis.org/oas/v3.0.3.html and
+ AIP-146). It describes the expected structure of
+ the parameters that this node accepts.
+ output_schema (google.protobuf.struct_pb2.Struct):
+ Output only. The output schema of the tool.
+
+ This schema is expected to conform to the
+ OpenAPI Schema standard (see
+ https://spec.openapis.org/oas/v3.0.3.html/ and
+ AIP-146). It describes the structure of the
+ output produced by this node.
+ type_ (google.cloud.discoveryengine_v1.types.WidgetConfig.Node.Type):
+ Output only. The type of the node.
+ """
+
+ class Type(proto.Enum):
+ r"""Identifies the type of the node in the agent flow.
+
+ Values:
+ TYPE_UNSPECIFIED (0):
+ Unspecified type.
+ TRIGGER (1):
+ Trigger type.
+ FLOW (2):
+ Flow type.
+ CONNECTOR (3):
+ Connector type.
+ """
+
+ TYPE_UNSPECIFIED = 0
+ TRIGGER = 1
+ FLOW = 2
+ CONNECTOR = 3
+
+ display_name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ icon_url: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ description: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+ parameter_schema: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=4,
+ message=struct_pb2.Struct,
+ )
+ output_schema: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=5,
+ message=struct_pb2.Struct,
+ )
+ type_: "WidgetConfig.Node.Type" = proto.Field(
+ proto.ENUM,
+ number=6,
+ enum="WidgetConfig.Node.Type",
+ )
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ display_name: 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=15,
+ message=timestamp_pb2.Timestamp,
+ )
+ data_store_type: DataStoreType = proto.Field(
+ proto.ENUM,
+ number=8,
+ enum=DataStoreType,
+ )
+ config_id: str = proto.Field(
+ proto.STRING,
+ number=12,
+ )
+ solution_type: common.SolutionType = proto.Field(
+ proto.ENUM,
+ number=14,
+ enum=common.SolutionType,
+ )
+ industry_vertical: common.IndustryVertical = proto.Field(
+ proto.ENUM,
+ number=26,
+ enum=common.IndustryVertical,
+ )
+ llm_enabled: bool = proto.Field(
+ proto.BOOL,
+ number=20,
+ )
+ enable_result_score: bool = proto.Field(
+ proto.BOOL,
+ number=21,
+ )
+ minimum_data_term_accepted: bool = proto.Field(
+ proto.BOOL,
+ number=25,
+ )
+ collection_components: MutableSequence[CollectionComponent] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=29,
+ message=CollectionComponent,
+ )
+ ui_settings: UiSettings = proto.Field(
+ proto.MESSAGE,
+ number=33,
+ message=UiSettings,
+ )
+ access_settings: AccessSettings = proto.Field(
+ proto.MESSAGE,
+ number=34,
+ message=AccessSettings,
+ )
+ ui_branding: UiBrandingSettings = proto.Field(
+ proto.MESSAGE,
+ number=35,
+ message=UiBrandingSettings,
+ )
+ homepage_setting: HomepageSetting = proto.Field(
+ proto.MESSAGE,
+ number=38,
+ message=HomepageSetting,
+ )
+ assistant_settings: AssistantSettings = proto.Field(
+ proto.MESSAGE,
+ number=39,
+ message=AssistantSettings,
+ )
+ customer_provided_config: CustomerProvidedConfig = proto.Field(
+ proto.MESSAGE,
+ number=40,
+ message=CustomerProvidedConfig,
+ )
+ enable_private_knowledge_graph: bool = proto.Field(
+ proto.BOOL,
+ number=42,
+ )
+ gemini_bundle: bool = proto.Field(
+ proto.BOOL,
+ number=44,
+ )
+ batch_auth_statuses: MutableSequence[BatchAuthStatus] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=48,
+ message=BatchAuthStatus,
+ )
+ nodes: MutableSequence[Node] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=46,
+ message=Node,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/widget_config_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/widget_config_service.py
new file mode 100644
index 000000000000..515e4bea20a1
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/widget_config_service.py
@@ -0,0 +1,150 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 proto # type: ignore
+
+from google.cloud.discoveryengine_v1.types import widget_config as gcd_widget_config
+
+__protobuf__ = proto.module(
+ package="google.cloud.discoveryengine.v1",
+ manifest={
+ "GetWidgetConfigRequest",
+ "UpdateWidgetConfigRequest",
+ },
+)
+
+
+class GetWidgetConfigRequest(proto.Message):
+ r"""Request for
+ [WidgetConfigService.GetWidgetConfig][google.cloud.discoveryengine.v1.WidgetConfigService.GetWidgetConfig]
+ method.
+
+ Attributes:
+ name (str):
+ Required. Full WidgetConfig resource name. Format:
+ ``projects/{project}/locations/{location}/collections/{collection_id}/dataStores/{data_store_id}/widgetConfigs/{widget_config_id}``
+ accept_cache (bool):
+ Optional. Whether it's acceptable to load the
+ widget config from cache. If set to true, recent
+ changes on widget configs may take a few minutes
+ to reflect on the end user's view. It's
+ recommended to set to true for maturely
+ developed widgets, as it improves widget
+ performance. Set to false to see changes
+ reflected in prod right away, if your widget is
+ under development.
+ get_widget_config_request_option (google.cloud.discoveryengine_v1.types.GetWidgetConfigRequest.GetWidgetConfigRequestOption):
+ Optional. Options for GetWidgetConfigRequest.
+ language_code (str):
+ Optional. BCP-47 language tag (e.g. "en", "fr-CA"). Used to
+ localize human-readable strings in the response, such as the
+ model selector ``display_name`` / ``description`` on
+ ``WidgetConfig.UiSettings.ModelConfigInfo``. Empty / unset
+ falls back to the default language (English).
+ model_info_view (google.cloud.discoveryengine_v1.types.ModelInfoView):
+ Optional. Selects which view of
+ ``WidgetConfig.UiSettings.ModelConfigInfo`` the backend
+ computes. ``ADMIN`` is set by the Cloud Console admin
+ "Feature Management" page to receive the admin-surfaced
+ model set with ``ResolvedModel.admin_view`` populated;
+ ``END_USER_MOBILE`` is set by the Gemini Enterprise mobile
+ app to receive the mobile model set; unset /
+ ``END_USER_WEB`` returns the end-user web selector.
+ """
+
+ class GetWidgetConfigRequestOption(proto.Message):
+ r"""Options for GetWidgetConfigRequest.
+
+ Attributes:
+ turn_off_collection_components (bool):
+ Optional. Whether to turn off collection_components in
+ WidgetConfig to reduce latency and data transmission.
+ """
+
+ turn_off_collection_components: bool = proto.Field(
+ proto.BOOL,
+ number=1,
+ )
+
+ name: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ accept_cache: bool = proto.Field(
+ proto.BOOL,
+ number=2,
+ )
+ get_widget_config_request_option: GetWidgetConfigRequestOption = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message=GetWidgetConfigRequestOption,
+ )
+ language_code: str = proto.Field(
+ proto.STRING,
+ number=4,
+ )
+ model_info_view: gcd_widget_config.ModelInfoView = proto.Field(
+ proto.ENUM,
+ number=5,
+ enum=gcd_widget_config.ModelInfoView,
+ )
+
+
+class UpdateWidgetConfigRequest(proto.Message):
+ r"""Request for
+ [WidgetConfigService.UpdateWidgetConfig][google.cloud.discoveryengine.v1.WidgetConfigService.UpdateWidgetConfig]
+ method.
+
+ Attributes:
+ widget_config (google.cloud.discoveryengine_v1.types.WidgetConfig):
+ Required. The
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ to update.
+
+ If the caller does not have permission to update the
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig],
+ then a PERMISSION_DENIED error is returned.
+
+ If the
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ to update does not exist, a NOT_FOUND error is returned.
+ update_mask (google.protobuf.field_mask_pb2.FieldMask):
+ Indicates which fields in the provided
+ [WidgetConfig][google.cloud.discoveryengine.v1.WidgetConfig]
+ to update. The following are the only supported fields:
+
+ - [WidgetConfig.enable_autocomplete][google.cloud.discoveryengine.v1.WidgetConfig.enable_autocomplete]
+
+ If not set, all supported fields are updated.
+ """
+
+ widget_config: gcd_widget_config.WidgetConfig = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message=gcd_widget_config.WidgetConfig,
+ )
+ update_mask: field_mask_pb2.FieldMask = proto.Field(
+ proto.MESSAGE,
+ number=2,
+ message=field_mask_pb2.FieldMask,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_get_acl_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_get_acl_config_async.py
new file mode 100644
index 000000000000..f485d74fda59
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_get_acl_config_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 GetAclConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AclConfigService_GetAclConfig_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 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)
+
+
+# [END discoveryengine_v1_generated_AclConfigService_GetAclConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_get_acl_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_get_acl_config_sync.py
new file mode 100644
index 000000000000..89979c3037e9
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_get_acl_config_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 GetAclConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AclConfigService_GetAclConfig_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 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)
+
+
+# [END discoveryengine_v1_generated_AclConfigService_GetAclConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_update_acl_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_update_acl_config_async.py
new file mode 100644
index 000000000000..f4578cc73936
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_update_acl_config_async.py
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 UpdateAclConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AclConfigService_UpdateAclConfig_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 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)
+
+
+# [END discoveryengine_v1_generated_AclConfigService_UpdateAclConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_update_acl_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_update_acl_config_sync.py
new file mode 100644
index 000000000000..d36c05368924
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_acl_config_service_update_acl_config_sync.py
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 UpdateAclConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AclConfigService_UpdateAclConfig_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 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)
+
+
+# [END discoveryengine_v1_generated_AclConfigService_UpdateAclConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_create_assistant_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_create_assistant_async.py
new file mode 100644
index 000000000000..553ddb21fe7b
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_create_assistant_async.py
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for CreateAssistant
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_CreateAssistant_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 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)
+
+
+# [END discoveryengine_v1_generated_AssistantService_CreateAssistant_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_create_assistant_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_create_assistant_sync.py
new file mode 100644
index 000000000000..ab3b649026ce
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_create_assistant_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 CreateAssistant
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_CreateAssistant_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 discoveryengine_v1
+
+
+def sample_create_assistant():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # 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 = client.create_assistant(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_AssistantService_CreateAssistant_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_delete_assistant_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_delete_assistant_async.py
new file mode 100644
index 000000000000..bf2f9a221fa1
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_delete_assistant_async.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 DeleteAssistant
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_DeleteAssistant_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 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)
+
+
+# [END discoveryengine_v1_generated_AssistantService_DeleteAssistant_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_delete_assistant_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_delete_assistant_sync.py
new file mode 100644
index 000000000000..304b212fe39b
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_delete_assistant_sync.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 DeleteAssistant
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_DeleteAssistant_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 discoveryengine_v1
+
+
+def sample_delete_assistant():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteAssistantRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ client.delete_assistant(request=request)
+
+
+# [END discoveryengine_v1_generated_AssistantService_DeleteAssistant_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_get_assistant_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_get_assistant_async.py
new file mode 100644
index 000000000000..5f13c40077ca
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_get_assistant_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 GetAssistant
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_GetAssistant_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 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)
+
+
+# [END discoveryengine_v1_generated_AssistantService_GetAssistant_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_get_assistant_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_get_assistant_sync.py
new file mode 100644
index 000000000000..18a9c8697ef3
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_get_assistant_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 GetAssistant
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_GetAssistant_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 discoveryengine_v1
+
+
+def sample_get_assistant():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetAssistantRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_assistant(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_AssistantService_GetAssistant_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_list_assistants_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_list_assistants_async.py
new file mode 100644
index 000000000000..03abd9b485b8
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_list_assistants_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 ListAssistants
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_ListAssistants_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 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)
+
+
+# [END discoveryengine_v1_generated_AssistantService_ListAssistants_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_list_assistants_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_list_assistants_sync.py
new file mode 100644
index 000000000000..1d01a1e99132
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_list_assistants_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 ListAssistants
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_ListAssistants_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 discoveryengine_v1
+
+
+def sample_list_assistants():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListAssistantsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_assistants(request=request)
+
+ # Handle the response
+ for response in page_result:
+ print(response)
+
+
+# [END discoveryengine_v1_generated_AssistantService_ListAssistants_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_update_assistant_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_update_assistant_async.py
new file mode 100644
index 000000000000..cb9ee727ad09
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_update_assistant_async.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for UpdateAssistant
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_UpdateAssistant_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 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)
+
+
+# [END discoveryengine_v1_generated_AssistantService_UpdateAssistant_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_update_assistant_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_update_assistant_sync.py
new file mode 100644
index 000000000000..2a8bba5e1cdc
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_assistant_service_update_assistant_sync.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for UpdateAssistant
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_AssistantService_UpdateAssistant_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 discoveryengine_v1
+
+
+def sample_update_assistant():
+ # Create a client
+ client = discoveryengine_v1.AssistantServiceClient()
+
+ # Initialize request argument(s)
+ assistant = discoveryengine_v1.Assistant()
+ assistant.display_name = "display_name_value"
+
+ request = discoveryengine_v1.UpdateAssistantRequest(
+ assistant=assistant,
+ )
+
+ # Make the request
+ response = client.update_assistant(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_AssistantService_UpdateAssistant_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_delete_collection_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_delete_collection_async.py
new file mode 100644
index 000000000000..5fed490305f2
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_delete_collection_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 DeleteCollection
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_CollectionService_DeleteCollection_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 discoveryengine_v1
+
+
+async def sample_delete_collection():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteCollectionRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ operation = await client.delete_collection(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = await operation.result()
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_CollectionService_DeleteCollection_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_delete_collection_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_delete_collection_sync.py
new file mode 100644
index 000000000000..1de204a2e9a9
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_delete_collection_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 DeleteCollection
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_CollectionService_DeleteCollection_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 discoveryengine_v1
+
+
+def sample_delete_collection():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteCollectionRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ operation = client.delete_collection(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = operation.result()
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_CollectionService_DeleteCollection_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_get_iam_policy_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_get_iam_policy_async.py
new file mode 100644
index 000000000000..6261a6a3ec5a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_get_iam_policy_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 GetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_CollectionService_GetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+async def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_CollectionService_GetIamPolicy_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_get_iam_policy_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_get_iam_policy_sync.py
new file mode 100644
index 000000000000..d4a74ae670a4
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_get_iam_policy_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 GetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_CollectionService_GetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_CollectionService_GetIamPolicy_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_set_iam_policy_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_set_iam_policy_async.py
new file mode 100644
index 000000000000..29552a88439a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_set_iam_policy_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 SetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_CollectionService_SetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+async def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_CollectionService_SetIamPolicy_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_set_iam_policy_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_set_iam_policy_sync.py
new file mode 100644
index 000000000000..da07a5ea12d2
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_collection_service_set_iam_policy_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 SetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_CollectionService_SetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.CollectionServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_CollectionService_SetIamPolicy_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_completion_service_advanced_complete_query_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_completion_service_advanced_complete_query_async.py
new file mode 100644
index 000000000000..4f3f1592dd44
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_completion_service_advanced_complete_query_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 AdvancedCompleteQuery
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_CompletionService_AdvancedCompleteQuery_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 discoveryengine_v1
+
+
+async def sample_advanced_complete_query():
+ # Create a client
+ client = discoveryengine_v1.CompletionServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.AdvancedCompleteQueryRequest(
+ completion_config="completion_config_value",
+ query="query_value",
+ )
+
+ # Make the request
+ response = await client.advanced_complete_query(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_CompletionService_AdvancedCompleteQuery_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_completion_service_advanced_complete_query_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_completion_service_advanced_complete_query_sync.py
new file mode 100644
index 000000000000..82cb6fbf5e75
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_completion_service_advanced_complete_query_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 AdvancedCompleteQuery
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_CompletionService_AdvancedCompleteQuery_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 discoveryengine_v1
+
+
+def sample_advanced_complete_query():
+ # Create a client
+ client = discoveryengine_v1.CompletionServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.AdvancedCompleteQueryRequest(
+ completion_config="completion_config_value",
+ query="query_value",
+ )
+
+ # Make the request
+ response = client.advanced_complete_query(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_CompletionService_AdvancedCompleteQuery_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_create_control_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_create_control_async.py
index 7cc30ac7c074..7401b1584c10 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_create_control_async.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_create_control_async.py
@@ -44,7 +44,7 @@ async def sample_create_control():
control.boost_action.filter = "filter_value"
control.boost_action.data_store = "data_store_value"
control.display_name = "display_name_value"
- control.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ control.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.CreateControlRequest(
parent="parent_value",
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_create_control_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_create_control_sync.py
index 4c191e8d4b66..d5cac534e508 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_create_control_sync.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_create_control_sync.py
@@ -44,7 +44,7 @@ def sample_create_control():
control.boost_action.filter = "filter_value"
control.boost_action.data_store = "data_store_value"
control.display_name = "display_name_value"
- control.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ control.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.CreateControlRequest(
parent="parent_value",
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_update_control_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_update_control_async.py
index aff496d786ca..004974a2a79e 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_update_control_async.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_update_control_async.py
@@ -44,7 +44,7 @@ async def sample_update_control():
control.boost_action.filter = "filter_value"
control.boost_action.data_store = "data_store_value"
control.display_name = "display_name_value"
- control.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ control.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateControlRequest(
control=control,
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_update_control_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_update_control_sync.py
index dfee8bdfd968..39d7dc76aa80 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_update_control_sync.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_control_service_update_control_sync.py
@@ -44,7 +44,7 @@ def sample_update_control():
control.boost_action.filter = "filter_value"
control.boost_action.data_store = "data_store_value"
control.display_name = "display_name_value"
- control.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ control.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateControlRequest(
control=control,
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_get_data_connector_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_get_data_connector_async.py
new file mode 100644
index 000000000000..730aaccd1e7e
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_get_data_connector_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 GetDataConnector
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataConnectorService_GetDataConnector_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 discoveryengine_v1
+
+
+async def sample_get_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetDataConnectorRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_data_connector(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataConnectorService_GetDataConnector_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_get_data_connector_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_get_data_connector_sync.py
new file mode 100644
index 000000000000..5a1c27129aaa
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_get_data_connector_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 GetDataConnector
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataConnectorService_GetDataConnector_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 discoveryengine_v1
+
+
+def sample_get_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetDataConnectorRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_data_connector(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataConnectorService_GetDataConnector_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_set_up_data_connector_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_set_up_data_connector_async.py
new file mode 100644
index 000000000000..966642cb743d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_set_up_data_connector_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 SetUpDataConnector
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataConnectorService_SetUpDataConnector_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 discoveryengine_v1
+
+
+async def sample_set_up_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceAsyncClient()
+
+ # Initialize request argument(s)
+ data_connector = discoveryengine_v1.DataConnector()
+ data_connector.data_source = "data_source_value"
+
+ request = discoveryengine_v1.SetUpDataConnectorRequest(
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=data_connector,
+ )
+
+ # Make the request
+ operation = await client.set_up_data_connector(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = await operation.result()
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataConnectorService_SetUpDataConnector_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_set_up_data_connector_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_set_up_data_connector_sync.py
new file mode 100644
index 000000000000..aa69f155654a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_set_up_data_connector_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 SetUpDataConnector
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataConnectorService_SetUpDataConnector_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 discoveryengine_v1
+
+
+def sample_set_up_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceClient()
+
+ # Initialize request argument(s)
+ data_connector = discoveryengine_v1.DataConnector()
+ data_connector.data_source = "data_source_value"
+
+ request = discoveryengine_v1.SetUpDataConnectorRequest(
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=data_connector,
+ )
+
+ # Make the request
+ operation = client.set_up_data_connector(request=request)
+
+ print("Waiting for operation to complete...")
+
+ response = operation.result()
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataConnectorService_SetUpDataConnector_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_update_data_connector_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_update_data_connector_async.py
new file mode 100644
index 000000000000..d526dcfe5bbf
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_update_data_connector_async.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for UpdateDataConnector
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataConnectorService_UpdateDataConnector_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 discoveryengine_v1
+
+
+async def sample_update_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceAsyncClient()
+
+ # Initialize request argument(s)
+ data_connector = discoveryengine_v1.DataConnector()
+ data_connector.data_source = "data_source_value"
+
+ request = discoveryengine_v1.UpdateDataConnectorRequest(
+ data_connector=data_connector,
+ )
+
+ # Make the request
+ response = await client.update_data_connector(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataConnectorService_UpdateDataConnector_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_update_data_connector_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_update_data_connector_sync.py
new file mode 100644
index 000000000000..7c0365ad14b3
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_connector_service_update_data_connector_sync.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for UpdateDataConnector
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataConnectorService_UpdateDataConnector_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 discoveryengine_v1
+
+
+def sample_update_data_connector():
+ # Create a client
+ client = discoveryengine_v1.DataConnectorServiceClient()
+
+ # Initialize request argument(s)
+ data_connector = discoveryengine_v1.DataConnector()
+ data_connector.data_source = "data_source_value"
+
+ request = discoveryengine_v1.UpdateDataConnectorRequest(
+ data_connector=data_connector,
+ )
+
+ # Make the request
+ response = client.update_data_connector(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataConnectorService_UpdateDataConnector_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_get_iam_policy_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_get_iam_policy_async.py
new file mode 100644
index 000000000000..f0fd3122795e
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_get_iam_policy_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 GetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataStoreService_GetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+async def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.DataStoreServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataStoreService_GetIamPolicy_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_get_iam_policy_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_get_iam_policy_sync.py
new file mode 100644
index 000000000000..3ebfa9d6d88a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_get_iam_policy_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 GetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataStoreService_GetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.DataStoreServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataStoreService_GetIamPolicy_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_set_iam_policy_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_set_iam_policy_async.py
new file mode 100644
index 000000000000..a5d8d7731eac
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_set_iam_policy_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 SetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataStoreService_SetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+async def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.DataStoreServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataStoreService_SetIamPolicy_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_set_iam_policy_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_set_iam_policy_sync.py
new file mode 100644
index 000000000000..af7b69b0234b
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_data_store_service_set_iam_policy_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 SetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_DataStoreService_SetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.DataStoreServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_DataStoreService_SetIamPolicy_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_create_engine_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_create_engine_async.py
index 03a7b3316744..7130ab349f71 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_create_engine_async.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_create_engine_async.py
@@ -41,7 +41,7 @@ async def sample_create_engine():
# Initialize request argument(s)
engine = discoveryengine_v1.Engine()
engine.display_name = "display_name_value"
- engine.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ engine.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.CreateEngineRequest(
parent="parent_value",
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_create_engine_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_create_engine_sync.py
index d8fe4fe0b356..b3eda9f53c7b 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_create_engine_sync.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_create_engine_sync.py
@@ -41,7 +41,7 @@ def sample_create_engine():
# Initialize request argument(s)
engine = discoveryengine_v1.Engine()
engine.display_name = "display_name_value"
- engine.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ engine.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.CreateEngineRequest(
parent="parent_value",
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_get_iam_policy_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_get_iam_policy_async.py
new file mode 100644
index 000000000000..27da5ec8b910
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_get_iam_policy_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 GetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_EngineService_GetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+async def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.EngineServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_EngineService_GetIamPolicy_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_get_iam_policy_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_get_iam_policy_sync.py
new file mode 100644
index 000000000000..4f8af50281ba
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_get_iam_policy_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 GetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_EngineService_GetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+def sample_get_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.EngineServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.get_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_EngineService_GetIamPolicy_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_set_iam_policy_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_set_iam_policy_async.py
new file mode 100644
index 000000000000..39641d38b82b
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_set_iam_policy_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 SetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_EngineService_SetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+async def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.EngineServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = await client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_EngineService_SetIamPolicy_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_set_iam_policy_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_set_iam_policy_sync.py
new file mode 100644
index 000000000000..783fc96a55b8
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_set_iam_policy_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 SetIamPolicy
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_EngineService_SetIamPolicy_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
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+
+from google.cloud import discoveryengine_v1
+
+
+def sample_set_iam_policy():
+ # Create a client
+ client = discoveryengine_v1.EngineServiceClient()
+
+ # Initialize request argument(s)
+ request = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Make the request
+ response = client.set_iam_policy(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_EngineService_SetIamPolicy_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_update_engine_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_update_engine_async.py
index c5d5810369b0..4dd6cf595062 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_update_engine_async.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_update_engine_async.py
@@ -41,7 +41,7 @@ async def sample_update_engine():
# Initialize request argument(s)
engine = discoveryengine_v1.Engine()
engine.display_name = "display_name_value"
- engine.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ engine.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateEngineRequest(
engine=engine,
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_update_engine_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_update_engine_sync.py
index 318fd5cef693..5a28ba514b36 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_update_engine_sync.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_engine_service_update_engine_sync.py
@@ -41,7 +41,7 @@ def sample_update_engine():
# Initialize request argument(s)
engine = discoveryengine_v1.Engine()
engine.display_name = "display_name_value"
- engine.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ engine.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateEngineRequest(
engine=engine,
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_create_license_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_create_license_config_async.py
new file mode 100644
index 000000000000..56146177c2f4
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_create_license_config_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 CreateLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_CreateLicenseConfig_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 discoveryengine_v1
+
+
+async def sample_create_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ license_config = discoveryengine_v1.LicenseConfig()
+ license_config.license_count = 1387
+ license_config.subscription_tier = "SUBSCRIPTION_TIER_EDU_GOV_EMERGING"
+ license_config.subscription_term = "SUBSCRIPTION_TERM_CUSTOM"
+
+ request = discoveryengine_v1.CreateLicenseConfigRequest(
+ parent="parent_value",
+ license_config=license_config,
+ )
+
+ # Make the request
+ response = await client.create_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_CreateLicenseConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_create_license_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_create_license_config_sync.py
new file mode 100644
index 000000000000..cddc100a5dd2
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_create_license_config_sync.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 CreateLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_CreateLicenseConfig_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 discoveryengine_v1
+
+
+def sample_create_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ license_config = discoveryengine_v1.LicenseConfig()
+ license_config.license_count = 1387
+ license_config.subscription_tier = "SUBSCRIPTION_TIER_EDU_GOV_EMERGING"
+ license_config.subscription_term = "SUBSCRIPTION_TERM_CUSTOM"
+
+ request = discoveryengine_v1.CreateLicenseConfigRequest(
+ parent="parent_value",
+ license_config=license_config,
+ )
+
+ # Make the request
+ response = client.create_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_CreateLicenseConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_distribute_license_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_distribute_license_config_async.py
new file mode 100644
index 000000000000..769ddedab60a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_distribute_license_config_async.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for DistributeLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_DistributeLicenseConfig_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 discoveryengine_v1
+
+
+async def sample_distribute_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DistributeLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ )
+
+ # Make the request
+ response = await client.distribute_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_DistributeLicenseConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_distribute_license_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_distribute_license_config_sync.py
new file mode 100644
index 000000000000..7da06cf1b148
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_distribute_license_config_sync.py
@@ -0,0 +1,56 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for DistributeLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_DistributeLicenseConfig_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 discoveryengine_v1
+
+
+def sample_distribute_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DistributeLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ )
+
+ # Make the request
+ response = client.distribute_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_DistributeLicenseConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_get_license_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_get_license_config_async.py
new file mode 100644
index 000000000000..d20a3ee6ca4e
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_get_license_config_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 GetLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_GetLicenseConfig_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 discoveryengine_v1
+
+
+async def sample_get_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetLicenseConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_GetLicenseConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_get_license_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_get_license_config_sync.py
new file mode 100644
index 000000000000..143adb9eb26a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_get_license_config_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 GetLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_GetLicenseConfig_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 discoveryengine_v1
+
+
+def sample_get_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetLicenseConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_GetLicenseConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_list_license_configs_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_list_license_configs_async.py
new file mode 100644
index 000000000000..4de30a5462a7
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_list_license_configs_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 ListLicenseConfigs
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_ListLicenseConfigs_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 discoveryengine_v1
+
+
+async def sample_list_license_configs():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListLicenseConfigsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_license_configs(request=request)
+
+ # Handle the response
+ async for response in page_result:
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_ListLicenseConfigs_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_list_license_configs_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_list_license_configs_sync.py
new file mode 100644
index 000000000000..d22c0681c51f
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_list_license_configs_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 ListLicenseConfigs
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_ListLicenseConfigs_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 discoveryengine_v1
+
+
+def sample_list_license_configs():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListLicenseConfigsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_license_configs(request=request)
+
+ # Handle the response
+ for response in page_result:
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_ListLicenseConfigs_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_retract_license_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_retract_license_config_async.py
new file mode 100644
index 000000000000..5eb341a7236b
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_retract_license_config_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 RetractLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_RetractLicenseConfig_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 discoveryengine_v1
+
+
+async def sample_retract_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.RetractLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ )
+
+ # Make the request
+ response = await client.retract_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_RetractLicenseConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_retract_license_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_retract_license_config_sync.py
new file mode 100644
index 000000000000..0063c401ae79
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_retract_license_config_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 RetractLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_RetractLicenseConfig_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 discoveryengine_v1
+
+
+def sample_retract_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.RetractLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ )
+
+ # Make the request
+ response = client.retract_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_RetractLicenseConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_update_license_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_update_license_config_async.py
new file mode 100644
index 000000000000..17d3eab3484d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_update_license_config_async.py
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Generated code. DO NOT EDIT!
+#
+# Snippet for UpdateLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_UpdateLicenseConfig_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 discoveryengine_v1
+
+
+async def sample_update_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ license_config = discoveryengine_v1.LicenseConfig()
+ license_config.license_count = 1387
+ license_config.subscription_tier = "SUBSCRIPTION_TIER_EDU_GOV_EMERGING"
+ license_config.subscription_term = "SUBSCRIPTION_TERM_CUSTOM"
+
+ request = discoveryengine_v1.UpdateLicenseConfigRequest(
+ license_config=license_config,
+ )
+
+ # Make the request
+ response = await client.update_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_UpdateLicenseConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_update_license_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_update_license_config_sync.py
new file mode 100644
index 000000000000..0276109f0fd9
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_license_config_service_update_license_config_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 UpdateLicenseConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_LicenseConfigService_UpdateLicenseConfig_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 discoveryengine_v1
+
+
+def sample_update_license_config():
+ # Create a client
+ client = discoveryengine_v1.LicenseConfigServiceClient()
+
+ # Initialize request argument(s)
+ license_config = discoveryengine_v1.LicenseConfig()
+ license_config.license_count = 1387
+ license_config.subscription_tier = "SUBSCRIPTION_TIER_EDU_GOV_EMERGING"
+ license_config.subscription_term = "SUBSCRIPTION_TERM_CUSTOM"
+
+ request = discoveryengine_v1.UpdateLicenseConfigRequest(
+ license_config=license_config,
+ )
+
+ # Make the request
+ response = client.update_license_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_LicenseConfigService_UpdateLicenseConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_create_serving_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_create_serving_config_async.py
new file mode 100644
index 000000000000..d5348dcd6625
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_create_serving_config_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 CreateServingConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_ServingConfigService_CreateServingConfig_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 discoveryengine_v1
+
+
+async def sample_create_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ serving_config = discoveryengine_v1.ServingConfig()
+ serving_config.media_config.content_watched_percentage_threshold = 0.3811
+ serving_config.display_name = "display_name_value"
+ serving_config.solution_type = "SOLUTION_TYPE_AI_MODE"
+
+ request = discoveryengine_v1.CreateServingConfigRequest(
+ parent="parent_value",
+ serving_config=serving_config,
+ serving_config_id="serving_config_id_value",
+ )
+
+ # Make the request
+ response = await client.create_serving_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_ServingConfigService_CreateServingConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_create_serving_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_create_serving_config_sync.py
new file mode 100644
index 000000000000..6865f6a3b2c9
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_create_serving_config_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 CreateServingConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_ServingConfigService_CreateServingConfig_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 discoveryengine_v1
+
+
+def sample_create_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceClient()
+
+ # Initialize request argument(s)
+ serving_config = discoveryengine_v1.ServingConfig()
+ serving_config.media_config.content_watched_percentage_threshold = 0.3811
+ serving_config.display_name = "display_name_value"
+ serving_config.solution_type = "SOLUTION_TYPE_AI_MODE"
+
+ request = discoveryengine_v1.CreateServingConfigRequest(
+ parent="parent_value",
+ serving_config=serving_config,
+ serving_config_id="serving_config_id_value",
+ )
+
+ # Make the request
+ response = client.create_serving_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_ServingConfigService_CreateServingConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_delete_serving_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_delete_serving_config_async.py
new file mode 100644
index 000000000000..4df261f48a72
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_delete_serving_config_async.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 DeleteServingConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_ServingConfigService_DeleteServingConfig_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 discoveryengine_v1
+
+
+async def sample_delete_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteServingConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ await client.delete_serving_config(request=request)
+
+
+# [END discoveryengine_v1_generated_ServingConfigService_DeleteServingConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_delete_serving_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_delete_serving_config_sync.py
new file mode 100644
index 000000000000..42c0b706a5fc
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_delete_serving_config_sync.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 DeleteServingConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_ServingConfigService_DeleteServingConfig_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 discoveryengine_v1
+
+
+def sample_delete_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.DeleteServingConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ client.delete_serving_config(request=request)
+
+
+# [END discoveryengine_v1_generated_ServingConfigService_DeleteServingConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_get_serving_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_get_serving_config_async.py
new file mode 100644
index 000000000000..80a682afe005
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_get_serving_config_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 GetServingConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_ServingConfigService_GetServingConfig_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 discoveryengine_v1
+
+
+async def sample_get_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetServingConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_serving_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_ServingConfigService_GetServingConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_get_serving_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_get_serving_config_sync.py
new file mode 100644
index 000000000000..0985ede99b1b
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_get_serving_config_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 GetServingConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_ServingConfigService_GetServingConfig_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 discoveryengine_v1
+
+
+def sample_get_serving_config():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetServingConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_serving_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_ServingConfigService_GetServingConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_list_serving_configs_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_list_serving_configs_async.py
new file mode 100644
index 000000000000..d543c959cb02
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_list_serving_configs_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 ListServingConfigs
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_ServingConfigService_ListServingConfigs_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 discoveryengine_v1
+
+
+async def sample_list_serving_configs():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListServingConfigsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_serving_configs(request=request)
+
+ # Handle the response
+ async for response in page_result:
+ print(response)
+
+
+# [END discoveryengine_v1_generated_ServingConfigService_ListServingConfigs_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_list_serving_configs_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_list_serving_configs_sync.py
new file mode 100644
index 000000000000..fed44b229fba
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_list_serving_configs_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 ListServingConfigs
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_ServingConfigService_ListServingConfigs_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 discoveryengine_v1
+
+
+def sample_list_serving_configs():
+ # Create a client
+ client = discoveryengine_v1.ServingConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListServingConfigsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ page_result = client.list_serving_configs(request=request)
+
+ # Handle the response
+ for response in page_result:
+ print(response)
+
+
+# [END discoveryengine_v1_generated_ServingConfigService_ListServingConfigs_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_update_serving_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_update_serving_config_async.py
index 0e4f5256ed7e..c63c0f086e7e 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_update_serving_config_async.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_update_serving_config_async.py
@@ -42,7 +42,7 @@ async def sample_update_serving_config():
serving_config = discoveryengine_v1.ServingConfig()
serving_config.media_config.content_watched_percentage_threshold = 0.3811
serving_config.display_name = "display_name_value"
- serving_config.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ serving_config.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateServingConfigRequest(
serving_config=serving_config,
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_update_serving_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_update_serving_config_sync.py
index 9826f8ca1bfc..c2869999fbd0 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_update_serving_config_sync.py
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_serving_config_service_update_serving_config_sync.py
@@ -42,7 +42,7 @@ def sample_update_serving_config():
serving_config = discoveryengine_v1.ServingConfig()
serving_config.media_config.content_watched_percentage_threshold = 0.3811
serving_config.display_name = "display_name_value"
- serving_config.solution_type = "SOLUTION_TYPE_GENERATIVE_CHAT"
+ serving_config.solution_type = "SOLUTION_TYPE_AI_MODE"
request = discoveryengine_v1.UpdateServingConfigRequest(
serving_config=serving_config,
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_async.py
new file mode 100644
index 000000000000..5d443be88db3
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_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 ListLicenseConfigsUsageStats
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_UserLicenseService_ListLicenseConfigsUsageStats_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 discoveryengine_v1
+
+
+async def sample_list_license_configs_usage_stats():
+ # Create a client
+ client = discoveryengine_v1.UserLicenseServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListLicenseConfigsUsageStatsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ response = await client.list_license_configs_usage_stats(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_UserLicenseService_ListLicenseConfigsUsageStats_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_sync.py
new file mode 100644
index 000000000000..7f93af12b0ea
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_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 ListLicenseConfigsUsageStats
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_UserLicenseService_ListLicenseConfigsUsageStats_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 discoveryengine_v1
+
+
+def sample_list_license_configs_usage_stats():
+ # Create a client
+ client = discoveryengine_v1.UserLicenseServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.ListLicenseConfigsUsageStatsRequest(
+ parent="parent_value",
+ )
+
+ # Make the request
+ response = client.list_license_configs_usage_stats(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_UserLicenseService_ListLicenseConfigsUsageStats_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_get_user_store_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_get_user_store_async.py
new file mode 100644
index 000000000000..d637734c2576
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_get_user_store_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 GetUserStore
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_UserStoreService_GetUserStore_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 discoveryengine_v1
+
+
+async def sample_get_user_store():
+ # Create a client
+ client = discoveryengine_v1.UserStoreServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetUserStoreRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_user_store(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_UserStoreService_GetUserStore_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_get_user_store_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_get_user_store_sync.py
new file mode 100644
index 000000000000..5374b6798b5a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_get_user_store_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 GetUserStore
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_UserStoreService_GetUserStore_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 discoveryengine_v1
+
+
+def sample_get_user_store():
+ # Create a client
+ client = discoveryengine_v1.UserStoreServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetUserStoreRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_user_store(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_UserStoreService_GetUserStore_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_update_user_store_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_update_user_store_async.py
new file mode 100644
index 000000000000..272aa3681914
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_update_user_store_async.py
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 UpdateUserStore
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_UserStoreService_UpdateUserStore_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 discoveryengine_v1
+
+
+async def sample_update_user_store():
+ # Create a client
+ client = discoveryengine_v1.UserStoreServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.UpdateUserStoreRequest()
+
+ # Make the request
+ response = await client.update_user_store(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_UserStoreService_UpdateUserStore_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_update_user_store_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_update_user_store_sync.py
new file mode 100644
index 000000000000..07b43d9096e2
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_user_store_service_update_user_store_sync.py
@@ -0,0 +1,51 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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 UpdateUserStore
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_UserStoreService_UpdateUserStore_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 discoveryengine_v1
+
+
+def sample_update_user_store():
+ # Create a client
+ client = discoveryengine_v1.UserStoreServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.UpdateUserStoreRequest()
+
+ # Make the request
+ response = client.update_user_store(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_UserStoreService_UpdateUserStore_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_get_widget_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_get_widget_config_async.py
new file mode 100644
index 000000000000..681d093d6820
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_get_widget_config_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 GetWidgetConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_WidgetConfigService_GetWidgetConfig_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 discoveryengine_v1
+
+
+async def sample_get_widget_config():
+ # Create a client
+ client = discoveryengine_v1.WidgetConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetWidgetConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = await client.get_widget_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_WidgetConfigService_GetWidgetConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_get_widget_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_get_widget_config_sync.py
new file mode 100644
index 000000000000..2fe5e1cac0c5
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_get_widget_config_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 GetWidgetConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_WidgetConfigService_GetWidgetConfig_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 discoveryengine_v1
+
+
+def sample_get_widget_config():
+ # Create a client
+ client = discoveryengine_v1.WidgetConfigServiceClient()
+
+ # Initialize request argument(s)
+ request = discoveryengine_v1.GetWidgetConfigRequest(
+ name="name_value",
+ )
+
+ # Make the request
+ response = client.get_widget_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_WidgetConfigService_GetWidgetConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_update_widget_config_async.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_update_widget_config_async.py
new file mode 100644
index 000000000000..024b66dbd875
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_update_widget_config_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 UpdateWidgetConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_WidgetConfigService_UpdateWidgetConfig_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 discoveryengine_v1
+
+
+async def sample_update_widget_config():
+ # Create a client
+ client = discoveryengine_v1.WidgetConfigServiceAsyncClient()
+
+ # Initialize request argument(s)
+ widget_config = discoveryengine_v1.WidgetConfig()
+ widget_config.display_name = "display_name_value"
+ widget_config.solution_type = "SOLUTION_TYPE_AI_MODE"
+
+ request = discoveryengine_v1.UpdateWidgetConfigRequest(
+ widget_config=widget_config,
+ )
+
+ # Make the request
+ response = await client.update_widget_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_WidgetConfigService_UpdateWidgetConfig_async]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_update_widget_config_sync.py b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_update_widget_config_sync.py
new file mode 100644
index 000000000000..1360e05aee53
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/discoveryengine_v1_generated_widget_config_service_update_widget_config_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 UpdateWidgetConfig
+# 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-discoveryengine
+
+
+# [START discoveryengine_v1_generated_WidgetConfigService_UpdateWidgetConfig_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 discoveryengine_v1
+
+
+def sample_update_widget_config():
+ # Create a client
+ client = discoveryengine_v1.WidgetConfigServiceClient()
+
+ # Initialize request argument(s)
+ widget_config = discoveryengine_v1.WidgetConfig()
+ widget_config.display_name = "display_name_value"
+ widget_config.solution_type = "SOLUTION_TYPE_AI_MODE"
+
+ request = discoveryengine_v1.UpdateWidgetConfigRequest(
+ widget_config=widget_config,
+ )
+
+ # Make the request
+ response = client.update_widget_config(request=request)
+
+ # Handle the response
+ print(response)
+
+
+# [END discoveryengine_v1_generated_WidgetConfigService_UpdateWidgetConfig_sync]
diff --git a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json
index 1c20ad3a1dab..de86762cfb9d 100644
--- a/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json
+++ b/packages/google-cloud-discoveryengine/samples/generated_samples/snippet_metadata_google.cloud.discoveryengine.v1.json
@@ -16,22 +16,26 @@
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient",
- "shortName": "AssistantServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.AclConfigServiceAsyncClient",
+ "shortName": "AclConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient.stream_assist",
+ "fullName": "google.cloud.discoveryengine_v1.AclConfigServiceAsyncClient.get_acl_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.AssistantService.StreamAssist",
+ "fullName": "google.cloud.discoveryengine.v1.AclConfigService.GetAclConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.AssistantService",
- "shortName": "AssistantService"
+ "fullName": "google.cloud.discoveryengine.v1.AclConfigService",
+ "shortName": "AclConfigService"
},
- "shortName": "StreamAssist"
+ "shortName": "GetAclConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.StreamAssistRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetAclConfigRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -46,22 +50,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "Iterable[google.cloud.discoveryengine_v1.types.StreamAssistResponse]",
- "shortName": "stream_assist"
+ "resultType": "google.cloud.discoveryengine_v1.types.AclConfig",
+ "shortName": "get_acl_config"
},
- "description": "Sample for StreamAssist",
- "file": "discoveryengine_v1_generated_assistant_service_stream_assist_async.py",
+ "description": "Sample for GetAclConfig",
+ "file": "discoveryengine_v1_generated_acl_config_service_get_acl_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_AssistantService_StreamAssist_async",
+ "regionTag": "discoveryengine_v1_generated_AclConfigService_GetAclConfig_async",
"segments": [
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -81,33 +85,37 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
+ "end": 52,
"start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_assistant_service_stream_assist_async.py"
+ "title": "discoveryengine_v1_generated_acl_config_service_get_acl_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient",
- "shortName": "AssistantServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.AclConfigServiceClient",
+ "shortName": "AclConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient.stream_assist",
+ "fullName": "google.cloud.discoveryengine_v1.AclConfigServiceClient.get_acl_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.AssistantService.StreamAssist",
+ "fullName": "google.cloud.discoveryengine.v1.AclConfigService.GetAclConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.AssistantService",
- "shortName": "AssistantService"
+ "fullName": "google.cloud.discoveryengine.v1.AclConfigService",
+ "shortName": "AclConfigService"
},
- "shortName": "StreamAssist"
+ "shortName": "GetAclConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.StreamAssistRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetAclConfigRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -122,22 +130,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "Iterable[google.cloud.discoveryengine_v1.types.StreamAssistResponse]",
- "shortName": "stream_assist"
+ "resultType": "google.cloud.discoveryengine_v1.types.AclConfig",
+ "shortName": "get_acl_config"
},
- "description": "Sample for StreamAssist",
- "file": "discoveryengine_v1_generated_assistant_service_stream_assist_sync.py",
+ "description": "Sample for GetAclConfig",
+ "file": "discoveryengine_v1_generated_acl_config_service_get_acl_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_AssistantService_StreamAssist_sync",
+ "regionTag": "discoveryengine_v1_generated_AclConfigService_GetAclConfig_sync",
"segments": [
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -157,38 +165,34 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
+ "end": 52,
"start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_assistant_service_stream_assist_sync.py"
+ "title": "discoveryengine_v1_generated_acl_config_service_get_acl_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient",
- "shortName": "CmekConfigServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.AclConfigServiceAsyncClient",
+ "shortName": "AclConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient.delete_cmek_config",
+ "fullName": "google.cloud.discoveryengine_v1.AclConfigServiceAsyncClient.update_acl_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.DeleteCmekConfig",
+ "fullName": "google.cloud.discoveryengine.v1.AclConfigService.UpdateAclConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
- "shortName": "CmekConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.AclConfigService",
+ "shortName": "AclConfigService"
},
- "shortName": "DeleteCmekConfig"
+ "shortName": "UpdateAclConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteCmekConfigRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateAclConfigRequest"
},
{
"name": "retry",
@@ -203,22 +207,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "delete_cmek_config"
+ "resultType": "google.cloud.discoveryengine_v1.types.AclConfig",
+ "shortName": "update_acl_config"
},
- "description": "Sample for DeleteCmekConfig",
- "file": "discoveryengine_v1_generated_cmek_config_service_delete_cmek_config_async.py",
+ "description": "Sample for UpdateAclConfig",
+ "file": "discoveryengine_v1_generated_acl_config_service_update_acl_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CmekConfigService_DeleteCmekConfig_async",
+ "regionTag": "discoveryengine_v1_generated_AclConfigService_UpdateAclConfig_async",
"segments": [
{
- "end": 55,
+ "end": 50,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 50,
"start": 27,
"type": "SHORT"
},
@@ -228,47 +232,43 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 44,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 46,
+ "end": 47,
+ "start": 45,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 51,
+ "start": 48,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_cmek_config_service_delete_cmek_config_async.py"
+ "title": "discoveryengine_v1_generated_acl_config_service_update_acl_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient",
- "shortName": "CmekConfigServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.AclConfigServiceClient",
+ "shortName": "AclConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient.delete_cmek_config",
+ "fullName": "google.cloud.discoveryengine_v1.AclConfigServiceClient.update_acl_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.DeleteCmekConfig",
+ "fullName": "google.cloud.discoveryengine.v1.AclConfigService.UpdateAclConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
- "shortName": "CmekConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.AclConfigService",
+ "shortName": "AclConfigService"
},
- "shortName": "DeleteCmekConfig"
+ "shortName": "UpdateAclConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteCmekConfigRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateAclConfigRequest"
},
{
"name": "retry",
@@ -283,22 +283,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "delete_cmek_config"
+ "resultType": "google.cloud.discoveryengine_v1.types.AclConfig",
+ "shortName": "update_acl_config"
},
- "description": "Sample for DeleteCmekConfig",
- "file": "discoveryengine_v1_generated_cmek_config_service_delete_cmek_config_sync.py",
+ "description": "Sample for UpdateAclConfig",
+ "file": "discoveryengine_v1_generated_acl_config_service_update_acl_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CmekConfigService_DeleteCmekConfig_sync",
+ "regionTag": "discoveryengine_v1_generated_AclConfigService_UpdateAclConfig_sync",
"segments": [
{
- "end": 55,
+ "end": 50,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 50,
"start": 27,
"type": "SHORT"
},
@@ -308,48 +308,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 44,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 46,
+ "end": 47,
+ "start": 45,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 51,
+ "start": 48,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_cmek_config_service_delete_cmek_config_sync.py"
+ "title": "discoveryengine_v1_generated_acl_config_service_update_acl_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient",
- "shortName": "CmekConfigServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient",
+ "shortName": "AssistantServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient.get_cmek_config",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient.create_assistant",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.GetCmekConfig",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.CreateAssistant",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
- "shortName": "CmekConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "GetCmekConfig"
+ "shortName": "CreateAssistant"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetCmekConfigRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.CreateAssistantRequest"
},
{
"name": "retry",
@@ -364,22 +360,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.CmekConfig",
- "shortName": "get_cmek_config"
+ "resultType": "google.cloud.discoveryengine_v1.types.Assistant",
+ "shortName": "create_assistant"
},
- "description": "Sample for GetCmekConfig",
- "file": "discoveryengine_v1_generated_cmek_config_service_get_cmek_config_async.py",
+ "description": "Sample for CreateAssistant",
+ "file": "discoveryengine_v1_generated_assistant_service_create_assistant_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CmekConfigService_GetCmekConfig_async",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_CreateAssistant_async",
"segments": [
{
- "end": 51,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -389,47 +385,43 @@
"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": "discoveryengine_v1_generated_cmek_config_service_get_cmek_config_async.py"
+ "title": "discoveryengine_v1_generated_assistant_service_create_assistant_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient",
- "shortName": "CmekConfigServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient",
+ "shortName": "AssistantServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient.get_cmek_config",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient.create_assistant",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.GetCmekConfig",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.CreateAssistant",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
- "shortName": "CmekConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "GetCmekConfig"
+ "shortName": "CreateAssistant"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetCmekConfigRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.CreateAssistantRequest"
},
{
"name": "retry",
@@ -444,22 +436,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.CmekConfig",
- "shortName": "get_cmek_config"
+ "resultType": "google.cloud.discoveryengine_v1.types.Assistant",
+ "shortName": "create_assistant"
},
- "description": "Sample for GetCmekConfig",
- "file": "discoveryengine_v1_generated_cmek_config_service_get_cmek_config_sync.py",
+ "description": "Sample for CreateAssistant",
+ "file": "discoveryengine_v1_generated_assistant_service_create_assistant_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CmekConfigService_GetCmekConfig_sync",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_CreateAssistant_sync",
"segments": [
{
- "end": 51,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -469,47 +461,47 @@
"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": "discoveryengine_v1_generated_cmek_config_service_get_cmek_config_sync.py"
+ "title": "discoveryengine_v1_generated_assistant_service_create_assistant_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient",
- "shortName": "CmekConfigServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient",
+ "shortName": "AssistantServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient.list_cmek_configs",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient.delete_assistant",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.ListCmekConfigs",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.DeleteAssistant",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
- "shortName": "CmekConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "ListCmekConfigs"
+ "shortName": "DeleteAssistant"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListCmekConfigsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteAssistantRequest"
},
{
- "name": "parent",
+ "name": "name",
"type": "str"
},
{
@@ -525,22 +517,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.ListCmekConfigsResponse",
- "shortName": "list_cmek_configs"
+ "shortName": "delete_assistant"
},
- "description": "Sample for ListCmekConfigs",
- "file": "discoveryengine_v1_generated_cmek_config_service_list_cmek_configs_async.py",
+ "description": "Sample for DeleteAssistant",
+ "file": "discoveryengine_v1_generated_assistant_service_delete_assistant_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CmekConfigService_ListCmekConfigs_async",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_DeleteAssistant_async",
"segments": [
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -555,41 +546,39 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_cmek_config_service_list_cmek_configs_async.py"
+ "title": "discoveryengine_v1_generated_assistant_service_delete_assistant_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient",
- "shortName": "CmekConfigServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient",
+ "shortName": "AssistantServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient.list_cmek_configs",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient.delete_assistant",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.ListCmekConfigs",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.DeleteAssistant",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
- "shortName": "CmekConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "ListCmekConfigs"
+ "shortName": "DeleteAssistant"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListCmekConfigsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteAssistantRequest"
},
{
- "name": "parent",
+ "name": "name",
"type": "str"
},
{
@@ -605,22 +594,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.ListCmekConfigsResponse",
- "shortName": "list_cmek_configs"
+ "shortName": "delete_assistant"
},
- "description": "Sample for ListCmekConfigs",
- "file": "discoveryengine_v1_generated_cmek_config_service_list_cmek_configs_sync.py",
+ "description": "Sample for DeleteAssistant",
+ "file": "discoveryengine_v1_generated_assistant_service_delete_assistant_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CmekConfigService_ListCmekConfigs_sync",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_DeleteAssistant_sync",
"segments": [
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -635,43 +623,41 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_cmek_config_service_list_cmek_configs_sync.py"
+ "title": "discoveryengine_v1_generated_assistant_service_delete_assistant_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient",
- "shortName": "CmekConfigServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient",
+ "shortName": "AssistantServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient.update_cmek_config",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient.get_assistant",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.UpdateCmekConfig",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.GetAssistant",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
- "shortName": "CmekConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "UpdateCmekConfig"
+ "shortName": "GetAssistant"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateCmekConfigRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetAssistantRequest"
},
{
- "name": "config",
- "type": "google.cloud.discoveryengine_v1.types.CmekConfig"
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -686,22 +672,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "update_cmek_config"
+ "resultType": "google.cloud.discoveryengine_v1.types.Assistant",
+ "shortName": "get_assistant"
},
- "description": "Sample for UpdateCmekConfig",
- "file": "discoveryengine_v1_generated_cmek_config_service_update_cmek_config_async.py",
+ "description": "Sample for GetAssistant",
+ "file": "discoveryengine_v1_generated_assistant_service_get_assistant_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CmekConfigService_UpdateCmekConfig_async",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_GetAssistant_async",
"segments": [
{
- "end": 58,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 58,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -711,47 +697,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 48,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 55,
- "start": 49,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 59,
- "start": 56,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_cmek_config_service_update_cmek_config_async.py"
+ "title": "discoveryengine_v1_generated_assistant_service_get_assistant_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient",
- "shortName": "CmekConfigServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient",
+ "shortName": "AssistantServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient.update_cmek_config",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient.get_assistant",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.UpdateCmekConfig",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.GetAssistant",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
- "shortName": "CmekConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "UpdateCmekConfig"
+ "shortName": "GetAssistant"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateCmekConfigRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetAssistantRequest"
},
{
- "name": "config",
- "type": "google.cloud.discoveryengine_v1.types.CmekConfig"
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -766,22 +752,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "update_cmek_config"
+ "resultType": "google.cloud.discoveryengine_v1.types.Assistant",
+ "shortName": "get_assistant"
},
- "description": "Sample for UpdateCmekConfig",
- "file": "discoveryengine_v1_generated_cmek_config_service_update_cmek_config_sync.py",
+ "description": "Sample for GetAssistant",
+ "file": "discoveryengine_v1_generated_assistant_service_get_assistant_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CmekConfigService_UpdateCmekConfig_sync",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_GetAssistant_sync",
"segments": [
{
- "end": 58,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 58,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -791,44 +777,48 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 48,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 55,
- "start": 49,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 59,
- "start": 56,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_cmek_config_service_update_cmek_config_sync.py"
+ "title": "discoveryengine_v1_generated_assistant_service_get_assistant_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
- "shortName": "CompletionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient",
+ "shortName": "AssistantServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.complete_query",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient.list_assistants",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.CompleteQuery",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.ListAssistants",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "CompleteQuery"
+ "shortName": "ListAssistants"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CompleteQueryRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListAssistantsRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -843,14 +833,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.CompleteQueryResponse",
- "shortName": "complete_query"
+ "resultType": "google.cloud.discoveryengine_v1.services.assistant_service.pagers.ListAssistantsAsyncPager",
+ "shortName": "list_assistants"
},
- "description": "Sample for CompleteQuery",
- "file": "discoveryengine_v1_generated_completion_service_complete_query_async.py",
+ "description": "Sample for ListAssistants",
+ "file": "discoveryengine_v1_generated_assistant_service_list_assistants_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_CompleteQuery_async",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_ListAssistants_async",
"segments": [
{
"end": 52,
@@ -868,43 +858,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 49,
- "start": 47,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
"end": 53,
- "start": 50,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_completion_service_complete_query_async.py"
+ "title": "discoveryengine_v1_generated_assistant_service_list_assistants_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
- "shortName": "CompletionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient",
+ "shortName": "AssistantServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.complete_query",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient.list_assistants",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.CompleteQuery",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.ListAssistants",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "CompleteQuery"
+ "shortName": "ListAssistants"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CompleteQueryRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListAssistantsRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -919,14 +913,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.CompleteQueryResponse",
- "shortName": "complete_query"
+ "resultType": "google.cloud.discoveryengine_v1.services.assistant_service.pagers.ListAssistantsPager",
+ "shortName": "list_assistants"
},
- "description": "Sample for CompleteQuery",
- "file": "discoveryengine_v1_generated_completion_service_complete_query_sync.py",
+ "description": "Sample for ListAssistants",
+ "file": "discoveryengine_v1_generated_assistant_service_list_assistants_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_CompleteQuery_sync",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_ListAssistants_sync",
"segments": [
{
"end": 52,
@@ -944,44 +938,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 49,
- "start": 47,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
"end": 53,
- "start": 50,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_completion_service_complete_query_sync.py"
+ "title": "discoveryengine_v1_generated_assistant_service_list_assistants_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
- "shortName": "CompletionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient",
+ "shortName": "AssistantServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.import_completion_suggestions",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient.stream_assist",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.ImportCompletionSuggestions",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.StreamAssist",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "ImportCompletionSuggestions"
+ "shortName": "StreamAssist"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportCompletionSuggestionsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.StreamAssistRequest"
},
{
"name": "retry",
@@ -996,22 +990,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "import_completion_suggestions"
+ "resultType": "Iterable[google.cloud.discoveryengine_v1.types.StreamAssistResponse]",
+ "shortName": "stream_assist"
},
- "description": "Sample for ImportCompletionSuggestions",
- "file": "discoveryengine_v1_generated_completion_service_import_completion_suggestions_async.py",
+ "description": "Sample for StreamAssist",
+ "file": "discoveryengine_v1_generated_assistant_service_stream_assist_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_ImportCompletionSuggestions_async",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_StreamAssist_async",
"segments": [
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -1021,43 +1015,43 @@
"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": "discoveryengine_v1_generated_completion_service_import_completion_suggestions_async.py"
+ "title": "discoveryengine_v1_generated_assistant_service_stream_assist_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
- "shortName": "CompletionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient",
+ "shortName": "AssistantServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.import_completion_suggestions",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient.stream_assist",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.ImportCompletionSuggestions",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.StreamAssist",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "ImportCompletionSuggestions"
+ "shortName": "StreamAssist"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportCompletionSuggestionsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.StreamAssistRequest"
},
{
"name": "retry",
@@ -1072,22 +1066,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "import_completion_suggestions"
+ "resultType": "Iterable[google.cloud.discoveryengine_v1.types.StreamAssistResponse]",
+ "shortName": "stream_assist"
},
- "description": "Sample for ImportCompletionSuggestions",
- "file": "discoveryengine_v1_generated_completion_service_import_completion_suggestions_sync.py",
+ "description": "Sample for StreamAssist",
+ "file": "discoveryengine_v1_generated_assistant_service_stream_assist_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_ImportCompletionSuggestions_sync",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_StreamAssist_sync",
"segments": [
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -1097,44 +1091,52 @@
"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": "discoveryengine_v1_generated_completion_service_import_completion_suggestions_sync.py"
+ "title": "discoveryengine_v1_generated_assistant_service_stream_assist_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
- "shortName": "CompletionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient",
+ "shortName": "AssistantServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.import_suggestion_deny_list_entries",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceAsyncClient.update_assistant",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.ImportSuggestionDenyListEntries",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.UpdateAssistant",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "ImportSuggestionDenyListEntries"
+ "shortName": "UpdateAssistant"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportSuggestionDenyListEntriesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateAssistantRequest"
+ },
+ {
+ "name": "assistant",
+ "type": "google.cloud.discoveryengine_v1.types.Assistant"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -1149,22 +1151,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "import_suggestion_deny_list_entries"
+ "resultType": "google.cloud.discoveryengine_v1.types.Assistant",
+ "shortName": "update_assistant"
},
- "description": "Sample for ImportSuggestionDenyListEntries",
- "file": "discoveryengine_v1_generated_completion_service_import_suggestion_deny_list_entries_async.py",
+ "description": "Sample for UpdateAssistant",
+ "file": "discoveryengine_v1_generated_assistant_service_update_assistant_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_ImportSuggestionDenyListEntries_async",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_UpdateAssistant_async",
"segments": [
{
- "end": 60,
+ "end": 54,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 54,
"start": 27,
"type": "SHORT"
},
@@ -1174,43 +1176,51 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 50,
+ "end": 48,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 57,
- "start": 51,
+ "end": 51,
+ "start": 49,
"type": "REQUEST_EXECUTION"
},
{
- "end": 61,
- "start": 58,
+ "end": 55,
+ "start": 52,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_completion_service_import_suggestion_deny_list_entries_async.py"
+ "title": "discoveryengine_v1_generated_assistant_service_update_assistant_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
- "shortName": "CompletionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient",
+ "shortName": "AssistantServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.import_suggestion_deny_list_entries",
+ "fullName": "google.cloud.discoveryengine_v1.AssistantServiceClient.update_assistant",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.ImportSuggestionDenyListEntries",
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService.UpdateAssistant",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.AssistantService",
+ "shortName": "AssistantService"
},
- "shortName": "ImportSuggestionDenyListEntries"
+ "shortName": "UpdateAssistant"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportSuggestionDenyListEntriesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateAssistantRequest"
+ },
+ {
+ "name": "assistant",
+ "type": "google.cloud.discoveryengine_v1.types.Assistant"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -1225,22 +1235,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "import_suggestion_deny_list_entries"
+ "resultType": "google.cloud.discoveryengine_v1.types.Assistant",
+ "shortName": "update_assistant"
},
- "description": "Sample for ImportSuggestionDenyListEntries",
- "file": "discoveryengine_v1_generated_completion_service_import_suggestion_deny_list_entries_sync.py",
+ "description": "Sample for UpdateAssistant",
+ "file": "discoveryengine_v1_generated_assistant_service_update_assistant_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_ImportSuggestionDenyListEntries_sync",
+ "regionTag": "discoveryengine_v1_generated_AssistantService_UpdateAssistant_sync",
"segments": [
{
- "end": 60,
+ "end": 54,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 54,
"start": 27,
"type": "SHORT"
},
@@ -1250,44 +1260,48 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 50,
+ "end": 48,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 57,
- "start": 51,
+ "end": 51,
+ "start": 49,
"type": "REQUEST_EXECUTION"
},
{
- "end": 61,
- "start": 58,
+ "end": 55,
+ "start": 52,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_completion_service_import_suggestion_deny_list_entries_sync.py"
+ "title": "discoveryengine_v1_generated_assistant_service_update_assistant_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
- "shortName": "CompletionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient",
+ "shortName": "CmekConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.purge_completion_suggestions",
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient.delete_cmek_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.PurgeCompletionSuggestions",
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.DeleteCmekConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
+ "shortName": "CmekConfigService"
},
- "shortName": "PurgeCompletionSuggestions"
+ "shortName": "DeleteCmekConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeCompletionSuggestionsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteCmekConfigRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -1303,13 +1317,13 @@
}
],
"resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "purge_completion_suggestions"
+ "shortName": "delete_cmek_config"
},
- "description": "Sample for PurgeCompletionSuggestions",
- "file": "discoveryengine_v1_generated_completion_service_purge_completion_suggestions_async.py",
+ "description": "Sample for DeleteCmekConfig",
+ "file": "discoveryengine_v1_generated_cmek_config_service_delete_cmek_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_PurgeCompletionSuggestions_async",
+ "regionTag": "discoveryengine_v1_generated_CmekConfigService_DeleteCmekConfig_async",
"segments": [
{
"end": 55,
@@ -1342,28 +1356,32 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_completion_service_purge_completion_suggestions_async.py"
+ "title": "discoveryengine_v1_generated_cmek_config_service_delete_cmek_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
- "shortName": "CompletionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient",
+ "shortName": "CmekConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.purge_completion_suggestions",
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient.delete_cmek_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.PurgeCompletionSuggestions",
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.DeleteCmekConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
+ "shortName": "CmekConfigService"
},
- "shortName": "PurgeCompletionSuggestions"
+ "shortName": "DeleteCmekConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeCompletionSuggestionsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteCmekConfigRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -1379,13 +1397,13 @@
}
],
"resultType": "google.api_core.operation.Operation",
- "shortName": "purge_completion_suggestions"
+ "shortName": "delete_cmek_config"
},
- "description": "Sample for PurgeCompletionSuggestions",
- "file": "discoveryengine_v1_generated_completion_service_purge_completion_suggestions_sync.py",
+ "description": "Sample for DeleteCmekConfig",
+ "file": "discoveryengine_v1_generated_cmek_config_service_delete_cmek_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_PurgeCompletionSuggestions_sync",
+ "regionTag": "discoveryengine_v1_generated_CmekConfigService_DeleteCmekConfig_sync",
"segments": [
{
"end": 55,
@@ -1418,29 +1436,33 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_completion_service_purge_completion_suggestions_sync.py"
+ "title": "discoveryengine_v1_generated_cmek_config_service_delete_cmek_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
- "shortName": "CompletionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient",
+ "shortName": "CmekConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.purge_suggestion_deny_list_entries",
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient.get_cmek_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.PurgeSuggestionDenyListEntries",
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.GetCmekConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
+ "shortName": "CmekConfigService"
},
- "shortName": "PurgeSuggestionDenyListEntries"
+ "shortName": "GetCmekConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeSuggestionDenyListEntriesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetCmekConfigRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -1455,22 +1477,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "purge_suggestion_deny_list_entries"
+ "resultType": "google.cloud.discoveryengine_v1.types.CmekConfig",
+ "shortName": "get_cmek_config"
},
- "description": "Sample for PurgeSuggestionDenyListEntries",
- "file": "discoveryengine_v1_generated_completion_service_purge_suggestion_deny_list_entries_async.py",
+ "description": "Sample for GetCmekConfig",
+ "file": "discoveryengine_v1_generated_cmek_config_service_get_cmek_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_PurgeSuggestionDenyListEntries_async",
+ "regionTag": "discoveryengine_v1_generated_CmekConfigService_GetCmekConfig_async",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -1485,38 +1507,42 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_completion_service_purge_suggestion_deny_list_entries_async.py"
+ "title": "discoveryengine_v1_generated_cmek_config_service_get_cmek_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
- "shortName": "CompletionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient",
+ "shortName": "CmekConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.purge_suggestion_deny_list_entries",
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient.get_cmek_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService.PurgeSuggestionDenyListEntries",
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.GetCmekConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.CompletionService",
- "shortName": "CompletionService"
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
+ "shortName": "CmekConfigService"
},
- "shortName": "PurgeSuggestionDenyListEntries"
+ "shortName": "GetCmekConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeSuggestionDenyListEntriesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetCmekConfigRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -1531,22 +1557,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "purge_suggestion_deny_list_entries"
+ "resultType": "google.cloud.discoveryengine_v1.types.CmekConfig",
+ "shortName": "get_cmek_config"
},
- "description": "Sample for PurgeSuggestionDenyListEntries",
- "file": "discoveryengine_v1_generated_completion_service_purge_suggestion_deny_list_entries_sync.py",
+ "description": "Sample for GetCmekConfig",
+ "file": "discoveryengine_v1_generated_cmek_config_service_get_cmek_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_CompletionService_PurgeSuggestionDenyListEntries_sync",
+ "regionTag": "discoveryengine_v1_generated_CmekConfigService_GetCmekConfig_sync",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -1561,52 +1587,44 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_completion_service_purge_suggestion_deny_list_entries_sync.py"
+ "title": "discoveryengine_v1_generated_cmek_config_service_get_cmek_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
- "shortName": "ControlServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient",
+ "shortName": "CmekConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.create_control",
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient.list_cmek_configs",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.CreateControl",
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.ListCmekConfigs",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
+ "shortName": "CmekConfigService"
},
- "shortName": "CreateControl"
+ "shortName": "ListCmekConfigs"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateControlRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListCmekConfigsRequest"
},
{
"name": "parent",
"type": "str"
},
- {
- "name": "control",
- "type": "google.cloud.discoveryengine_v1.types.Control"
- },
- {
- "name": "control_id",
- "type": "str"
- },
{
"name": "retry",
"type": "google.api_core.retry.Retry"
@@ -1620,22 +1638,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Control",
- "shortName": "create_control"
+ "resultType": "google.cloud.discoveryengine_v1.types.ListCmekConfigsResponse",
+ "shortName": "list_cmek_configs"
},
- "description": "Sample for CreateControl",
- "file": "discoveryengine_v1_generated_control_service_create_control_async.py",
+ "description": "Sample for ListCmekConfigs",
+ "file": "discoveryengine_v1_generated_cmek_config_service_list_cmek_configs_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_CreateControl_async",
+ "regionTag": "discoveryengine_v1_generated_CmekConfigService_ListCmekConfigs_async",
"segments": [
{
- "end": 60,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -1645,56 +1663,48 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 54,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 57,
- "start": 55,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 61,
- "start": 58,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_create_control_async.py"
+ "title": "discoveryengine_v1_generated_cmek_config_service_list_cmek_configs_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
- "shortName": "ControlServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient",
+ "shortName": "CmekConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.create_control",
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient.list_cmek_configs",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.CreateControl",
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.ListCmekConfigs",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
+ "shortName": "CmekConfigService"
},
- "shortName": "CreateControl"
+ "shortName": "ListCmekConfigs"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateControlRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListCmekConfigsRequest"
},
{
"name": "parent",
"type": "str"
},
- {
- "name": "control",
- "type": "google.cloud.discoveryengine_v1.types.Control"
- },
- {
- "name": "control_id",
- "type": "str"
- },
{
"name": "retry",
"type": "google.api_core.retry.Retry"
@@ -1708,22 +1718,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Control",
- "shortName": "create_control"
+ "resultType": "google.cloud.discoveryengine_v1.types.ListCmekConfigsResponse",
+ "shortName": "list_cmek_configs"
},
- "description": "Sample for CreateControl",
- "file": "discoveryengine_v1_generated_control_service_create_control_sync.py",
+ "description": "Sample for ListCmekConfigs",
+ "file": "discoveryengine_v1_generated_cmek_config_service_list_cmek_configs_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_CreateControl_sync",
+ "regionTag": "discoveryengine_v1_generated_CmekConfigService_ListCmekConfigs_sync",
"segments": [
{
- "end": 60,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -1733,48 +1743,48 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 54,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 57,
- "start": 55,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 61,
- "start": 58,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_create_control_sync.py"
+ "title": "discoveryengine_v1_generated_cmek_config_service_list_cmek_configs_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
- "shortName": "ControlServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient",
+ "shortName": "CmekConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.delete_control",
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceAsyncClient.update_cmek_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.DeleteControl",
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.UpdateCmekConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
+ "shortName": "CmekConfigService"
},
- "shortName": "DeleteControl"
+ "shortName": "UpdateCmekConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteControlRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateCmekConfigRequest"
},
{
- "name": "name",
- "type": "str"
+ "name": "config",
+ "type": "google.cloud.discoveryengine_v1.types.CmekConfig"
},
{
"name": "retry",
@@ -1789,21 +1799,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_control"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "update_cmek_config"
},
- "description": "Sample for DeleteControl",
- "file": "discoveryengine_v1_generated_control_service_delete_control_async.py",
+ "description": "Sample for UpdateCmekConfig",
+ "file": "discoveryengine_v1_generated_cmek_config_service_update_cmek_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_DeleteControl_async",
+ "regionTag": "discoveryengine_v1_generated_CmekConfigService_UpdateCmekConfig_async",
"segments": [
{
- "end": 49,
+ "end": 58,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 58,
"start": 27,
"type": "SHORT"
},
@@ -1813,45 +1824,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 48,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "start": 46,
+ "end": 55,
+ "start": 49,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 59,
+ "start": 56,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_delete_control_async.py"
+ "title": "discoveryengine_v1_generated_cmek_config_service_update_cmek_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
- "shortName": "ControlServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient",
+ "shortName": "CmekConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.delete_control",
+ "fullName": "google.cloud.discoveryengine_v1.CmekConfigServiceClient.update_cmek_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.DeleteControl",
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService.UpdateCmekConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CmekConfigService",
+ "shortName": "CmekConfigService"
},
- "shortName": "DeleteControl"
+ "shortName": "UpdateCmekConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteControlRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateCmekConfigRequest"
},
{
- "name": "name",
- "type": "str"
+ "name": "config",
+ "type": "google.cloud.discoveryengine_v1.types.CmekConfig"
},
{
"name": "retry",
@@ -1866,21 +1879,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_control"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "update_cmek_config"
},
- "description": "Sample for DeleteControl",
- "file": "discoveryengine_v1_generated_control_service_delete_control_sync.py",
+ "description": "Sample for UpdateCmekConfig",
+ "file": "discoveryengine_v1_generated_cmek_config_service_update_cmek_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_DeleteControl_sync",
+ "regionTag": "discoveryengine_v1_generated_CmekConfigService_UpdateCmekConfig_sync",
"segments": [
{
- "end": 49,
+ "end": 58,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 58,
"start": 27,
"type": "SHORT"
},
@@ -1890,42 +1904,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 48,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "start": 46,
+ "end": 55,
+ "start": 49,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 59,
+ "start": 56,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_delete_control_sync.py"
+ "title": "discoveryengine_v1_generated_cmek_config_service_update_cmek_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
- "shortName": "ControlServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceAsyncClient",
+ "shortName": "CollectionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.get_control",
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceAsyncClient.delete_collection",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.GetControl",
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService.DeleteCollection",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService",
+ "shortName": "CollectionService"
},
- "shortName": "GetControl"
+ "shortName": "DeleteCollection"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetControlRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteCollectionRequest"
},
{
"name": "name",
@@ -1944,22 +1960,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Control",
- "shortName": "get_control"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "delete_collection"
},
- "description": "Sample for GetControl",
- "file": "discoveryengine_v1_generated_control_service_get_control_async.py",
+ "description": "Sample for DeleteCollection",
+ "file": "discoveryengine_v1_generated_collection_service_delete_collection_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_GetControl_async",
+ "regionTag": "discoveryengine_v1_generated_CollectionService_DeleteCollection_async",
"segments": [
{
- "end": 51,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -1974,38 +1990,38 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_get_control_async.py"
+ "title": "discoveryengine_v1_generated_collection_service_delete_collection_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
- "shortName": "ControlServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceClient",
+ "shortName": "CollectionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.get_control",
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceClient.delete_collection",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.GetControl",
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService.DeleteCollection",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService",
+ "shortName": "CollectionService"
},
- "shortName": "GetControl"
+ "shortName": "DeleteCollection"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetControlRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteCollectionRequest"
},
{
"name": "name",
@@ -2024,22 +2040,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Control",
- "shortName": "get_control"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "delete_collection"
},
- "description": "Sample for GetControl",
- "file": "discoveryengine_v1_generated_control_service_get_control_sync.py",
+ "description": "Sample for DeleteCollection",
+ "file": "discoveryengine_v1_generated_collection_service_delete_collection_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_GetControl_sync",
+ "regionTag": "discoveryengine_v1_generated_CollectionService_DeleteCollection_sync",
"segments": [
{
- "end": 51,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -2054,42 +2070,42 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_get_control_sync.py"
+ "title": "discoveryengine_v1_generated_collection_service_delete_collection_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
- "shortName": "ControlServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceAsyncClient",
+ "shortName": "CollectionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.list_controls",
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceAsyncClient.get_iam_policy",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.ListControls",
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService.GetIamPolicy",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService",
+ "shortName": "CollectionService"
},
- "shortName": "ListControls"
+ "shortName": "GetIamPolicy"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListControlsRequest"
+ "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest"
},
{
- "name": "parent",
+ "name": "resource",
"type": "str"
},
{
@@ -2105,14 +2121,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.control_service.pagers.ListControlsAsyncPager",
- "shortName": "list_controls"
+ "resultType": "google.iam.v1.policy_pb2.Policy",
+ "shortName": "get_iam_policy"
},
- "description": "Sample for ListControls",
- "file": "discoveryengine_v1_generated_control_service_list_controls_async.py",
+ "description": "Sample for GetIamPolicy",
+ "file": "discoveryengine_v1_generated_collection_service_get_iam_policy_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_ListControls_async",
+ "regionTag": "discoveryengine_v1_generated_CollectionService_GetIamPolicy_async",
"segments": [
{
"end": 52,
@@ -2125,51 +2141,51 @@
"type": "SHORT"
},
{
- "end": 40,
- "start": 38,
+ "end": 41,
+ "start": 39,
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
- "start": 41,
+ "end": 46,
+ "start": 42,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 49,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
"end": 53,
- "start": 49,
+ "start": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_list_controls_async.py"
+ "title": "discoveryengine_v1_generated_collection_service_get_iam_policy_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
- "shortName": "ControlServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceClient",
+ "shortName": "CollectionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.list_controls",
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceClient.get_iam_policy",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.ListControls",
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService.GetIamPolicy",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService",
+ "shortName": "CollectionService"
},
- "shortName": "ListControls"
+ "shortName": "GetIamPolicy"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListControlsRequest"
+ "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest"
},
{
- "name": "parent",
+ "name": "resource",
"type": "str"
},
{
@@ -2185,14 +2201,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.control_service.pagers.ListControlsPager",
- "shortName": "list_controls"
+ "resultType": "google.iam.v1.policy_pb2.Policy",
+ "shortName": "get_iam_policy"
},
- "description": "Sample for ListControls",
- "file": "discoveryengine_v1_generated_control_service_list_controls_sync.py",
+ "description": "Sample for GetIamPolicy",
+ "file": "discoveryengine_v1_generated_collection_service_get_iam_policy_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_ListControls_sync",
+ "regionTag": "discoveryengine_v1_generated_CollectionService_GetIamPolicy_sync",
"segments": [
{
"end": 52,
@@ -2205,57 +2221,53 @@
"type": "SHORT"
},
{
- "end": 40,
- "start": 38,
+ "end": 41,
+ "start": 39,
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
- "start": 41,
+ "end": 46,
+ "start": 42,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 49,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
"end": 53,
- "start": 49,
+ "start": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_list_controls_sync.py"
+ "title": "discoveryengine_v1_generated_collection_service_get_iam_policy_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
- "shortName": "ControlServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceAsyncClient",
+ "shortName": "CollectionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.update_control",
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceAsyncClient.set_iam_policy",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.UpdateControl",
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService.SetIamPolicy",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService",
+ "shortName": "CollectionService"
},
- "shortName": "UpdateControl"
+ "shortName": "SetIamPolicy"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateControlRequest"
- },
- {
- "name": "control",
- "type": "google.cloud.discoveryengine_v1.types.Control"
+ "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "resource",
+ "type": "str"
},
{
"name": "retry",
@@ -2270,76 +2282,72 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Control",
- "shortName": "update_control"
+ "resultType": "google.iam.v1.policy_pb2.Policy",
+ "shortName": "set_iam_policy"
},
- "description": "Sample for UpdateControl",
- "file": "discoveryengine_v1_generated_control_service_update_control_async.py",
+ "description": "Sample for SetIamPolicy",
+ "file": "discoveryengine_v1_generated_collection_service_set_iam_policy_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_UpdateControl_async",
+ "regionTag": "discoveryengine_v1_generated_CollectionService_SetIamPolicy_async",
"segments": [
{
- "end": 58,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 58,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
{
- "end": 40,
- "start": 38,
+ "end": 41,
+ "start": 39,
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 52,
- "start": 41,
+ "end": 46,
+ "start": 42,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 55,
- "start": 53,
+ "end": 49,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
- "end": 59,
- "start": 56,
+ "end": 53,
+ "start": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_update_control_async.py"
+ "title": "discoveryengine_v1_generated_collection_service_set_iam_policy_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
- "shortName": "ControlServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceClient",
+ "shortName": "CollectionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.update_control",
+ "fullName": "google.cloud.discoveryengine_v1.CollectionServiceClient.set_iam_policy",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService.UpdateControl",
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService.SetIamPolicy",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ControlService",
- "shortName": "ControlService"
+ "fullName": "google.cloud.discoveryengine.v1.CollectionService",
+ "shortName": "CollectionService"
},
- "shortName": "UpdateControl"
+ "shortName": "SetIamPolicy"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateControlRequest"
- },
- {
- "name": "control",
- "type": "google.cloud.discoveryengine_v1.types.Control"
+ "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "resource",
+ "type": "str"
},
{
"name": "retry",
@@ -2354,69 +2362,69 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Control",
- "shortName": "update_control"
+ "resultType": "google.iam.v1.policy_pb2.Policy",
+ "shortName": "set_iam_policy"
},
- "description": "Sample for UpdateControl",
- "file": "discoveryengine_v1_generated_control_service_update_control_sync.py",
+ "description": "Sample for SetIamPolicy",
+ "file": "discoveryengine_v1_generated_collection_service_set_iam_policy_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ControlService_UpdateControl_sync",
+ "regionTag": "discoveryengine_v1_generated_CollectionService_SetIamPolicy_sync",
"segments": [
{
- "end": 58,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 58,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
{
- "end": 40,
- "start": 38,
+ "end": 41,
+ "start": 39,
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 52,
- "start": 41,
+ "end": 46,
+ "start": 42,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 55,
- "start": 53,
+ "end": 49,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
- "end": 59,
- "start": 56,
+ "end": 53,
+ "start": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_control_service_update_control_sync.py"
+ "title": "discoveryengine_v1_generated_collection_service_set_iam_policy_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
+ "shortName": "CompletionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.answer_query",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.advanced_complete_query",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.AnswerQuery",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "AnswerQuery"
+ "shortName": "AdvancedCompleteQuery"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.AnswerQueryRequest"
+ "type": "google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryRequest"
},
{
"name": "retry",
@@ -2431,22 +2439,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.AnswerQueryResponse",
- "shortName": "answer_query"
+ "resultType": "google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryResponse",
+ "shortName": "advanced_complete_query"
},
- "description": "Sample for AnswerQuery",
- "file": "discoveryengine_v1_generated_conversational_search_service_answer_query_async.py",
+ "description": "Sample for AdvancedCompleteQuery",
+ "file": "discoveryengine_v1_generated_completion_service_advanced_complete_query_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_AnswerQuery_async",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_AdvancedCompleteQuery_async",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -2456,43 +2464,43 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 46,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 50,
+ "end": 49,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 53,
+ "start": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_answer_query_async.py"
+ "title": "discoveryengine_v1_generated_completion_service_advanced_complete_query_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
+ "shortName": "CompletionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.answer_query",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.advanced_complete_query",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.AnswerQuery",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.AdvancedCompleteQuery",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "AnswerQuery"
+ "shortName": "AdvancedCompleteQuery"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.AnswerQueryRequest"
+ "type": "google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryRequest"
},
{
"name": "retry",
@@ -2507,22 +2515,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.AnswerQueryResponse",
- "shortName": "answer_query"
+ "resultType": "google.cloud.discoveryengine_v1.types.AdvancedCompleteQueryResponse",
+ "shortName": "advanced_complete_query"
},
- "description": "Sample for AnswerQuery",
- "file": "discoveryengine_v1_generated_conversational_search_service_answer_query_sync.py",
+ "description": "Sample for AdvancedCompleteQuery",
+ "file": "discoveryengine_v1_generated_completion_service_advanced_complete_query_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_AnswerQuery_sync",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_AdvancedCompleteQuery_sync",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -2532,52 +2540,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 46,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 50,
+ "end": 49,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 53,
+ "start": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_answer_query_sync.py"
+ "title": "discoveryengine_v1_generated_completion_service_advanced_complete_query_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
+ "shortName": "CompletionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.converse_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.complete_query",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.CompleteQuery",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "ConverseConversation"
+ "shortName": "CompleteQuery"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ConverseConversationRequest"
- },
- {
- "name": "name",
- "type": "str"
- },
- {
- "name": "query",
- "type": "google.cloud.discoveryengine_v1.types.TextInput"
+ "type": "google.cloud.discoveryengine_v1.types.CompleteQueryRequest"
},
{
"name": "retry",
@@ -2592,22 +2592,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.ConverseConversationResponse",
- "shortName": "converse_conversation"
+ "resultType": "google.cloud.discoveryengine_v1.types.CompleteQueryResponse",
+ "shortName": "complete_query"
},
- "description": "Sample for ConverseConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py",
+ "description": "Sample for CompleteQuery",
+ "file": "discoveryengine_v1_generated_completion_service_complete_query_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_async",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_CompleteQuery_async",
"segments": [
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -2617,51 +2617,43 @@
"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": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py"
+ "title": "discoveryengine_v1_generated_completion_service_complete_query_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
+ "shortName": "CompletionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.converse_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.complete_query",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.CompleteQuery",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "ConverseConversation"
+ "shortName": "CompleteQuery"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ConverseConversationRequest"
- },
- {
- "name": "name",
- "type": "str"
- },
- {
- "name": "query",
- "type": "google.cloud.discoveryengine_v1.types.TextInput"
+ "type": "google.cloud.discoveryengine_v1.types.CompleteQueryRequest"
},
{
"name": "retry",
@@ -2676,22 +2668,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.ConverseConversationResponse",
- "shortName": "converse_conversation"
+ "resultType": "google.cloud.discoveryengine_v1.types.CompleteQueryResponse",
+ "shortName": "complete_query"
},
- "description": "Sample for ConverseConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py",
+ "description": "Sample for CompleteQuery",
+ "file": "discoveryengine_v1_generated_completion_service_complete_query_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_sync",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_CompleteQuery_sync",
"segments": [
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -2701,52 +2693,44 @@
"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": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py"
+ "title": "discoveryengine_v1_generated_completion_service_complete_query_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
+ "shortName": "CompletionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.create_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.import_completion_suggestions",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateConversation",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.ImportCompletionSuggestions",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "CreateConversation"
+ "shortName": "ImportCompletionSuggestions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateConversationRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "conversation",
- "type": "google.cloud.discoveryengine_v1.types.Conversation"
+ "type": "google.cloud.discoveryengine_v1.types.ImportCompletionSuggestionsRequest"
},
{
"name": "retry",
@@ -2761,22 +2745,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
- "shortName": "create_conversation"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "import_completion_suggestions"
},
- "description": "Sample for CreateConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py",
+ "description": "Sample for ImportCompletionSuggestions",
+ "file": "discoveryengine_v1_generated_completion_service_import_completion_suggestions_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_async",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_ImportCompletionSuggestions_async",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -2786,51 +2770,43 @@
"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": "discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py"
+ "title": "discoveryengine_v1_generated_completion_service_import_completion_suggestions_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
+ "shortName": "CompletionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.create_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.import_completion_suggestions",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateConversation",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.ImportCompletionSuggestions",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "CreateConversation"
+ "shortName": "ImportCompletionSuggestions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateConversationRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "conversation",
- "type": "google.cloud.discoveryengine_v1.types.Conversation"
+ "type": "google.cloud.discoveryengine_v1.types.ImportCompletionSuggestionsRequest"
},
{
"name": "retry",
@@ -2845,22 +2821,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
- "shortName": "create_conversation"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "import_completion_suggestions"
},
- "description": "Sample for CreateConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py",
+ "description": "Sample for ImportCompletionSuggestions",
+ "file": "discoveryengine_v1_generated_completion_service_import_completion_suggestions_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_sync",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_ImportCompletionSuggestions_sync",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -2870,52 +2846,44 @@
"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": "discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py"
+ "title": "discoveryengine_v1_generated_completion_service_import_completion_suggestions_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
+ "shortName": "CompletionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.create_session",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.import_suggestion_deny_list_entries",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateSession",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.ImportSuggestionDenyListEntries",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "CreateSession"
+ "shortName": "ImportSuggestionDenyListEntries"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateSessionRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "session",
- "type": "google.cloud.discoveryengine_v1.types.Session"
+ "type": "google.cloud.discoveryengine_v1.types.ImportSuggestionDenyListEntriesRequest"
},
{
"name": "retry",
@@ -2930,22 +2898,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "create_session"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "import_suggestion_deny_list_entries"
},
- "description": "Sample for CreateSession",
- "file": "discoveryengine_v1_generated_conversational_search_service_create_session_async.py",
+ "description": "Sample for ImportSuggestionDenyListEntries",
+ "file": "discoveryengine_v1_generated_completion_service_import_suggestion_deny_list_entries_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateSession_async",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_ImportSuggestionDenyListEntries_async",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -2955,51 +2923,43 @@
"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": "discoveryengine_v1_generated_conversational_search_service_create_session_async.py"
+ "title": "discoveryengine_v1_generated_completion_service_import_suggestion_deny_list_entries_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
+ "shortName": "CompletionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.create_session",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.import_suggestion_deny_list_entries",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateSession",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.ImportSuggestionDenyListEntries",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "CreateSession"
+ "shortName": "ImportSuggestionDenyListEntries"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateSessionRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "session",
- "type": "google.cloud.discoveryengine_v1.types.Session"
+ "type": "google.cloud.discoveryengine_v1.types.ImportSuggestionDenyListEntriesRequest"
},
{
"name": "retry",
@@ -3014,22 +2974,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "create_session"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "import_suggestion_deny_list_entries"
},
- "description": "Sample for CreateSession",
- "file": "discoveryengine_v1_generated_conversational_search_service_create_session_sync.py",
+ "description": "Sample for ImportSuggestionDenyListEntries",
+ "file": "discoveryengine_v1_generated_completion_service_import_suggestion_deny_list_entries_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateSession_sync",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_ImportSuggestionDenyListEntries_sync",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -3039,48 +2999,44 @@
"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": "discoveryengine_v1_generated_conversational_search_service_create_session_sync.py"
+ "title": "discoveryengine_v1_generated_completion_service_import_suggestion_deny_list_entries_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
+ "shortName": "CompletionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.delete_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.purge_completion_suggestions",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteConversation",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.PurgeCompletionSuggestions",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "DeleteConversation"
+ "shortName": "PurgeCompletionSuggestions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteConversationRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.PurgeCompletionSuggestionsRequest"
},
{
"name": "retry",
@@ -3095,21 +3051,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_conversation"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "purge_completion_suggestions"
},
- "description": "Sample for DeleteConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py",
+ "description": "Sample for PurgeCompletionSuggestions",
+ "file": "discoveryengine_v1_generated_completion_service_purge_completion_suggestions_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_async",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_PurgeCompletionSuggestions_async",
"segments": [
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -3124,40 +3081,38 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py"
+ "title": "discoveryengine_v1_generated_completion_service_purge_completion_suggestions_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
+ "shortName": "CompletionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.delete_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.purge_completion_suggestions",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteConversation",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.PurgeCompletionSuggestions",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "DeleteConversation"
+ "shortName": "PurgeCompletionSuggestions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteConversationRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.PurgeCompletionSuggestionsRequest"
},
{
"name": "retry",
@@ -3172,21 +3127,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_conversation"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "purge_completion_suggestions"
},
- "description": "Sample for DeleteConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py",
+ "description": "Sample for PurgeCompletionSuggestions",
+ "file": "discoveryengine_v1_generated_completion_service_purge_completion_suggestions_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_sync",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_PurgeCompletionSuggestions_sync",
"segments": [
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -3201,41 +3157,39 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py"
+ "title": "discoveryengine_v1_generated_completion_service_purge_completion_suggestions_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient",
+ "shortName": "CompletionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.delete_session",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceAsyncClient.purge_suggestion_deny_list_entries",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteSession",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.PurgeSuggestionDenyListEntries",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "DeleteSession"
+ "shortName": "PurgeSuggestionDenyListEntries"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteSessionRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.PurgeSuggestionDenyListEntriesRequest"
},
{
"name": "retry",
@@ -3250,21 +3204,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_session"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "purge_suggestion_deny_list_entries"
},
- "description": "Sample for DeleteSession",
- "file": "discoveryengine_v1_generated_conversational_search_service_delete_session_async.py",
+ "description": "Sample for PurgeSuggestionDenyListEntries",
+ "file": "discoveryengine_v1_generated_completion_service_purge_suggestion_deny_list_entries_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteSession_async",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_PurgeSuggestionDenyListEntries_async",
"segments": [
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -3279,40 +3234,38 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_delete_session_async.py"
+ "title": "discoveryengine_v1_generated_completion_service_purge_suggestion_deny_list_entries_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient",
+ "shortName": "CompletionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.delete_session",
+ "fullName": "google.cloud.discoveryengine_v1.CompletionServiceClient.purge_suggestion_deny_list_entries",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteSession",
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService.PurgeSuggestionDenyListEntries",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.CompletionService",
+ "shortName": "CompletionService"
},
- "shortName": "DeleteSession"
+ "shortName": "PurgeSuggestionDenyListEntries"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteSessionRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.PurgeSuggestionDenyListEntriesRequest"
},
{
"name": "retry",
@@ -3327,21 +3280,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_session"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "purge_suggestion_deny_list_entries"
},
- "description": "Sample for DeleteSession",
- "file": "discoveryengine_v1_generated_conversational_search_service_delete_session_sync.py",
+ "description": "Sample for PurgeSuggestionDenyListEntries",
+ "file": "discoveryengine_v1_generated_completion_service_purge_suggestion_deny_list_entries_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteSession_sync",
+ "regionTag": "discoveryengine_v1_generated_CompletionService_PurgeSuggestionDenyListEntries_sync",
"segments": [
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -3356,40 +3310,50 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_delete_session_sync.py"
+ "title": "discoveryengine_v1_generated_completion_service_purge_suggestion_deny_list_entries_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
+ "shortName": "ControlServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.get_answer",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.create_control",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetAnswer",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.CreateControl",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "GetAnswer"
+ "shortName": "CreateControl"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetAnswerRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateControlRequest"
},
{
- "name": "name",
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "control",
+ "type": "google.cloud.discoveryengine_v1.types.Control"
+ },
+ {
+ "name": "control_id",
"type": "str"
},
{
@@ -3405,22 +3369,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Answer",
- "shortName": "get_answer"
+ "resultType": "google.cloud.discoveryengine_v1.types.Control",
+ "shortName": "create_control"
},
- "description": "Sample for GetAnswer",
- "file": "discoveryengine_v1_generated_conversational_search_service_get_answer_async.py",
+ "description": "Sample for CreateControl",
+ "file": "discoveryengine_v1_generated_control_service_create_control_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetAnswer_async",
+ "regionTag": "discoveryengine_v1_generated_ControlService_CreateControl_async",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -3430,46 +3394,54 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 54,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 57,
+ "start": 55,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 61,
+ "start": 58,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_get_answer_async.py"
+ "title": "discoveryengine_v1_generated_control_service_create_control_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
+ "shortName": "ControlServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.get_answer",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.create_control",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetAnswer",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.CreateControl",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "GetAnswer"
+ "shortName": "CreateControl"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetAnswerRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateControlRequest"
},
{
- "name": "name",
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "control",
+ "type": "google.cloud.discoveryengine_v1.types.Control"
+ },
+ {
+ "name": "control_id",
"type": "str"
},
{
@@ -3485,22 +3457,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Answer",
- "shortName": "get_answer"
+ "resultType": "google.cloud.discoveryengine_v1.types.Control",
+ "shortName": "create_control"
},
- "description": "Sample for GetAnswer",
- "file": "discoveryengine_v1_generated_conversational_search_service_get_answer_sync.py",
+ "description": "Sample for CreateControl",
+ "file": "discoveryengine_v1_generated_control_service_create_control_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetAnswer_sync",
+ "regionTag": "discoveryengine_v1_generated_ControlService_CreateControl_sync",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -3510,44 +3482,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 54,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 57,
+ "start": 55,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 61,
+ "start": 58,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_get_answer_sync.py"
+ "title": "discoveryengine_v1_generated_control_service_create_control_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
+ "shortName": "ControlServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.get_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.delete_control",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetConversation",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.DeleteControl",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "GetConversation"
+ "shortName": "DeleteControl"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetConversationRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteControlRequest"
},
{
"name": "name",
@@ -3566,22 +3538,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
- "shortName": "get_conversation"
+ "shortName": "delete_control"
},
- "description": "Sample for GetConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py",
+ "description": "Sample for DeleteControl",
+ "file": "discoveryengine_v1_generated_control_service_delete_control_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetConversation_async",
+ "regionTag": "discoveryengine_v1_generated_ControlService_DeleteControl_async",
"segments": [
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -3596,38 +3567,36 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py"
+ "title": "discoveryengine_v1_generated_control_service_delete_control_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
+ "shortName": "ControlServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.get_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.delete_control",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetConversation",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.DeleteControl",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "GetConversation"
+ "shortName": "DeleteControl"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetConversationRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteControlRequest"
},
{
"name": "name",
@@ -3646,22 +3615,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
- "shortName": "get_conversation"
+ "shortName": "delete_control"
},
- "description": "Sample for GetConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py",
+ "description": "Sample for DeleteControl",
+ "file": "discoveryengine_v1_generated_control_service_delete_control_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetConversation_sync",
+ "regionTag": "discoveryengine_v1_generated_ControlService_DeleteControl_sync",
"segments": [
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -3676,39 +3644,37 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py"
+ "title": "discoveryengine_v1_generated_control_service_delete_control_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
+ "shortName": "ControlServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.get_session",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.get_control",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetSession",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.GetControl",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "GetSession"
+ "shortName": "GetControl"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetSessionRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetControlRequest"
},
{
"name": "name",
@@ -3727,14 +3693,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "get_session"
+ "resultType": "google.cloud.discoveryengine_v1.types.Control",
+ "shortName": "get_control"
},
- "description": "Sample for GetSession",
- "file": "discoveryengine_v1_generated_conversational_search_service_get_session_async.py",
+ "description": "Sample for GetControl",
+ "file": "discoveryengine_v1_generated_control_service_get_control_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetSession_async",
+ "regionTag": "discoveryengine_v1_generated_ControlService_GetControl_async",
"segments": [
{
"end": 51,
@@ -3767,28 +3733,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_get_session_async.py"
+ "title": "discoveryengine_v1_generated_control_service_get_control_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
+ "shortName": "ControlServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.get_session",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.get_control",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetSession",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.GetControl",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "GetSession"
+ "shortName": "GetControl"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetSessionRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetControlRequest"
},
{
"name": "name",
@@ -3807,14 +3773,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "get_session"
+ "resultType": "google.cloud.discoveryengine_v1.types.Control",
+ "shortName": "get_control"
},
- "description": "Sample for GetSession",
- "file": "discoveryengine_v1_generated_conversational_search_service_get_session_sync.py",
+ "description": "Sample for GetControl",
+ "file": "discoveryengine_v1_generated_control_service_get_control_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetSession_sync",
+ "regionTag": "discoveryengine_v1_generated_ControlService_GetControl_sync",
"segments": [
{
"end": 51,
@@ -3847,29 +3813,29 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_get_session_sync.py"
+ "title": "discoveryengine_v1_generated_control_service_get_control_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
+ "shortName": "ControlServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.list_conversations",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.list_controls",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListConversations",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.ListControls",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "ListConversations"
+ "shortName": "ListControls"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListConversationsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListControlsRequest"
},
{
"name": "parent",
@@ -3888,14 +3854,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsAsyncPager",
- "shortName": "list_conversations"
+ "resultType": "google.cloud.discoveryengine_v1.services.control_service.pagers.ListControlsAsyncPager",
+ "shortName": "list_controls"
},
- "description": "Sample for ListConversations",
- "file": "discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py",
+ "description": "Sample for ListControls",
+ "file": "discoveryengine_v1_generated_control_service_list_controls_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListConversations_async",
+ "regionTag": "discoveryengine_v1_generated_ControlService_ListControls_async",
"segments": [
{
"end": 52,
@@ -3928,28 +3894,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py"
+ "title": "discoveryengine_v1_generated_control_service_list_controls_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
+ "shortName": "ControlServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.list_conversations",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.list_controls",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListConversations",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.ListControls",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "ListConversations"
+ "shortName": "ListControls"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListConversationsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListControlsRequest"
},
{
"name": "parent",
@@ -3968,14 +3934,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsPager",
- "shortName": "list_conversations"
+ "resultType": "google.cloud.discoveryengine_v1.services.control_service.pagers.ListControlsPager",
+ "shortName": "list_controls"
},
- "description": "Sample for ListConversations",
- "file": "discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py",
+ "description": "Sample for ListControls",
+ "file": "discoveryengine_v1_generated_control_service_list_controls_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListConversations_sync",
+ "regionTag": "discoveryengine_v1_generated_ControlService_ListControls_sync",
"segments": [
{
"end": 52,
@@ -4008,33 +3974,37 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py"
+ "title": "discoveryengine_v1_generated_control_service_list_controls_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
- "shortName": "ConversationalSearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient",
+ "shortName": "ControlServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.list_sessions",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceAsyncClient.update_control",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListSessions",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.UpdateControl",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "ListSessions"
+ "shortName": "UpdateControl"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListSessionsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateControlRequest"
},
{
- "name": "parent",
- "type": "str"
+ "name": "control",
+ "type": "google.cloud.discoveryengine_v1.types.Control"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -4049,22 +4019,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListSessionsAsyncPager",
- "shortName": "list_sessions"
+ "resultType": "google.cloud.discoveryengine_v1.types.Control",
+ "shortName": "update_control"
},
- "description": "Sample for ListSessions",
- "file": "discoveryengine_v1_generated_conversational_search_service_list_sessions_async.py",
+ "description": "Sample for UpdateControl",
+ "file": "discoveryengine_v1_generated_control_service_update_control_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListSessions_async",
+ "regionTag": "discoveryengine_v1_generated_ControlService_UpdateControl_async",
"segments": [
{
- "end": 52,
+ "end": 58,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 58,
"start": 27,
"type": "SHORT"
},
@@ -4074,47 +4044,51 @@
"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": "discoveryengine_v1_generated_conversational_search_service_list_sessions_async.py"
+ "title": "discoveryengine_v1_generated_control_service_update_control_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
- "shortName": "ConversationalSearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient",
+ "shortName": "ControlServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.list_sessions",
+ "fullName": "google.cloud.discoveryengine_v1.ControlServiceClient.update_control",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListSessions",
+ "fullName": "google.cloud.discoveryengine.v1.ControlService.UpdateControl",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
- "shortName": "ConversationalSearchService"
+ "fullName": "google.cloud.discoveryengine.v1.ControlService",
+ "shortName": "ControlService"
},
- "shortName": "ListSessions"
+ "shortName": "UpdateControl"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListSessionsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateControlRequest"
},
{
- "name": "parent",
- "type": "str"
+ "name": "control",
+ "type": "google.cloud.discoveryengine_v1.types.Control"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -4129,22 +4103,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListSessionsPager",
- "shortName": "list_sessions"
+ "resultType": "google.cloud.discoveryengine_v1.types.Control",
+ "shortName": "update_control"
},
- "description": "Sample for ListSessions",
- "file": "discoveryengine_v1_generated_conversational_search_service_list_sessions_sync.py",
+ "description": "Sample for UpdateControl",
+ "file": "discoveryengine_v1_generated_control_service_update_control_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListSessions_sync",
+ "regionTag": "discoveryengine_v1_generated_ControlService_UpdateControl_sync",
"segments": [
{
- "end": 52,
+ "end": 58,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 58,
"start": 27,
"type": "SHORT"
},
@@ -4154,22 +4128,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": "discoveryengine_v1_generated_conversational_search_service_list_sessions_sync.py"
+ "title": "discoveryengine_v1_generated_control_service_update_control_sync.py"
},
{
"canonical": true,
@@ -4179,14 +4153,14 @@
"fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
"shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.stream_answer_query",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.answer_query",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.StreamAnswerQuery",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.AnswerQuery",
"service": {
"fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
"shortName": "ConversationalSearchService"
},
- "shortName": "StreamAnswerQuery"
+ "shortName": "AnswerQuery"
},
"parameters": [
{
@@ -4206,22 +4180,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "Iterable[google.cloud.discoveryengine_v1.types.AnswerQueryResponse]",
- "shortName": "stream_answer_query"
+ "resultType": "google.cloud.discoveryengine_v1.types.AnswerQueryResponse",
+ "shortName": "answer_query"
},
- "description": "Sample for StreamAnswerQuery",
- "file": "discoveryengine_v1_generated_conversational_search_service_stream_answer_query_async.py",
+ "description": "Sample for AnswerQuery",
+ "file": "discoveryengine_v1_generated_conversational_search_service_answer_query_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_StreamAnswerQuery_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_AnswerQuery_async",
"segments": [
{
- "end": 56,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -4241,12 +4215,12 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
+ "end": 56,
"start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_stream_answer_query_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_answer_query_async.py"
},
{
"canonical": true,
@@ -4255,14 +4229,14 @@
"fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
"shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.stream_answer_query",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.answer_query",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.StreamAnswerQuery",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.AnswerQuery",
"service": {
"fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
"shortName": "ConversationalSearchService"
},
- "shortName": "StreamAnswerQuery"
+ "shortName": "AnswerQuery"
},
"parameters": [
{
@@ -4282,22 +4256,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "Iterable[google.cloud.discoveryengine_v1.types.AnswerQueryResponse]",
- "shortName": "stream_answer_query"
+ "resultType": "google.cloud.discoveryengine_v1.types.AnswerQueryResponse",
+ "shortName": "answer_query"
},
- "description": "Sample for StreamAnswerQuery",
- "file": "discoveryengine_v1_generated_conversational_search_service_stream_answer_query_sync.py",
+ "description": "Sample for AnswerQuery",
+ "file": "discoveryengine_v1_generated_conversational_search_service_answer_query_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_StreamAnswerQuery_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_AnswerQuery_sync",
"segments": [
{
- "end": 56,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -4317,12 +4291,12 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
+ "end": 56,
"start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_stream_answer_query_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_answer_query_sync.py"
},
{
"canonical": true,
@@ -4332,27 +4306,27 @@
"fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
"shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.update_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.converse_conversation",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateConversation",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation",
"service": {
"fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
"shortName": "ConversationalSearchService"
},
- "shortName": "UpdateConversation"
+ "shortName": "ConverseConversation"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateConversationRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ConverseConversationRequest"
},
{
- "name": "conversation",
- "type": "google.cloud.discoveryengine_v1.types.Conversation"
+ "name": "name",
+ "type": "str"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "query",
+ "type": "google.cloud.discoveryengine_v1.types.TextInput"
},
{
"name": "retry",
@@ -4367,22 +4341,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
- "shortName": "update_conversation"
+ "resultType": "google.cloud.discoveryengine_v1.types.ConverseConversationResponse",
+ "shortName": "converse_conversation"
},
- "description": "Sample for UpdateConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py",
+ "description": "Sample for ConverseConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_async",
"segments": [
{
- "end": 50,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 50,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -4392,22 +4366,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 47,
- "start": 45,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 51,
- "start": 48,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_async.py"
},
{
"canonical": true,
@@ -4416,27 +4390,27 @@
"fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
"shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.update_conversation",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.converse_conversation",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateConversation",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ConverseConversation",
"service": {
"fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
"shortName": "ConversationalSearchService"
},
- "shortName": "UpdateConversation"
+ "shortName": "ConverseConversation"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateConversationRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ConverseConversationRequest"
},
{
- "name": "conversation",
- "type": "google.cloud.discoveryengine_v1.types.Conversation"
+ "name": "name",
+ "type": "str"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "query",
+ "type": "google.cloud.discoveryengine_v1.types.TextInput"
},
{
"name": "retry",
@@ -4451,22 +4425,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
- "shortName": "update_conversation"
+ "resultType": "google.cloud.discoveryengine_v1.types.ConverseConversationResponse",
+ "shortName": "converse_conversation"
},
- "description": "Sample for UpdateConversation",
- "file": "discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py",
+ "description": "Sample for ConverseConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ConverseConversation_sync",
"segments": [
{
- "end": 50,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 50,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -4476,22 +4450,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 47,
- "start": 45,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 51,
- "start": 48,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_converse_conversation_sync.py"
},
{
"canonical": true,
@@ -4501,27 +4475,27 @@
"fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
"shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.update_session",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.create_conversation",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateSession",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateConversation",
"service": {
"fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
"shortName": "ConversationalSearchService"
},
- "shortName": "UpdateSession"
+ "shortName": "CreateConversation"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateSessionRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateConversationRequest"
},
{
- "name": "session",
- "type": "google.cloud.discoveryengine_v1.types.Session"
+ "name": "parent",
+ "type": "str"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "conversation",
+ "type": "google.cloud.discoveryengine_v1.types.Conversation"
},
{
"name": "retry",
@@ -4536,22 +4510,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "update_session"
+ "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
+ "shortName": "create_conversation"
},
- "description": "Sample for UpdateSession",
- "file": "discoveryengine_v1_generated_conversational_search_service_update_session_async.py",
+ "description": "Sample for CreateConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateSession_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_async",
"segments": [
{
- "end": 50,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 50,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -4561,22 +4535,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 47,
- "start": 45,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 51,
- "start": 48,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_update_session_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_create_conversation_async.py"
},
{
"canonical": true,
@@ -4585,27 +4559,27 @@
"fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
"shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.update_session",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.create_conversation",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateSession",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateConversation",
"service": {
"fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
"shortName": "ConversationalSearchService"
},
- "shortName": "UpdateSession"
+ "shortName": "CreateConversation"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateSessionRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateConversationRequest"
},
{
- "name": "session",
- "type": "google.cloud.discoveryengine_v1.types.Session"
+ "name": "parent",
+ "type": "str"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "conversation",
+ "type": "google.cloud.discoveryengine_v1.types.Conversation"
},
{
"name": "retry",
@@ -4620,22 +4594,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "update_session"
+ "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
+ "shortName": "create_conversation"
},
- "description": "Sample for UpdateSession",
- "file": "discoveryengine_v1_generated_conversational_search_service_update_session_sync.py",
+ "description": "Sample for CreateConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateSession_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateConversation_sync",
"segments": [
{
- "end": 50,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 50,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -4645,56 +4619,52 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 47,
- "start": 45,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 51,
- "start": 48,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_conversational_search_service_update_session_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_create_conversation_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
- "shortName": "DataStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.create_data_store",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.create_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.CreateDataStore",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "CreateDataStore"
+ "shortName": "CreateSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateDataStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateSessionRequest"
},
{
"name": "parent",
"type": "str"
},
{
- "name": "data_store",
- "type": "google.cloud.discoveryengine_v1.types.DataStore"
- },
- {
- "name": "data_store_id",
- "type": "str"
+ "name": "session",
+ "type": "google.cloud.discoveryengine_v1.types.Session"
},
{
"name": "retry",
@@ -4709,22 +4679,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "create_data_store"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "create_session"
},
- "description": "Sample for CreateDataStore",
- "file": "discoveryengine_v1_generated_data_store_service_create_data_store_async.py",
+ "description": "Sample for CreateSession",
+ "file": "discoveryengine_v1_generated_conversational_search_service_create_session_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_CreateDataStore_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateSession_async",
"segments": [
{
- "end": 61,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 61,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -4734,55 +4704,51 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 51,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 58,
- "start": 52,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 62,
- "start": 59,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_create_data_store_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_create_session_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
- "shortName": "DataStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.create_data_store",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.create_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.CreateDataStore",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.CreateSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "CreateDataStore"
+ "shortName": "CreateSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateDataStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateSessionRequest"
},
{
"name": "parent",
"type": "str"
},
{
- "name": "data_store",
- "type": "google.cloud.discoveryengine_v1.types.DataStore"
- },
- {
- "name": "data_store_id",
- "type": "str"
+ "name": "session",
+ "type": "google.cloud.discoveryengine_v1.types.Session"
},
{
"name": "retry",
@@ -4797,22 +4763,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "create_data_store"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "create_session"
},
- "description": "Sample for CreateDataStore",
- "file": "discoveryengine_v1_generated_data_store_service_create_data_store_sync.py",
+ "description": "Sample for CreateSession",
+ "file": "discoveryengine_v1_generated_conversational_search_service_create_session_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_CreateDataStore_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_CreateSession_sync",
"segments": [
{
- "end": 61,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 61,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -4822,44 +4788,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 51,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 58,
- "start": 52,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 62,
- "start": 59,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_create_data_store_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_create_session_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
- "shortName": "DataStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.delete_data_store",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.delete_conversation",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.DeleteDataStore",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteConversation",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "DeleteDataStore"
+ "shortName": "DeleteConversation"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteDataStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteConversationRequest"
},
{
"name": "name",
@@ -4878,22 +4844,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "delete_data_store"
+ "shortName": "delete_conversation"
},
- "description": "Sample for DeleteDataStore",
- "file": "discoveryengine_v1_generated_data_store_service_delete_data_store_async.py",
+ "description": "Sample for DeleteConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_DeleteDataStore_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_async",
"segments": [
{
- "end": 55,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -4908,38 +4873,36 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_delete_data_store_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
- "shortName": "DataStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.delete_data_store",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.delete_conversation",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.DeleteDataStore",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteConversation",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "DeleteDataStore"
+ "shortName": "DeleteConversation"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteDataStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteConversationRequest"
},
{
"name": "name",
@@ -4958,22 +4921,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "delete_data_store"
+ "shortName": "delete_conversation"
},
- "description": "Sample for DeleteDataStore",
- "file": "discoveryengine_v1_generated_data_store_service_delete_data_store_sync.py",
+ "description": "Sample for DeleteConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_DeleteDataStore_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteConversation_sync",
"segments": [
{
- "end": 55,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -4988,39 +4950,37 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_delete_data_store_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_delete_conversation_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
- "shortName": "DataStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.get_data_store",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.delete_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.GetDataStore",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "GetDataStore"
+ "shortName": "DeleteSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetDataStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteSessionRequest"
},
{
"name": "name",
@@ -5039,22 +4999,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.DataStore",
- "shortName": "get_data_store"
+ "shortName": "delete_session"
},
- "description": "Sample for GetDataStore",
- "file": "discoveryengine_v1_generated_data_store_service_get_data_store_async.py",
+ "description": "Sample for DeleteSession",
+ "file": "discoveryengine_v1_generated_conversational_search_service_delete_session_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_GetDataStore_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteSession_async",
"segments": [
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -5069,38 +5028,36 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_get_data_store_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_delete_session_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
- "shortName": "DataStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.get_data_store",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.delete_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.GetDataStore",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.DeleteSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "GetDataStore"
+ "shortName": "DeleteSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetDataStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteSessionRequest"
},
{
"name": "name",
@@ -5119,22 +5076,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.DataStore",
- "shortName": "get_data_store"
+ "shortName": "delete_session"
},
- "description": "Sample for GetDataStore",
- "file": "discoveryengine_v1_generated_data_store_service_get_data_store_sync.py",
+ "description": "Sample for DeleteSession",
+ "file": "discoveryengine_v1_generated_conversational_search_service_delete_session_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_GetDataStore_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_DeleteSession_sync",
"segments": [
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -5149,42 +5105,40 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_get_data_store_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_delete_session_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
- "shortName": "DataStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.list_data_stores",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.get_answer",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.ListDataStores",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetAnswer",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "ListDataStores"
+ "shortName": "GetAnswer"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListDataStoresRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetAnswerRequest"
},
{
- "name": "parent",
+ "name": "name",
"type": "str"
},
{
@@ -5200,22 +5154,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.data_store_service.pagers.ListDataStoresAsyncPager",
- "shortName": "list_data_stores"
+ "resultType": "google.cloud.discoveryengine_v1.types.Answer",
+ "shortName": "get_answer"
},
- "description": "Sample for ListDataStores",
- "file": "discoveryengine_v1_generated_data_store_service_list_data_stores_async.py",
+ "description": "Sample for GetAnswer",
+ "file": "discoveryengine_v1_generated_conversational_search_service_get_answer_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_ListDataStores_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetAnswer_async",
"segments": [
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -5235,36 +5189,36 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
+ "end": 52,
"start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_list_data_stores_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_get_answer_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
- "shortName": "DataStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.list_data_stores",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.get_answer",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.ListDataStores",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetAnswer",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "ListDataStores"
+ "shortName": "GetAnswer"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListDataStoresRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetAnswerRequest"
},
{
- "name": "parent",
+ "name": "name",
"type": "str"
},
{
@@ -5280,22 +5234,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.data_store_service.pagers.ListDataStoresPager",
- "shortName": "list_data_stores"
+ "resultType": "google.cloud.discoveryengine_v1.types.Answer",
+ "shortName": "get_answer"
},
- "description": "Sample for ListDataStores",
- "file": "discoveryengine_v1_generated_data_store_service_list_data_stores_sync.py",
+ "description": "Sample for GetAnswer",
+ "file": "discoveryengine_v1_generated_conversational_search_service_get_answer_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_ListDataStores_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetAnswer_sync",
"segments": [
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -5315,42 +5269,38 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
+ "end": 52,
"start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_list_data_stores_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_get_answer_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
- "shortName": "DataStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.update_data_store",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.get_conversation",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.UpdateDataStore",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetConversation",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "UpdateDataStore"
+ "shortName": "GetConversation"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateDataStoreRequest"
- },
- {
- "name": "data_store",
- "type": "google.cloud.discoveryengine_v1.types.DataStore"
+ "type": "google.cloud.discoveryengine_v1.types.GetConversationRequest"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -5365,22 +5315,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.DataStore",
- "shortName": "update_data_store"
+ "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
+ "shortName": "get_conversation"
},
- "description": "Sample for UpdateDataStore",
- "file": "discoveryengine_v1_generated_data_store_service_update_data_store_async.py",
+ "description": "Sample for GetConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_UpdateDataStore_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetConversation_async",
"segments": [
{
- "end": 54,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 54,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -5390,51 +5340,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 48,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 51,
- "start": 49,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 55,
- "start": 52,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_update_data_store_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_get_conversation_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
- "shortName": "DataStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.update_data_store",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.get_conversation",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService.UpdateDataStore",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetConversation",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
- "shortName": "DataStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "UpdateDataStore"
+ "shortName": "GetConversation"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateDataStoreRequest"
- },
- {
- "name": "data_store",
- "type": "google.cloud.discoveryengine_v1.types.DataStore"
+ "type": "google.cloud.discoveryengine_v1.types.GetConversationRequest"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -5449,22 +5395,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.DataStore",
- "shortName": "update_data_store"
+ "resultType": "google.cloud.discoveryengine_v1.types.Conversation",
+ "shortName": "get_conversation"
},
- "description": "Sample for UpdateDataStore",
- "file": "discoveryengine_v1_generated_data_store_service_update_data_store_sync.py",
+ "description": "Sample for GetConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DataStoreService_UpdateDataStore_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetConversation_sync",
"segments": [
{
- "end": 54,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 54,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -5474,47 +5420,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 48,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 51,
- "start": 49,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 55,
- "start": 52,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_data_store_service_update_data_store_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_get_conversation_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
- "shortName": "DocumentServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.batch_get_documents_metadata",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.get_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.BatchGetDocumentsMetadata",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "BatchGetDocumentsMetadata"
+ "shortName": "GetSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.BatchGetDocumentsMetadataRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetSessionRequest"
},
{
- "name": "parent",
+ "name": "name",
"type": "str"
},
{
@@ -5530,14 +5476,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.BatchGetDocumentsMetadataResponse",
- "shortName": "batch_get_documents_metadata"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "get_session"
},
- "description": "Sample for BatchGetDocumentsMetadata",
- "file": "discoveryengine_v1_generated_document_service_batch_get_documents_metadata_async.py",
+ "description": "Sample for GetSession",
+ "file": "discoveryengine_v1_generated_conversational_search_service_get_session_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_BatchGetDocumentsMetadata_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetSession_async",
"segments": [
{
"end": 51,
@@ -5570,31 +5516,31 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_batch_get_documents_metadata_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_get_session_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
- "shortName": "DocumentServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.batch_get_documents_metadata",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.get_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.BatchGetDocumentsMetadata",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.GetSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "BatchGetDocumentsMetadata"
+ "shortName": "GetSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.BatchGetDocumentsMetadataRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetSessionRequest"
},
{
- "name": "parent",
+ "name": "name",
"type": "str"
},
{
@@ -5610,14 +5556,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.BatchGetDocumentsMetadataResponse",
- "shortName": "batch_get_documents_metadata"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "get_session"
},
- "description": "Sample for BatchGetDocumentsMetadata",
- "file": "discoveryengine_v1_generated_document_service_batch_get_documents_metadata_sync.py",
+ "description": "Sample for GetSession",
+ "file": "discoveryengine_v1_generated_conversational_search_service_get_session_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_BatchGetDocumentsMetadata_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_GetSession_sync",
"segments": [
{
"end": 51,
@@ -5650,42 +5596,34 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_batch_get_documents_metadata_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_get_session_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
- "shortName": "DocumentServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.create_document",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.list_conversations",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.CreateDocument",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListConversations",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "CreateDocument"
+ "shortName": "ListConversations"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateDocumentRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListConversationsRequest"
},
{
"name": "parent",
"type": "str"
},
- {
- "name": "document",
- "type": "google.cloud.discoveryengine_v1.types.Document"
- },
- {
- "name": "document_id",
- "type": "str"
- },
{
"name": "retry",
"type": "google.api_core.retry.Retry"
@@ -5699,14 +5637,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Document",
- "shortName": "create_document"
+ "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsAsyncPager",
+ "shortName": "list_conversations"
},
- "description": "Sample for CreateDocument",
- "file": "discoveryengine_v1_generated_document_service_create_document_async.py",
+ "description": "Sample for ListConversations",
+ "file": "discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_CreateDocument_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListConversations_async",
"segments": [
{
"end": 52,
@@ -5724,56 +5662,48 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 49,
- "start": 47,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
"end": 53,
- "start": 50,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_create_document_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_list_conversations_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
- "shortName": "DocumentServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.create_document",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.list_conversations",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.CreateDocument",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListConversations",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "CreateDocument"
+ "shortName": "ListConversations"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateDocumentRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListConversationsRequest"
},
{
"name": "parent",
"type": "str"
},
- {
- "name": "document",
- "type": "google.cloud.discoveryengine_v1.types.Document"
- },
- {
- "name": "document_id",
- "type": "str"
- },
{
"name": "retry",
"type": "google.api_core.retry.Retry"
@@ -5787,14 +5717,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Document",
- "shortName": "create_document"
+ "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListConversationsPager",
+ "shortName": "list_conversations"
},
- "description": "Sample for CreateDocument",
- "file": "discoveryengine_v1_generated_document_service_create_document_sync.py",
+ "description": "Sample for ListConversations",
+ "file": "discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_CreateDocument_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListConversations_sync",
"segments": [
{
"end": 52,
@@ -5812,47 +5742,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 49,
- "start": 47,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
"end": 53,
- "start": 50,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_create_document_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_list_conversations_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
- "shortName": "DocumentServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.delete_document",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.list_sessions",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.DeleteDocument",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListSessions",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "DeleteDocument"
+ "shortName": "ListSessions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteDocumentRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListSessionsRequest"
},
{
- "name": "name",
+ "name": "parent",
"type": "str"
},
{
@@ -5868,21 +5798,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_document"
+ "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListSessionsAsyncPager",
+ "shortName": "list_sessions"
},
- "description": "Sample for DeleteDocument",
- "file": "discoveryengine_v1_generated_document_service_delete_document_async.py",
+ "description": "Sample for ListSessions",
+ "file": "discoveryengine_v1_generated_conversational_search_service_list_sessions_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_DeleteDocument_async",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListSessions_async",
"segments": [
{
- "end": 49,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -5897,39 +5828,41 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_delete_document_async.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_list_sessions_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
- "shortName": "DocumentServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.delete_document",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.list_sessions",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.DeleteDocument",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.ListSessions",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "DeleteDocument"
+ "shortName": "ListSessions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteDocumentRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListSessionsRequest"
},
{
- "name": "name",
+ "name": "parent",
"type": "str"
},
{
@@ -5945,21 +5878,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_document"
+ "resultType": "google.cloud.discoveryengine_v1.services.conversational_search_service.pagers.ListSessionsPager",
+ "shortName": "list_sessions"
},
- "description": "Sample for DeleteDocument",
- "file": "discoveryengine_v1_generated_document_service_delete_document_sync.py",
+ "description": "Sample for ListSessions",
+ "file": "discoveryengine_v1_generated_conversational_search_service_list_sessions_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_DeleteDocument_sync",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_ListSessions_sync",
"segments": [
{
- "end": 49,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -5974,41 +5908,3409 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_delete_document_sync.py"
+ "title": "discoveryengine_v1_generated_conversational_search_service_list_sessions_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
- "shortName": "DocumentServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.get_document",
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.stream_answer_query",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.GetDocument",
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.StreamAnswerQuery",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
},
- "shortName": "GetDocument"
+ "shortName": "StreamAnswerQuery"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetDocumentRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.AnswerQueryRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "Iterable[google.cloud.discoveryengine_v1.types.AnswerQueryResponse]",
+ "shortName": "stream_answer_query"
+ },
+ "description": "Sample for StreamAnswerQuery",
+ "file": "discoveryengine_v1_generated_conversational_search_service_stream_answer_query_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_StreamAnswerQuery_async",
+ "segments": [
+ {
+ "end": 56,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 56,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 52,
+ "start": 50,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 57,
+ "start": 53,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_conversational_search_service_stream_answer_query_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.stream_answer_query",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.StreamAnswerQuery",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
+ },
+ "shortName": "StreamAnswerQuery"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.AnswerQueryRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "Iterable[google.cloud.discoveryengine_v1.types.AnswerQueryResponse]",
+ "shortName": "stream_answer_query"
+ },
+ "description": "Sample for StreamAnswerQuery",
+ "file": "discoveryengine_v1_generated_conversational_search_service_stream_answer_query_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_StreamAnswerQuery_sync",
+ "segments": [
+ {
+ "end": 56,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 56,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 52,
+ "start": 50,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 57,
+ "start": 53,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_conversational_search_service_stream_answer_query_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.update_conversation",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateConversation",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
+ },
+ "shortName": "UpdateConversation"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateConversationRequest"
+ },
+ {
+ "name": "conversation",
+ "type": "google.cloud.discoveryengine_v1.types.Conversation"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.Conversation",
+ "shortName": "update_conversation"
+ },
+ "description": "Sample for UpdateConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_async",
+ "segments": [
+ {
+ "end": 50,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 50,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 44,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 47,
+ "start": 45,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 51,
+ "start": 48,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_conversational_search_service_update_conversation_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.update_conversation",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateConversation",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
+ },
+ "shortName": "UpdateConversation"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateConversationRequest"
+ },
+ {
+ "name": "conversation",
+ "type": "google.cloud.discoveryengine_v1.types.Conversation"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.Conversation",
+ "shortName": "update_conversation"
+ },
+ "description": "Sample for UpdateConversation",
+ "file": "discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateConversation_sync",
+ "segments": [
+ {
+ "end": 50,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 50,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 44,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 47,
+ "start": 45,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 51,
+ "start": 48,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_conversational_search_service_update_conversation_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient",
+ "shortName": "ConversationalSearchServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceAsyncClient.update_session",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateSession",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
+ },
+ "shortName": "UpdateSession"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateSessionRequest"
+ },
+ {
+ "name": "session",
+ "type": "google.cloud.discoveryengine_v1.types.Session"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.Session",
+ "shortName": "update_session"
+ },
+ "description": "Sample for UpdateSession",
+ "file": "discoveryengine_v1_generated_conversational_search_service_update_session_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateSession_async",
+ "segments": [
+ {
+ "end": 50,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 50,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 44,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 47,
+ "start": 45,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 51,
+ "start": 48,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_conversational_search_service_update_session_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient",
+ "shortName": "ConversationalSearchServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.ConversationalSearchServiceClient.update_session",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService.UpdateSession",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.ConversationalSearchService",
+ "shortName": "ConversationalSearchService"
+ },
+ "shortName": "UpdateSession"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateSessionRequest"
+ },
+ {
+ "name": "session",
+ "type": "google.cloud.discoveryengine_v1.types.Session"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.Session",
+ "shortName": "update_session"
+ },
+ "description": "Sample for UpdateSession",
+ "file": "discoveryengine_v1_generated_conversational_search_service_update_session_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_ConversationalSearchService_UpdateSession_sync",
+ "segments": [
+ {
+ "end": 50,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 50,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 44,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 47,
+ "start": 45,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 51,
+ "start": 48,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_conversational_search_service_update_session_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceAsyncClient",
+ "shortName": "DataConnectorServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceAsyncClient.get_data_connector",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService.GetDataConnector",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "shortName": "DataConnectorService"
+ },
+ "shortName": "GetDataConnector"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetDataConnectorRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.DataConnector",
+ "shortName": "get_data_connector"
+ },
+ "description": "Sample for GetDataConnector",
+ "file": "discoveryengine_v1_generated_data_connector_service_get_data_connector_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataConnectorService_GetDataConnector_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": "discoveryengine_v1_generated_data_connector_service_get_data_connector_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceClient",
+ "shortName": "DataConnectorServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceClient.get_data_connector",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService.GetDataConnector",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "shortName": "DataConnectorService"
+ },
+ "shortName": "GetDataConnector"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetDataConnectorRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.DataConnector",
+ "shortName": "get_data_connector"
+ },
+ "description": "Sample for GetDataConnector",
+ "file": "discoveryengine_v1_generated_data_connector_service_get_data_connector_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataConnectorService_GetDataConnector_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": "discoveryengine_v1_generated_data_connector_service_get_data_connector_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceAsyncClient",
+ "shortName": "DataConnectorServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceAsyncClient.set_up_data_connector",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "shortName": "DataConnectorService"
+ },
+ "shortName": "SetUpDataConnector"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.SetUpDataConnectorRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "collection_id",
+ "type": "str"
+ },
+ {
+ "name": "collection_display_name",
+ "type": "str"
+ },
+ {
+ "name": "data_connector",
+ "type": "google.cloud.discoveryengine_v1.types.DataConnector"
+ },
+ {
+ "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": "set_up_data_connector"
+ },
+ "description": "Sample for SetUpDataConnector",
+ "file": "discoveryengine_v1_generated_data_connector_service_set_up_data_connector_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataConnectorService_SetUpDataConnector_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": "discoveryengine_v1_generated_data_connector_service_set_up_data_connector_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceClient",
+ "shortName": "DataConnectorServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceClient.set_up_data_connector",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService.SetUpDataConnector",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "shortName": "DataConnectorService"
+ },
+ "shortName": "SetUpDataConnector"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.SetUpDataConnectorRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "collection_id",
+ "type": "str"
+ },
+ {
+ "name": "collection_display_name",
+ "type": "str"
+ },
+ {
+ "name": "data_connector",
+ "type": "google.cloud.discoveryengine_v1.types.DataConnector"
+ },
+ {
+ "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": "set_up_data_connector"
+ },
+ "description": "Sample for SetUpDataConnector",
+ "file": "discoveryengine_v1_generated_data_connector_service_set_up_data_connector_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataConnectorService_SetUpDataConnector_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": "discoveryengine_v1_generated_data_connector_service_set_up_data_connector_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceAsyncClient",
+ "shortName": "DataConnectorServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceAsyncClient.update_data_connector",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService.UpdateDataConnector",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "shortName": "DataConnectorService"
+ },
+ "shortName": "UpdateDataConnector"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateDataConnectorRequest"
+ },
+ {
+ "name": "data_connector",
+ "type": "google.cloud.discoveryengine_v1.types.DataConnector"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.DataConnector",
+ "shortName": "update_data_connector"
+ },
+ "description": "Sample for UpdateDataConnector",
+ "file": "discoveryengine_v1_generated_data_connector_service_update_data_connector_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataConnectorService_UpdateDataConnector_async",
+ "segments": [
+ {
+ "end": 54,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 54,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 48,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 51,
+ "start": 49,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 55,
+ "start": 52,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_data_connector_service_update_data_connector_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceClient",
+ "shortName": "DataConnectorServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataConnectorServiceClient.update_data_connector",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService.UpdateDataConnector",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataConnectorService",
+ "shortName": "DataConnectorService"
+ },
+ "shortName": "UpdateDataConnector"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateDataConnectorRequest"
+ },
+ {
+ "name": "data_connector",
+ "type": "google.cloud.discoveryengine_v1.types.DataConnector"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.DataConnector",
+ "shortName": "update_data_connector"
+ },
+ "description": "Sample for UpdateDataConnector",
+ "file": "discoveryengine_v1_generated_data_connector_service_update_data_connector_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataConnectorService_UpdateDataConnector_sync",
+ "segments": [
+ {
+ "end": 54,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 54,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 48,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 51,
+ "start": 49,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 55,
+ "start": 52,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_data_connector_service_update_data_connector_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
+ "shortName": "DataStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.create_data_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.CreateDataStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "CreateDataStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CreateDataStoreRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "data_store",
+ "type": "google.cloud.discoveryengine_v1.types.DataStore"
+ },
+ {
+ "name": "data_store_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_data_store"
+ },
+ "description": "Sample for CreateDataStore",
+ "file": "discoveryengine_v1_generated_data_store_service_create_data_store_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_CreateDataStore_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": "discoveryengine_v1_generated_data_store_service_create_data_store_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
+ "shortName": "DataStoreServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.create_data_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.CreateDataStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "CreateDataStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CreateDataStoreRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "data_store",
+ "type": "google.cloud.discoveryengine_v1.types.DataStore"
+ },
+ {
+ "name": "data_store_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_data_store"
+ },
+ "description": "Sample for CreateDataStore",
+ "file": "discoveryengine_v1_generated_data_store_service_create_data_store_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_CreateDataStore_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": "discoveryengine_v1_generated_data_store_service_create_data_store_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
+ "shortName": "DataStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.delete_data_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.DeleteDataStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "DeleteDataStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.DeleteDataStoreRequest"
+ },
+ {
+ "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_data_store"
+ },
+ "description": "Sample for DeleteDataStore",
+ "file": "discoveryengine_v1_generated_data_store_service_delete_data_store_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_DeleteDataStore_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": "discoveryengine_v1_generated_data_store_service_delete_data_store_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
+ "shortName": "DataStoreServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.delete_data_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.DeleteDataStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "DeleteDataStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.DeleteDataStoreRequest"
+ },
+ {
+ "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_data_store"
+ },
+ "description": "Sample for DeleteDataStore",
+ "file": "discoveryengine_v1_generated_data_store_service_delete_data_store_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_DeleteDataStore_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": "discoveryengine_v1_generated_data_store_service_delete_data_store_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
+ "shortName": "DataStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.get_data_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.GetDataStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "GetDataStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetDataStoreRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.DataStore",
+ "shortName": "get_data_store"
+ },
+ "description": "Sample for GetDataStore",
+ "file": "discoveryengine_v1_generated_data_store_service_get_data_store_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_GetDataStore_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": "discoveryengine_v1_generated_data_store_service_get_data_store_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
+ "shortName": "DataStoreServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.get_data_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.GetDataStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "GetDataStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetDataStoreRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.DataStore",
+ "shortName": "get_data_store"
+ },
+ "description": "Sample for GetDataStore",
+ "file": "discoveryengine_v1_generated_data_store_service_get_data_store_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_GetDataStore_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": "discoveryengine_v1_generated_data_store_service_get_data_store_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
+ "shortName": "DataStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.get_iam_policy",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.GetIamPolicy",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "GetIamPolicy"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest"
+ },
+ {
+ "name": "resource",
+ "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.iam.v1.policy_pb2.Policy",
+ "shortName": "get_iam_policy"
+ },
+ "description": "Sample for GetIamPolicy",
+ "file": "discoveryengine_v1_generated_data_store_service_get_iam_policy_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_GetIamPolicy_async",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 41,
+ "start": 39,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 42,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_data_store_service_get_iam_policy_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
+ "shortName": "DataStoreServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.get_iam_policy",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.GetIamPolicy",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "GetIamPolicy"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest"
+ },
+ {
+ "name": "resource",
+ "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.iam.v1.policy_pb2.Policy",
+ "shortName": "get_iam_policy"
+ },
+ "description": "Sample for GetIamPolicy",
+ "file": "discoveryengine_v1_generated_data_store_service_get_iam_policy_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_GetIamPolicy_sync",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 41,
+ "start": 39,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 42,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_data_store_service_get_iam_policy_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
+ "shortName": "DataStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.list_data_stores",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.ListDataStores",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "ListDataStores"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.ListDataStoresRequest"
+ },
+ {
+ "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.discoveryengine_v1.services.data_store_service.pagers.ListDataStoresAsyncPager",
+ "shortName": "list_data_stores"
+ },
+ "description": "Sample for ListDataStores",
+ "file": "discoveryengine_v1_generated_data_store_service_list_data_stores_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_ListDataStores_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": "discoveryengine_v1_generated_data_store_service_list_data_stores_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
+ "shortName": "DataStoreServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.list_data_stores",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.ListDataStores",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "ListDataStores"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.ListDataStoresRequest"
+ },
+ {
+ "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.discoveryengine_v1.services.data_store_service.pagers.ListDataStoresPager",
+ "shortName": "list_data_stores"
+ },
+ "description": "Sample for ListDataStores",
+ "file": "discoveryengine_v1_generated_data_store_service_list_data_stores_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_ListDataStores_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": "discoveryengine_v1_generated_data_store_service_list_data_stores_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
+ "shortName": "DataStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.set_iam_policy",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.SetIamPolicy",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "SetIamPolicy"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest"
+ },
+ {
+ "name": "resource",
+ "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.iam.v1.policy_pb2.Policy",
+ "shortName": "set_iam_policy"
+ },
+ "description": "Sample for SetIamPolicy",
+ "file": "discoveryengine_v1_generated_data_store_service_set_iam_policy_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_SetIamPolicy_async",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 41,
+ "start": 39,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 42,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_data_store_service_set_iam_policy_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
+ "shortName": "DataStoreServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.set_iam_policy",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.SetIamPolicy",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "SetIamPolicy"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest"
+ },
+ {
+ "name": "resource",
+ "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.iam.v1.policy_pb2.Policy",
+ "shortName": "set_iam_policy"
+ },
+ "description": "Sample for SetIamPolicy",
+ "file": "discoveryengine_v1_generated_data_store_service_set_iam_policy_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_SetIamPolicy_sync",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 41,
+ "start": 39,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 42,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_data_store_service_set_iam_policy_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient",
+ "shortName": "DataStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceAsyncClient.update_data_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.UpdateDataStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "UpdateDataStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateDataStoreRequest"
+ },
+ {
+ "name": "data_store",
+ "type": "google.cloud.discoveryengine_v1.types.DataStore"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.DataStore",
+ "shortName": "update_data_store"
+ },
+ "description": "Sample for UpdateDataStore",
+ "file": "discoveryengine_v1_generated_data_store_service_update_data_store_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_UpdateDataStore_async",
+ "segments": [
+ {
+ "end": 54,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 54,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 48,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 51,
+ "start": 49,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 55,
+ "start": 52,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_data_store_service_update_data_store_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient",
+ "shortName": "DataStoreServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DataStoreServiceClient.update_data_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService.UpdateDataStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DataStoreService",
+ "shortName": "DataStoreService"
+ },
+ "shortName": "UpdateDataStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateDataStoreRequest"
+ },
+ {
+ "name": "data_store",
+ "type": "google.cloud.discoveryengine_v1.types.DataStore"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.DataStore",
+ "shortName": "update_data_store"
+ },
+ "description": "Sample for UpdateDataStore",
+ "file": "discoveryengine_v1_generated_data_store_service_update_data_store_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DataStoreService_UpdateDataStore_sync",
+ "segments": [
+ {
+ "end": 54,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 54,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 48,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 51,
+ "start": 49,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 55,
+ "start": 52,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_data_store_service_update_data_store_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
+ "shortName": "DocumentServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.batch_get_documents_metadata",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.BatchGetDocumentsMetadata",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "BatchGetDocumentsMetadata"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.BatchGetDocumentsMetadataRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.BatchGetDocumentsMetadataResponse",
+ "shortName": "batch_get_documents_metadata"
+ },
+ "description": "Sample for BatchGetDocumentsMetadata",
+ "file": "discoveryengine_v1_generated_document_service_batch_get_documents_metadata_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_BatchGetDocumentsMetadata_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": "discoveryengine_v1_generated_document_service_batch_get_documents_metadata_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
+ "shortName": "DocumentServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.batch_get_documents_metadata",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.BatchGetDocumentsMetadata",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "BatchGetDocumentsMetadata"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.BatchGetDocumentsMetadataRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.BatchGetDocumentsMetadataResponse",
+ "shortName": "batch_get_documents_metadata"
+ },
+ "description": "Sample for BatchGetDocumentsMetadata",
+ "file": "discoveryengine_v1_generated_document_service_batch_get_documents_metadata_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_BatchGetDocumentsMetadata_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": "discoveryengine_v1_generated_document_service_batch_get_documents_metadata_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
+ "shortName": "DocumentServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.create_document",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.CreateDocument",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "CreateDocument"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CreateDocumentRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "document",
+ "type": "google.cloud.discoveryengine_v1.types.Document"
+ },
+ {
+ "name": "document_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.cloud.discoveryengine_v1.types.Document",
+ "shortName": "create_document"
+ },
+ "description": "Sample for CreateDocument",
+ "file": "discoveryengine_v1_generated_document_service_create_document_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_CreateDocument_async",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_document_service_create_document_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
+ "shortName": "DocumentServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.create_document",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.CreateDocument",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "CreateDocument"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CreateDocumentRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "document",
+ "type": "google.cloud.discoveryengine_v1.types.Document"
+ },
+ {
+ "name": "document_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.cloud.discoveryengine_v1.types.Document",
+ "shortName": "create_document"
+ },
+ "description": "Sample for CreateDocument",
+ "file": "discoveryengine_v1_generated_document_service_create_document_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_CreateDocument_sync",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_document_service_create_document_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
+ "shortName": "DocumentServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.delete_document",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.DeleteDocument",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "DeleteDocument"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.DeleteDocumentRequest"
+ },
+ {
+ "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]]]"
+ }
+ ],
+ "shortName": "delete_document"
+ },
+ "description": "Sample for DeleteDocument",
+ "file": "discoveryengine_v1_generated_document_service_delete_document_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_DeleteDocument_async",
+ "segments": [
+ {
+ "end": 49,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 49,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 45,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "start": 46,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_document_service_delete_document_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
+ "shortName": "DocumentServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.delete_document",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.DeleteDocument",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "DeleteDocument"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.DeleteDocumentRequest"
+ },
+ {
+ "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]]]"
+ }
+ ],
+ "shortName": "delete_document"
+ },
+ "description": "Sample for DeleteDocument",
+ "file": "discoveryengine_v1_generated_document_service_delete_document_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_DeleteDocument_sync",
+ "segments": [
+ {
+ "end": 49,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 49,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 45,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "start": 46,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_document_service_delete_document_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
+ "shortName": "DocumentServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.get_document",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.GetDocument",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "GetDocument"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetDocumentRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.Document",
+ "shortName": "get_document"
+ },
+ "description": "Sample for GetDocument",
+ "file": "discoveryengine_v1_generated_document_service_get_document_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_GetDocument_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": "discoveryengine_v1_generated_document_service_get_document_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
+ "shortName": "DocumentServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.get_document",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.GetDocument",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "GetDocument"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetDocumentRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.Document",
+ "shortName": "get_document"
+ },
+ "description": "Sample for GetDocument",
+ "file": "discoveryengine_v1_generated_document_service_get_document_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_GetDocument_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": "discoveryengine_v1_generated_document_service_get_document_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
+ "shortName": "DocumentServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.import_documents",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.ImportDocuments",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "ImportDocuments"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.ImportDocumentsRequest"
+ },
+ {
+ "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": "import_documents"
+ },
+ "description": "Sample for ImportDocuments",
+ "file": "discoveryengine_v1_generated_document_service_import_documents_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1_generated_document_service_import_documents_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
+ "shortName": "DocumentServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.import_documents",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.ImportDocuments",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "ImportDocuments"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.ImportDocumentsRequest"
+ },
+ {
+ "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": "import_documents"
+ },
+ "description": "Sample for ImportDocuments",
+ "file": "discoveryengine_v1_generated_document_service_import_documents_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_ImportDocuments_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": "discoveryengine_v1_generated_document_service_import_documents_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
+ "shortName": "DocumentServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.list_documents",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.ListDocuments",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "ListDocuments"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.ListDocumentsRequest"
+ },
+ {
+ "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.discoveryengine_v1.services.document_service.pagers.ListDocumentsAsyncPager",
+ "shortName": "list_documents"
+ },
+ "description": "Sample for ListDocuments",
+ "file": "discoveryengine_v1_generated_document_service_list_documents_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_ListDocuments_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": "discoveryengine_v1_generated_document_service_list_documents_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
+ "shortName": "DocumentServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.list_documents",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.ListDocuments",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "ListDocuments"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.ListDocumentsRequest"
+ },
+ {
+ "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.discoveryengine_v1.services.document_service.pagers.ListDocumentsPager",
+ "shortName": "list_documents"
+ },
+ "description": "Sample for ListDocuments",
+ "file": "discoveryengine_v1_generated_document_service_list_documents_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_ListDocuments_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": "discoveryengine_v1_generated_document_service_list_documents_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
+ "shortName": "DocumentServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.purge_documents",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "PurgeDocuments"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest"
+ },
+ {
+ "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": "purge_documents"
+ },
+ "description": "Sample for PurgeDocuments",
+ "file": "discoveryengine_v1_generated_document_service_purge_documents_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1_generated_document_service_purge_documents_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
+ "shortName": "DocumentServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.purge_documents",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "PurgeDocuments"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest"
+ },
+ {
+ "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": "purge_documents"
+ },
+ "description": "Sample for PurgeDocuments",
+ "file": "discoveryengine_v1_generated_document_service_purge_documents_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_PurgeDocuments_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": "discoveryengine_v1_generated_document_service_purge_documents_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
+ "shortName": "DocumentServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.update_document",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.UpdateDocument",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "UpdateDocument"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateDocumentRequest"
+ },
+ {
+ "name": "document",
+ "type": "google.cloud.discoveryengine_v1.types.Document"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.Document",
+ "shortName": "update_document"
+ },
+ "description": "Sample for UpdateDocument",
+ "file": "discoveryengine_v1_generated_document_service_update_document_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_UpdateDocument_async",
+ "segments": [
+ {
+ "end": 50,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 50,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 44,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 47,
+ "start": 45,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 51,
+ "start": 48,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_document_service_update_document_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
+ "shortName": "DocumentServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.update_document",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService.UpdateDocument",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.DocumentService",
+ "shortName": "DocumentService"
+ },
+ "shortName": "UpdateDocument"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateDocumentRequest"
+ },
+ {
+ "name": "document",
+ "type": "google.cloud.discoveryengine_v1.types.Document"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -6024,13 +9326,2042 @@
}
],
"resultType": "google.cloud.discoveryengine_v1.types.Document",
- "shortName": "get_document"
+ "shortName": "update_document"
+ },
+ "description": "Sample for UpdateDocument",
+ "file": "discoveryengine_v1_generated_document_service_update_document_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_DocumentService_UpdateDocument_sync",
+ "segments": [
+ {
+ "end": 50,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 50,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 44,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 47,
+ "start": 45,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 51,
+ "start": 48,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_document_service_update_document_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
+ "shortName": "EngineServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.create_engine",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.CreateEngine",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "CreateEngine"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CreateEngineRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "engine",
+ "type": "google.cloud.discoveryengine_v1.types.Engine"
+ },
+ {
+ "name": "engine_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_engine"
+ },
+ "description": "Sample for CreateEngine",
+ "file": "discoveryengine_v1_generated_engine_service_create_engine_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_CreateEngine_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": "discoveryengine_v1_generated_engine_service_create_engine_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
+ "shortName": "EngineServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.create_engine",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.CreateEngine",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "CreateEngine"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CreateEngineRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "engine",
+ "type": "google.cloud.discoveryengine_v1.types.Engine"
+ },
+ {
+ "name": "engine_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_engine"
+ },
+ "description": "Sample for CreateEngine",
+ "file": "discoveryengine_v1_generated_engine_service_create_engine_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_CreateEngine_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": "discoveryengine_v1_generated_engine_service_create_engine_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
+ "shortName": "EngineServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.delete_engine",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.DeleteEngine",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "DeleteEngine"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.DeleteEngineRequest"
+ },
+ {
+ "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_engine"
+ },
+ "description": "Sample for DeleteEngine",
+ "file": "discoveryengine_v1_generated_engine_service_delete_engine_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_DeleteEngine_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": "discoveryengine_v1_generated_engine_service_delete_engine_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
+ "shortName": "EngineServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.delete_engine",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.DeleteEngine",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "DeleteEngine"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.DeleteEngineRequest"
+ },
+ {
+ "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_engine"
+ },
+ "description": "Sample for DeleteEngine",
+ "file": "discoveryengine_v1_generated_engine_service_delete_engine_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_DeleteEngine_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": "discoveryengine_v1_generated_engine_service_delete_engine_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
+ "shortName": "EngineServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.get_engine",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.GetEngine",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "GetEngine"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetEngineRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.Engine",
+ "shortName": "get_engine"
+ },
+ "description": "Sample for GetEngine",
+ "file": "discoveryengine_v1_generated_engine_service_get_engine_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_GetEngine_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": "discoveryengine_v1_generated_engine_service_get_engine_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
+ "shortName": "EngineServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.get_engine",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.GetEngine",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "GetEngine"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetEngineRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.Engine",
+ "shortName": "get_engine"
+ },
+ "description": "Sample for GetEngine",
+ "file": "discoveryengine_v1_generated_engine_service_get_engine_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_GetEngine_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": "discoveryengine_v1_generated_engine_service_get_engine_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
+ "shortName": "EngineServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.get_iam_policy",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.GetIamPolicy",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "GetIamPolicy"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest"
+ },
+ {
+ "name": "resource",
+ "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.iam.v1.policy_pb2.Policy",
+ "shortName": "get_iam_policy"
+ },
+ "description": "Sample for GetIamPolicy",
+ "file": "discoveryengine_v1_generated_engine_service_get_iam_policy_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_GetIamPolicy_async",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 41,
+ "start": 39,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 42,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_engine_service_get_iam_policy_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
+ "shortName": "EngineServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.get_iam_policy",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.GetIamPolicy",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "GetIamPolicy"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.iam.v1.iam_policy_pb2.GetIamPolicyRequest"
+ },
+ {
+ "name": "resource",
+ "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.iam.v1.policy_pb2.Policy",
+ "shortName": "get_iam_policy"
+ },
+ "description": "Sample for GetIamPolicy",
+ "file": "discoveryengine_v1_generated_engine_service_get_iam_policy_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_GetIamPolicy_sync",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 41,
+ "start": 39,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 42,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_engine_service_get_iam_policy_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
+ "shortName": "EngineServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.list_engines",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.ListEngines",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "ListEngines"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.ListEnginesRequest"
+ },
+ {
+ "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.discoveryengine_v1.services.engine_service.pagers.ListEnginesAsyncPager",
+ "shortName": "list_engines"
+ },
+ "description": "Sample for ListEngines",
+ "file": "discoveryengine_v1_generated_engine_service_list_engines_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_ListEngines_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": "discoveryengine_v1_generated_engine_service_list_engines_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
+ "shortName": "EngineServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.list_engines",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.ListEngines",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "ListEngines"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.ListEnginesRequest"
+ },
+ {
+ "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.discoveryengine_v1.services.engine_service.pagers.ListEnginesPager",
+ "shortName": "list_engines"
+ },
+ "description": "Sample for ListEngines",
+ "file": "discoveryengine_v1_generated_engine_service_list_engines_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_ListEngines_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": "discoveryengine_v1_generated_engine_service_list_engines_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
+ "shortName": "EngineServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.set_iam_policy",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.SetIamPolicy",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "SetIamPolicy"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest"
+ },
+ {
+ "name": "resource",
+ "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.iam.v1.policy_pb2.Policy",
+ "shortName": "set_iam_policy"
+ },
+ "description": "Sample for SetIamPolicy",
+ "file": "discoveryengine_v1_generated_engine_service_set_iam_policy_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_SetIamPolicy_async",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 41,
+ "start": 39,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 42,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_engine_service_set_iam_policy_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
+ "shortName": "EngineServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.set_iam_policy",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.SetIamPolicy",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "SetIamPolicy"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.iam.v1.iam_policy_pb2.SetIamPolicyRequest"
+ },
+ {
+ "name": "resource",
+ "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.iam.v1.policy_pb2.Policy",
+ "shortName": "set_iam_policy"
+ },
+ "description": "Sample for SetIamPolicy",
+ "file": "discoveryengine_v1_generated_engine_service_set_iam_policy_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_SetIamPolicy_sync",
+ "segments": [
+ {
+ "end": 52,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 52,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 41,
+ "start": 39,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 46,
+ "start": 42,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 47,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 53,
+ "start": 50,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_engine_service_set_iam_policy_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
+ "shortName": "EngineServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.update_engine",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.UpdateEngine",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "UpdateEngine"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateEngineRequest"
+ },
+ {
+ "name": "engine",
+ "type": "google.cloud.discoveryengine_v1.types.Engine"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.Engine",
+ "shortName": "update_engine"
+ },
+ "description": "Sample for UpdateEngine",
+ "file": "discoveryengine_v1_generated_engine_service_update_engine_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_UpdateEngine_async",
+ "segments": [
+ {
+ "end": 55,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 55,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 52,
+ "start": 50,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 56,
+ "start": 53,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_engine_service_update_engine_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
+ "shortName": "EngineServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.update_engine",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService.UpdateEngine",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.EngineService",
+ "shortName": "EngineService"
+ },
+ "shortName": "UpdateEngine"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.UpdateEngineRequest"
+ },
+ {
+ "name": "engine",
+ "type": "google.cloud.discoveryengine_v1.types.Engine"
+ },
+ {
+ "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.cloud.discoveryengine_v1.types.Engine",
+ "shortName": "update_engine"
+ },
+ "description": "Sample for UpdateEngine",
+ "file": "discoveryengine_v1_generated_engine_service_update_engine_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_EngineService_UpdateEngine_sync",
+ "segments": [
+ {
+ "end": 55,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 55,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 49,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 52,
+ "start": 50,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 56,
+ "start": 53,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_engine_service_update_engine_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient",
+ "shortName": "GroundedGenerationServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient.check_grounding",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.CheckGrounding",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
+ "shortName": "GroundedGenerationService"
+ },
+ "shortName": "CheckGrounding"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CheckGroundingRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.cloud.discoveryengine_v1.types.CheckGroundingResponse",
+ "shortName": "check_grounding"
+ },
+ "description": "Sample for CheckGrounding",
+ "file": "discoveryengine_v1_generated_grounded_generation_service_check_grounding_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_CheckGrounding_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": "discoveryengine_v1_generated_grounded_generation_service_check_grounding_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient",
+ "shortName": "GroundedGenerationServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient.check_grounding",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.CheckGrounding",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
+ "shortName": "GroundedGenerationService"
+ },
+ "shortName": "CheckGrounding"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CheckGroundingRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.cloud.discoveryengine_v1.types.CheckGroundingResponse",
+ "shortName": "check_grounding"
+ },
+ "description": "Sample for CheckGrounding",
+ "file": "discoveryengine_v1_generated_grounded_generation_service_check_grounding_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_CheckGrounding_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": "discoveryengine_v1_generated_grounded_generation_service_check_grounding_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient",
+ "shortName": "GroundedGenerationServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient.generate_grounded_content",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.GenerateGroundedContent",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
+ "shortName": "GroundedGenerationService"
+ },
+ "shortName": "GenerateGroundedContent"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse",
+ "shortName": "generate_grounded_content"
+ },
+ "description": "Sample for GenerateGroundedContent",
+ "file": "discoveryengine_v1_generated_grounded_generation_service_generate_grounded_content_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_GenerateGroundedContent_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": "discoveryengine_v1_generated_grounded_generation_service_generate_grounded_content_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient",
+ "shortName": "GroundedGenerationServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient.generate_grounded_content",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.GenerateGroundedContent",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
+ "shortName": "GroundedGenerationService"
+ },
+ "shortName": "GenerateGroundedContent"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse",
+ "shortName": "generate_grounded_content"
+ },
+ "description": "Sample for GenerateGroundedContent",
+ "file": "discoveryengine_v1_generated_grounded_generation_service_generate_grounded_content_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_GenerateGroundedContent_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": "discoveryengine_v1_generated_grounded_generation_service_generate_grounded_content_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient",
+ "shortName": "GroundedGenerationServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient.stream_generate_grounded_content",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.StreamGenerateGroundedContent",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
+ "shortName": "GroundedGenerationService"
+ },
+ "shortName": "StreamGenerateGroundedContent"
+ },
+ "parameters": [
+ {
+ "name": "requests",
+ "type": "Iterator[google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest]"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "Iterable[google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse]",
+ "shortName": "stream_generate_grounded_content"
+ },
+ "description": "Sample for StreamGenerateGroundedContent",
+ "file": "discoveryengine_v1_generated_grounded_generation_service_stream_generate_grounded_content_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_StreamGenerateGroundedContent_async",
+ "segments": [
+ {
+ "end": 62,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 62,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 55,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 58,
+ "start": 56,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 63,
+ "start": 59,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_grounded_generation_service_stream_generate_grounded_content_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient",
+ "shortName": "GroundedGenerationServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient.stream_generate_grounded_content",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.StreamGenerateGroundedContent",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
+ "shortName": "GroundedGenerationService"
+ },
+ "shortName": "StreamGenerateGroundedContent"
+ },
+ "parameters": [
+ {
+ "name": "requests",
+ "type": "Iterator[google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest]"
+ },
+ {
+ "name": "retry",
+ "type": "google.api_core.retry.Retry"
+ },
+ {
+ "name": "timeout",
+ "type": "float"
+ },
+ {
+ "name": "metadata",
+ "type": "Sequence[Tuple[str, Union[str, bytes]]]"
+ }
+ ],
+ "resultType": "Iterable[google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse]",
+ "shortName": "stream_generate_grounded_content"
+ },
+ "description": "Sample for StreamGenerateGroundedContent",
+ "file": "discoveryengine_v1_generated_grounded_generation_service_stream_generate_grounded_content_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_StreamGenerateGroundedContent_sync",
+ "segments": [
+ {
+ "end": 62,
+ "start": 27,
+ "type": "FULL"
+ },
+ {
+ "end": 62,
+ "start": 27,
+ "type": "SHORT"
+ },
+ {
+ "end": 40,
+ "start": 38,
+ "type": "CLIENT_INITIALIZATION"
+ },
+ {
+ "end": 55,
+ "start": 41,
+ "type": "REQUEST_INITIALIZATION"
+ },
+ {
+ "end": 58,
+ "start": 56,
+ "type": "REQUEST_EXECUTION"
+ },
+ {
+ "end": 63,
+ "start": 59,
+ "type": "RESPONSE_HANDLING"
+ }
+ ],
+ "title": "discoveryengine_v1_generated_grounded_generation_service_stream_generate_grounded_content_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
+ "shortName": "IdentityMappingStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.create_identity_mapping_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.CreateIdentityMappingStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
+ },
+ "shortName": "CreateIdentityMappingStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CreateIdentityMappingStoreRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "identity_mapping_store",
+ "type": "google.cloud.discoveryengine_v1.types.IdentityMappingStore"
+ },
+ {
+ "name": "identity_mapping_store_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.cloud.discoveryengine_v1.types.IdentityMappingStore",
+ "shortName": "create_identity_mapping_store"
+ },
+ "description": "Sample for CreateIdentityMappingStore",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_create_identity_mapping_store_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_CreateIdentityMappingStore_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": "discoveryengine_v1_generated_identity_mapping_store_service_create_identity_mapping_store_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
+ "shortName": "IdentityMappingStoreServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.create_identity_mapping_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.CreateIdentityMappingStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
+ },
+ "shortName": "CreateIdentityMappingStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.CreateIdentityMappingStoreRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "identity_mapping_store",
+ "type": "google.cloud.discoveryengine_v1.types.IdentityMappingStore"
+ },
+ {
+ "name": "identity_mapping_store_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.cloud.discoveryengine_v1.types.IdentityMappingStore",
+ "shortName": "create_identity_mapping_store"
+ },
+ "description": "Sample for CreateIdentityMappingStore",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_create_identity_mapping_store_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_CreateIdentityMappingStore_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": "discoveryengine_v1_generated_identity_mapping_store_service_create_identity_mapping_store_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
+ "shortName": "IdentityMappingStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.delete_identity_mapping_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.DeleteIdentityMappingStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
+ },
+ "shortName": "DeleteIdentityMappingStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.DeleteIdentityMappingStoreRequest"
+ },
+ {
+ "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_identity_mapping_store"
},
- "description": "Sample for GetDocument",
- "file": "discoveryengine_v1_generated_document_service_get_document_async.py",
+ "description": "Sample for DeleteIdentityMappingStore",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_delete_identity_mapping_store_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_GetDocument_async",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_DeleteIdentityMappingStore_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": "discoveryengine_v1_generated_identity_mapping_store_service_delete_identity_mapping_store_async.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
+ "shortName": "IdentityMappingStoreServiceClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.delete_identity_mapping_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.DeleteIdentityMappingStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
+ },
+ "shortName": "DeleteIdentityMappingStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.DeleteIdentityMappingStoreRequest"
+ },
+ {
+ "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_identity_mapping_store"
+ },
+ "description": "Sample for DeleteIdentityMappingStore",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_delete_identity_mapping_store_sync.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_DeleteIdentityMappingStore_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": "discoveryengine_v1_generated_identity_mapping_store_service_delete_identity_mapping_store_sync.py"
+ },
+ {
+ "canonical": true,
+ "clientMethod": {
+ "async": true,
+ "client": {
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
+ "shortName": "IdentityMappingStoreServiceAsyncClient"
+ },
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.get_identity_mapping_store",
+ "method": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.GetIdentityMappingStore",
+ "service": {
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
+ },
+ "shortName": "GetIdentityMappingStore"
+ },
+ "parameters": [
+ {
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetIdentityMappingStoreRequest"
+ },
+ {
+ "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.discoveryengine_v1.types.IdentityMappingStore",
+ "shortName": "get_identity_mapping_store"
+ },
+ "description": "Sample for GetIdentityMappingStore",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_get_identity_mapping_store_async.py",
+ "language": "PYTHON",
+ "origin": "API_DEFINITION",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_GetIdentityMappingStore_async",
"segments": [
{
"end": 51,
@@ -6063,28 +11394,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_get_document_async.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_get_identity_mapping_store_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
- "shortName": "DocumentServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
+ "shortName": "IdentityMappingStoreServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.get_document",
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.get_identity_mapping_store",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.GetDocument",
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.GetIdentityMappingStore",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
},
- "shortName": "GetDocument"
+ "shortName": "GetIdentityMappingStore"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetDocumentRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetIdentityMappingStoreRequest"
},
{
"name": "name",
@@ -6103,14 +11434,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Document",
- "shortName": "get_document"
+ "resultType": "google.cloud.discoveryengine_v1.types.IdentityMappingStore",
+ "shortName": "get_identity_mapping_store"
},
- "description": "Sample for GetDocument",
- "file": "discoveryengine_v1_generated_document_service_get_document_sync.py",
+ "description": "Sample for GetIdentityMappingStore",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_get_identity_mapping_store_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_GetDocument_sync",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_GetIdentityMappingStore_sync",
"segments": [
{
"end": 51,
@@ -6143,29 +11474,29 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_get_document_sync.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_get_identity_mapping_store_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
- "shortName": "DocumentServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
+ "shortName": "IdentityMappingStoreServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.import_documents",
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.import_identity_mappings",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.ImportDocuments",
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ImportIdentityMappings",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
},
- "shortName": "ImportDocuments"
+ "shortName": "ImportIdentityMappings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportDocumentsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ImportIdentityMappingsRequest"
},
{
"name": "retry",
@@ -6181,13 +11512,13 @@
}
],
"resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "import_documents"
+ "shortName": "import_identity_mappings"
},
- "description": "Sample for ImportDocuments",
- "file": "discoveryengine_v1_generated_document_service_import_documents_async.py",
+ "description": "Sample for ImportIdentityMappings",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_import_identity_mappings_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_ImportDocuments_async",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ImportIdentityMappings_async",
"segments": [
{
"end": 55,
@@ -6220,28 +11551,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_import_documents_async.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_import_identity_mappings_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
- "shortName": "DocumentServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
+ "shortName": "IdentityMappingStoreServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.import_documents",
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.import_identity_mappings",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.ImportDocuments",
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ImportIdentityMappings",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
},
- "shortName": "ImportDocuments"
+ "shortName": "ImportIdentityMappings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportDocumentsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ImportIdentityMappingsRequest"
},
{
"name": "retry",
@@ -6257,13 +11588,13 @@
}
],
"resultType": "google.api_core.operation.Operation",
- "shortName": "import_documents"
+ "shortName": "import_identity_mappings"
},
- "description": "Sample for ImportDocuments",
- "file": "discoveryengine_v1_generated_document_service_import_documents_sync.py",
+ "description": "Sample for ImportIdentityMappings",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_import_identity_mappings_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_ImportDocuments_sync",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ImportIdentityMappings_sync",
"segments": [
{
"end": 55,
@@ -6296,29 +11627,29 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_import_documents_sync.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_import_identity_mappings_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
- "shortName": "DocumentServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
+ "shortName": "IdentityMappingStoreServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.list_documents",
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.list_identity_mapping_stores",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.ListDocuments",
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ListIdentityMappingStores",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
},
- "shortName": "ListDocuments"
+ "shortName": "ListIdentityMappingStores"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListDocumentsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListIdentityMappingStoresRequest"
},
{
"name": "parent",
@@ -6337,14 +11668,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsAsyncPager",
- "shortName": "list_documents"
+ "resultType": "google.cloud.discoveryengine_v1.services.identity_mapping_store_service.pagers.ListIdentityMappingStoresAsyncPager",
+ "shortName": "list_identity_mapping_stores"
},
- "description": "Sample for ListDocuments",
- "file": "discoveryengine_v1_generated_document_service_list_documents_async.py",
+ "description": "Sample for ListIdentityMappingStores",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mapping_stores_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_ListDocuments_async",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ListIdentityMappingStores_async",
"segments": [
{
"end": 52,
@@ -6377,28 +11708,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_list_documents_async.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mapping_stores_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
- "shortName": "DocumentServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
+ "shortName": "IdentityMappingStoreServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.list_documents",
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.list_identity_mapping_stores",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.ListDocuments",
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ListIdentityMappingStores",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
},
- "shortName": "ListDocuments"
+ "shortName": "ListIdentityMappingStores"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListDocumentsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListIdentityMappingStoresRequest"
},
{
"name": "parent",
@@ -6417,14 +11748,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.document_service.pagers.ListDocumentsPager",
- "shortName": "list_documents"
+ "resultType": "google.cloud.discoveryengine_v1.services.identity_mapping_store_service.pagers.ListIdentityMappingStoresPager",
+ "shortName": "list_identity_mapping_stores"
},
- "description": "Sample for ListDocuments",
- "file": "discoveryengine_v1_generated_document_service_list_documents_sync.py",
+ "description": "Sample for ListIdentityMappingStores",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mapping_stores_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_ListDocuments_sync",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ListIdentityMappingStores_sync",
"segments": [
{
"end": 52,
@@ -6457,29 +11788,29 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_list_documents_sync.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mapping_stores_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
- "shortName": "DocumentServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
+ "shortName": "IdentityMappingStoreServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.purge_documents",
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.list_identity_mappings",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments",
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ListIdentityMappings",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
},
- "shortName": "PurgeDocuments"
+ "shortName": "ListIdentityMappings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListIdentityMappingsRequest"
},
{
"name": "retry",
@@ -6494,22 +11825,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "purge_documents"
+ "resultType": "google.cloud.discoveryengine_v1.services.identity_mapping_store_service.pagers.ListIdentityMappingsAsyncPager",
+ "shortName": "list_identity_mappings"
},
- "description": "Sample for PurgeDocuments",
- "file": "discoveryengine_v1_generated_document_service_purge_documents_async.py",
+ "description": "Sample for ListIdentityMappings",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mappings_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_PurgeDocuments_async",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ListIdentityMappings_async",
"segments": [
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -6519,43 +11850,43 @@
"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": "discoveryengine_v1_generated_document_service_purge_documents_async.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mappings_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
- "shortName": "DocumentServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
+ "shortName": "IdentityMappingStoreServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.purge_documents",
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.list_identity_mappings",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.PurgeDocuments",
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ListIdentityMappings",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
},
- "shortName": "PurgeDocuments"
+ "shortName": "ListIdentityMappings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeDocumentsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListIdentityMappingsRequest"
},
{
"name": "retry",
@@ -6570,22 +11901,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "purge_documents"
+ "resultType": "google.cloud.discoveryengine_v1.services.identity_mapping_store_service.pagers.ListIdentityMappingsPager",
+ "shortName": "list_identity_mappings"
},
- "description": "Sample for PurgeDocuments",
- "file": "discoveryengine_v1_generated_document_service_purge_documents_sync.py",
+ "description": "Sample for ListIdentityMappings",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mappings_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_PurgeDocuments_sync",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ListIdentityMappings_sync",
"segments": [
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -6595,52 +11926,44 @@
"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": "discoveryengine_v1_generated_document_service_purge_documents_sync.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mappings_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient",
- "shortName": "DocumentServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
+ "shortName": "IdentityMappingStoreServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceAsyncClient.update_document",
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.purge_identity_mappings",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.UpdateDocument",
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.PurgeIdentityMappings",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
},
- "shortName": "UpdateDocument"
+ "shortName": "PurgeIdentityMappings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateDocumentRequest"
- },
- {
- "name": "document",
- "type": "google.cloud.discoveryengine_v1.types.Document"
- },
- {
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "type": "google.cloud.discoveryengine_v1.types.PurgeIdentityMappingsRequest"
},
{
"name": "retry",
@@ -6655,22 +11978,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Document",
- "shortName": "update_document"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "purge_identity_mappings"
},
- "description": "Sample for UpdateDocument",
- "file": "discoveryengine_v1_generated_document_service_update_document_async.py",
+ "description": "Sample for PurgeIdentityMappings",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_purge_identity_mappings_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_UpdateDocument_async",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_PurgeIdentityMappings_async",
"segments": [
{
- "end": 50,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 50,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -6680,51 +12003,43 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 47,
- "start": 45,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 51,
- "start": 48,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_update_document_async.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_purge_identity_mappings_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient",
- "shortName": "DocumentServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
+ "shortName": "IdentityMappingStoreServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.DocumentServiceClient.update_document",
+ "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.purge_identity_mappings",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService.UpdateDocument",
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.PurgeIdentityMappings",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.DocumentService",
- "shortName": "DocumentService"
+ "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
+ "shortName": "IdentityMappingStoreService"
},
- "shortName": "UpdateDocument"
+ "shortName": "PurgeIdentityMappings"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateDocumentRequest"
- },
- {
- "name": "document",
- "type": "google.cloud.discoveryengine_v1.types.Document"
- },
- {
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "type": "google.cloud.discoveryengine_v1.types.PurgeIdentityMappingsRequest"
},
{
"name": "retry",
@@ -6739,22 +12054,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Document",
- "shortName": "update_document"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "purge_identity_mappings"
},
- "description": "Sample for UpdateDocument",
- "file": "discoveryengine_v1_generated_document_service_update_document_sync.py",
+ "description": "Sample for PurgeIdentityMappings",
+ "file": "discoveryengine_v1_generated_identity_mapping_store_service_purge_identity_mappings_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_DocumentService_UpdateDocument_sync",
+ "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_PurgeIdentityMappings_sync",
"segments": [
{
- "end": 50,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 50,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -6764,55 +12079,55 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 47,
- "start": 45,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 51,
- "start": 48,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_document_service_update_document_sync.py"
+ "title": "discoveryengine_v1_generated_identity_mapping_store_service_purge_identity_mappings_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
- "shortName": "EngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient",
+ "shortName": "LicenseConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.create_engine",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient.create_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.CreateEngine",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.CreateLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "CreateEngine"
+ "shortName": "CreateLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateEngineRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateLicenseConfigRequest"
},
{
"name": "parent",
"type": "str"
},
{
- "name": "engine",
- "type": "google.cloud.discoveryengine_v1.types.Engine"
+ "name": "license_config",
+ "type": "google.cloud.discoveryengine_v1.types.LicenseConfig"
},
{
- "name": "engine_id",
+ "name": "license_config_id",
"type": "str"
},
{
@@ -6828,22 +12143,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "create_engine"
+ "resultType": "google.cloud.discoveryengine_v1.types.LicenseConfig",
+ "shortName": "create_license_config"
},
- "description": "Sample for CreateEngine",
- "file": "discoveryengine_v1_generated_engine_service_create_engine_async.py",
+ "description": "Sample for CreateLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_create_license_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_CreateEngine_async",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_CreateLicenseConfig_async",
"segments": [
{
- "end": 61,
+ "end": 57,
"start": 27,
"type": "FULL"
},
{
- "end": 61,
+ "end": 57,
"start": 27,
"type": "SHORT"
},
@@ -6858,49 +12173,49 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 58,
+ "end": 54,
"start": 52,
"type": "REQUEST_EXECUTION"
},
{
- "end": 62,
- "start": 59,
+ "end": 58,
+ "start": 55,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_create_engine_async.py"
+ "title": "discoveryengine_v1_generated_license_config_service_create_license_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
- "shortName": "EngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient",
+ "shortName": "LicenseConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.create_engine",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient.create_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.CreateEngine",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.CreateLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "CreateEngine"
+ "shortName": "CreateLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateEngineRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateLicenseConfigRequest"
},
{
"name": "parent",
"type": "str"
},
{
- "name": "engine",
- "type": "google.cloud.discoveryengine_v1.types.Engine"
+ "name": "license_config",
+ "type": "google.cloud.discoveryengine_v1.types.LicenseConfig"
},
{
- "name": "engine_id",
+ "name": "license_config_id",
"type": "str"
},
{
@@ -6916,22 +12231,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "create_engine"
+ "resultType": "google.cloud.discoveryengine_v1.types.LicenseConfig",
+ "shortName": "create_license_config"
},
- "description": "Sample for CreateEngine",
- "file": "discoveryengine_v1_generated_engine_service_create_engine_sync.py",
+ "description": "Sample for CreateLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_create_license_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_CreateEngine_sync",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_CreateLicenseConfig_sync",
"segments": [
{
- "end": 61,
+ "end": 57,
"start": 27,
"type": "FULL"
},
{
- "end": 61,
+ "end": 57,
"start": 27,
"type": "SHORT"
},
@@ -6946,42 +12261,58 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 58,
+ "end": 54,
"start": 52,
"type": "REQUEST_EXECUTION"
},
{
- "end": 62,
- "start": 59,
+ "end": 58,
+ "start": 55,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_create_engine_sync.py"
+ "title": "discoveryengine_v1_generated_license_config_service_create_license_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
- "shortName": "EngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient",
+ "shortName": "LicenseConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.delete_engine",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient.distribute_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.DeleteEngine",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "DeleteEngine"
+ "shortName": "DistributeLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteEngineRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DistributeLicenseConfigRequest"
},
{
- "name": "name",
+ "name": "billing_account_license_config",
+ "type": "str"
+ },
+ {
+ "name": "project_number",
+ "type": "int"
+ },
+ {
+ "name": "location",
+ "type": "str"
+ },
+ {
+ "name": "license_count",
+ "type": "int"
+ },
+ {
+ "name": "license_config_id",
"type": "str"
},
{
@@ -6997,22 +12328,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "delete_engine"
+ "resultType": "google.cloud.discoveryengine_v1.types.DistributeLicenseConfigResponse",
+ "shortName": "distribute_license_config"
},
- "description": "Sample for DeleteEngine",
- "file": "discoveryengine_v1_generated_engine_service_delete_engine_async.py",
+ "description": "Sample for DistributeLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_distribute_license_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_DeleteEngine_async",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_DistributeLicenseConfig_async",
"segments": [
{
- "end": 55,
+ "end": 54,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 54,
"start": 27,
"type": "SHORT"
},
@@ -7022,46 +12353,62 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 48,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 46,
+ "end": 51,
+ "start": 49,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 55,
+ "start": 52,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_delete_engine_async.py"
+ "title": "discoveryengine_v1_generated_license_config_service_distribute_license_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
- "shortName": "EngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient",
+ "shortName": "LicenseConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.delete_engine",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient.distribute_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.DeleteEngine",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.DistributeLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "DeleteEngine"
+ "shortName": "DistributeLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteEngineRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DistributeLicenseConfigRequest"
},
{
- "name": "name",
+ "name": "billing_account_license_config",
+ "type": "str"
+ },
+ {
+ "name": "project_number",
+ "type": "int"
+ },
+ {
+ "name": "location",
+ "type": "str"
+ },
+ {
+ "name": "license_count",
+ "type": "int"
+ },
+ {
+ "name": "license_config_id",
"type": "str"
},
{
@@ -7077,22 +12424,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "delete_engine"
+ "resultType": "google.cloud.discoveryengine_v1.types.DistributeLicenseConfigResponse",
+ "shortName": "distribute_license_config"
},
- "description": "Sample for DeleteEngine",
- "file": "discoveryengine_v1_generated_engine_service_delete_engine_sync.py",
+ "description": "Sample for DistributeLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_distribute_license_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_DeleteEngine_sync",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_DistributeLicenseConfig_sync",
"segments": [
{
- "end": 55,
+ "end": 54,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 54,
"start": 27,
"type": "SHORT"
},
@@ -7102,44 +12449,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 48,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 46,
+ "end": 51,
+ "start": 49,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 55,
+ "start": 52,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_delete_engine_sync.py"
+ "title": "discoveryengine_v1_generated_license_config_service_distribute_license_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
- "shortName": "EngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient",
+ "shortName": "LicenseConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.get_engine",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient.get_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.GetEngine",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.GetLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "GetEngine"
+ "shortName": "GetLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetEngineRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetLicenseConfigRequest"
},
{
"name": "name",
@@ -7158,14 +12505,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Engine",
- "shortName": "get_engine"
+ "resultType": "google.cloud.discoveryengine_v1.types.LicenseConfig",
+ "shortName": "get_license_config"
},
- "description": "Sample for GetEngine",
- "file": "discoveryengine_v1_generated_engine_service_get_engine_async.py",
+ "description": "Sample for GetLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_get_license_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_GetEngine_async",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_GetLicenseConfig_async",
"segments": [
{
"end": 51,
@@ -7198,28 +12545,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_get_engine_async.py"
+ "title": "discoveryengine_v1_generated_license_config_service_get_license_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
- "shortName": "EngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient",
+ "shortName": "LicenseConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.get_engine",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient.get_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.GetEngine",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.GetLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "GetEngine"
+ "shortName": "GetLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetEngineRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetLicenseConfigRequest"
},
{
"name": "name",
@@ -7238,14 +12585,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Engine",
- "shortName": "get_engine"
+ "resultType": "google.cloud.discoveryengine_v1.types.LicenseConfig",
+ "shortName": "get_license_config"
},
- "description": "Sample for GetEngine",
- "file": "discoveryengine_v1_generated_engine_service_get_engine_sync.py",
+ "description": "Sample for GetLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_get_license_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_GetEngine_sync",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_GetLicenseConfig_sync",
"segments": [
{
"end": 51,
@@ -7278,29 +12625,29 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_get_engine_sync.py"
+ "title": "discoveryengine_v1_generated_license_config_service_get_license_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
- "shortName": "EngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient",
+ "shortName": "LicenseConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.list_engines",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient.list_license_configs",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.ListEngines",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "ListEngines"
+ "shortName": "ListLicenseConfigs"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListEnginesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListLicenseConfigsRequest"
},
{
"name": "parent",
@@ -7319,14 +12666,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.engine_service.pagers.ListEnginesAsyncPager",
- "shortName": "list_engines"
+ "resultType": "google.cloud.discoveryengine_v1.services.license_config_service.pagers.ListLicenseConfigsAsyncPager",
+ "shortName": "list_license_configs"
},
- "description": "Sample for ListEngines",
- "file": "discoveryengine_v1_generated_engine_service_list_engines_async.py",
+ "description": "Sample for ListLicenseConfigs",
+ "file": "discoveryengine_v1_generated_license_config_service_list_license_configs_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_ListEngines_async",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_ListLicenseConfigs_async",
"segments": [
{
"end": 52,
@@ -7359,28 +12706,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_list_engines_async.py"
+ "title": "discoveryengine_v1_generated_license_config_service_list_license_configs_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
- "shortName": "EngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient",
+ "shortName": "LicenseConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.list_engines",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient.list_license_configs",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.ListEngines",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.ListLicenseConfigs",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "ListEngines"
+ "shortName": "ListLicenseConfigs"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListEnginesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListLicenseConfigsRequest"
},
{
"name": "parent",
@@ -7399,14 +12746,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.engine_service.pagers.ListEnginesPager",
- "shortName": "list_engines"
+ "resultType": "google.cloud.discoveryengine_v1.services.license_config_service.pagers.ListLicenseConfigsPager",
+ "shortName": "list_license_configs"
},
- "description": "Sample for ListEngines",
- "file": "discoveryengine_v1_generated_engine_service_list_engines_sync.py",
+ "description": "Sample for ListLicenseConfigs",
+ "file": "discoveryengine_v1_generated_license_config_service_list_license_configs_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_ListEngines_sync",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_ListLicenseConfigs_sync",
"segments": [
{
"end": 52,
@@ -7439,37 +12786,45 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_list_engines_sync.py"
+ "title": "discoveryengine_v1_generated_license_config_service_list_license_configs_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient",
- "shortName": "EngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient",
+ "shortName": "LicenseConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceAsyncClient.update_engine",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient.retract_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.UpdateEngine",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "UpdateEngine"
+ "shortName": "RetractLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateEngineRequest"
+ "type": "google.cloud.discoveryengine_v1.types.RetractLicenseConfigRequest"
},
{
- "name": "engine",
- "type": "google.cloud.discoveryengine_v1.types.Engine"
+ "name": "billing_account_license_config",
+ "type": "str"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "license_config",
+ "type": "str"
+ },
+ {
+ "name": "full_retract",
+ "type": "bool"
+ },
+ {
+ "name": "license_count",
+ "type": "int"
},
{
"name": "retry",
@@ -7484,22 +12839,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Engine",
- "shortName": "update_engine"
+ "resultType": "google.cloud.discoveryengine_v1.types.RetractLicenseConfigResponse",
+ "shortName": "retract_license_config"
},
- "description": "Sample for UpdateEngine",
- "file": "discoveryengine_v1_generated_engine_service_update_engine_async.py",
+ "description": "Sample for RetractLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_retract_license_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_UpdateEngine_async",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_RetractLicenseConfig_async",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -7509,51 +12864,59 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 46,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 50,
+ "end": 49,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 53,
+ "start": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_update_engine_async.py"
+ "title": "discoveryengine_v1_generated_license_config_service_retract_license_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient",
- "shortName": "EngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient",
+ "shortName": "LicenseConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.EngineServiceClient.update_engine",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient.retract_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService.UpdateEngine",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.RetractLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.EngineService",
- "shortName": "EngineService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "UpdateEngine"
+ "shortName": "RetractLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateEngineRequest"
+ "type": "google.cloud.discoveryengine_v1.types.RetractLicenseConfigRequest"
},
{
- "name": "engine",
- "type": "google.cloud.discoveryengine_v1.types.Engine"
+ "name": "billing_account_license_config",
+ "type": "str"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "license_config",
+ "type": "str"
+ },
+ {
+ "name": "full_retract",
+ "type": "bool"
+ },
+ {
+ "name": "license_count",
+ "type": "int"
},
{
"name": "retry",
@@ -7568,22 +12931,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Engine",
- "shortName": "update_engine"
+ "resultType": "google.cloud.discoveryengine_v1.types.RetractLicenseConfigResponse",
+ "shortName": "retract_license_config"
},
- "description": "Sample for UpdateEngine",
- "file": "discoveryengine_v1_generated_engine_service_update_engine_sync.py",
+ "description": "Sample for RetractLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_retract_license_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_EngineService_UpdateEngine_sync",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_RetractLicenseConfig_sync",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -7593,44 +12956,52 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 46,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 50,
+ "end": 49,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 53,
+ "start": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_engine_service_update_engine_sync.py"
+ "title": "discoveryengine_v1_generated_license_config_service_retract_license_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient",
- "shortName": "GroundedGenerationServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient",
+ "shortName": "LicenseConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient.check_grounding",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceAsyncClient.update_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.CheckGrounding",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.UpdateLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
- "shortName": "GroundedGenerationService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "CheckGrounding"
+ "shortName": "UpdateLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CheckGroundingRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateLicenseConfigRequest"
+ },
+ {
+ "name": "license_config",
+ "type": "google.cloud.discoveryengine_v1.types.LicenseConfig"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -7645,22 +13016,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.CheckGroundingResponse",
- "shortName": "check_grounding"
+ "resultType": "google.cloud.discoveryengine_v1.types.LicenseConfig",
+ "shortName": "update_license_config"
},
- "description": "Sample for CheckGrounding",
- "file": "discoveryengine_v1_generated_grounded_generation_service_check_grounding_async.py",
+ "description": "Sample for UpdateLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_update_license_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_CheckGrounding_async",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_UpdateLicenseConfig_async",
"segments": [
{
- "end": 51,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -7670,43 +13041,51 @@
"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": "discoveryengine_v1_generated_grounded_generation_service_check_grounding_async.py"
+ "title": "discoveryengine_v1_generated_license_config_service_update_license_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient",
- "shortName": "GroundedGenerationServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient",
+ "shortName": "LicenseConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient.check_grounding",
+ "fullName": "google.cloud.discoveryengine_v1.LicenseConfigServiceClient.update_license_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.CheckGrounding",
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService.UpdateLicenseConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
- "shortName": "GroundedGenerationService"
+ "fullName": "google.cloud.discoveryengine.v1.LicenseConfigService",
+ "shortName": "LicenseConfigService"
},
- "shortName": "CheckGrounding"
+ "shortName": "UpdateLicenseConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CheckGroundingRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateLicenseConfigRequest"
+ },
+ {
+ "name": "license_config",
+ "type": "google.cloud.discoveryengine_v1.types.LicenseConfig"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -7721,22 +13100,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.CheckGroundingResponse",
- "shortName": "check_grounding"
+ "resultType": "google.cloud.discoveryengine_v1.types.LicenseConfig",
+ "shortName": "update_license_config"
},
- "description": "Sample for CheckGrounding",
- "file": "discoveryengine_v1_generated_grounded_generation_service_check_grounding_sync.py",
+ "description": "Sample for UpdateLicenseConfig",
+ "file": "discoveryengine_v1_generated_license_config_service_update_license_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_CheckGrounding_sync",
+ "regionTag": "discoveryengine_v1_generated_LicenseConfigService_UpdateLicenseConfig_sync",
"segments": [
{
- "end": 51,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -7746,44 +13125,48 @@
"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": "discoveryengine_v1_generated_grounded_generation_service_check_grounding_sync.py"
+ "title": "discoveryengine_v1_generated_license_config_service_update_license_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient",
- "shortName": "GroundedGenerationServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ProjectServiceAsyncClient",
+ "shortName": "ProjectServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient.generate_grounded_content",
+ "fullName": "google.cloud.discoveryengine_v1.ProjectServiceAsyncClient.provision_project",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.GenerateGroundedContent",
+ "fullName": "google.cloud.discoveryengine.v1.ProjectService.ProvisionProject",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
- "shortName": "GroundedGenerationService"
+ "fullName": "google.cloud.discoveryengine.v1.ProjectService",
+ "shortName": "ProjectService"
},
- "shortName": "GenerateGroundedContent"
+ "shortName": "ProvisionProject"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ProvisionProjectRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -7798,22 +13181,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse",
- "shortName": "generate_grounded_content"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "provision_project"
},
- "description": "Sample for GenerateGroundedContent",
- "file": "discoveryengine_v1_generated_grounded_generation_service_generate_grounded_content_async.py",
+ "description": "Sample for ProvisionProject",
+ "file": "discoveryengine_v1_generated_project_service_provision_project_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_GenerateGroundedContent_async",
+ "regionTag": "discoveryengine_v1_generated_ProjectService_ProvisionProject_async",
"segments": [
{
- "end": 51,
+ "end": 57,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 57,
"start": 27,
"type": "SHORT"
},
@@ -7823,43 +13206,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 47,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 54,
+ "start": 48,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 58,
+ "start": 55,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_grounded_generation_service_generate_grounded_content_async.py"
+ "title": "discoveryengine_v1_generated_project_service_provision_project_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient",
- "shortName": "GroundedGenerationServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ProjectServiceClient",
+ "shortName": "ProjectServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient.generate_grounded_content",
+ "fullName": "google.cloud.discoveryengine_v1.ProjectServiceClient.provision_project",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.GenerateGroundedContent",
+ "fullName": "google.cloud.discoveryengine.v1.ProjectService.ProvisionProject",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
- "shortName": "GroundedGenerationService"
+ "fullName": "google.cloud.discoveryengine.v1.ProjectService",
+ "shortName": "ProjectService"
},
- "shortName": "GenerateGroundedContent"
+ "shortName": "ProvisionProject"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ProvisionProjectRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -7874,22 +13261,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse",
- "shortName": "generate_grounded_content"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "provision_project"
},
- "description": "Sample for GenerateGroundedContent",
- "file": "discoveryengine_v1_generated_grounded_generation_service_generate_grounded_content_sync.py",
+ "description": "Sample for ProvisionProject",
+ "file": "discoveryengine_v1_generated_project_service_provision_project_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_GenerateGroundedContent_sync",
+ "regionTag": "discoveryengine_v1_generated_ProjectService_ProvisionProject_sync",
"segments": [
{
- "end": 51,
+ "end": 57,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 57,
"start": 27,
"type": "SHORT"
},
@@ -7899,44 +13286,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 47,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 54,
+ "start": 48,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 58,
+ "start": 55,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_grounded_generation_service_generate_grounded_content_sync.py"
+ "title": "discoveryengine_v1_generated_project_service_provision_project_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient",
- "shortName": "GroundedGenerationServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.RankServiceAsyncClient",
+ "shortName": "RankServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceAsyncClient.stream_generate_grounded_content",
+ "fullName": "google.cloud.discoveryengine_v1.RankServiceAsyncClient.rank",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.StreamGenerateGroundedContent",
+ "fullName": "google.cloud.discoveryengine.v1.RankService.Rank",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
- "shortName": "GroundedGenerationService"
+ "fullName": "google.cloud.discoveryengine.v1.RankService",
+ "shortName": "RankService"
},
- "shortName": "StreamGenerateGroundedContent"
+ "shortName": "Rank"
},
"parameters": [
{
- "name": "requests",
- "type": "Iterator[google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest]"
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.RankRequest"
},
{
"name": "retry",
@@ -7951,22 +13338,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "Iterable[google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse]",
- "shortName": "stream_generate_grounded_content"
+ "resultType": "google.cloud.discoveryengine_v1.types.RankResponse",
+ "shortName": "rank"
},
- "description": "Sample for StreamGenerateGroundedContent",
- "file": "discoveryengine_v1_generated_grounded_generation_service_stream_generate_grounded_content_async.py",
+ "description": "Sample for Rank",
+ "file": "discoveryengine_v1_generated_rank_service_rank_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_StreamGenerateGroundedContent_async",
+ "regionTag": "discoveryengine_v1_generated_RankService_Rank_async",
"segments": [
{
- "end": 62,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 62,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -7976,43 +13363,43 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 55,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 58,
- "start": 56,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 63,
- "start": 59,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_grounded_generation_service_stream_generate_grounded_content_async.py"
+ "title": "discoveryengine_v1_generated_rank_service_rank_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient",
- "shortName": "GroundedGenerationServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.RankServiceClient",
+ "shortName": "RankServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.GroundedGenerationServiceClient.stream_generate_grounded_content",
+ "fullName": "google.cloud.discoveryengine_v1.RankServiceClient.rank",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService.StreamGenerateGroundedContent",
+ "fullName": "google.cloud.discoveryengine.v1.RankService.Rank",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.GroundedGenerationService",
- "shortName": "GroundedGenerationService"
+ "fullName": "google.cloud.discoveryengine.v1.RankService",
+ "shortName": "RankService"
},
- "shortName": "StreamGenerateGroundedContent"
+ "shortName": "Rank"
},
"parameters": [
{
- "name": "requests",
- "type": "Iterator[google.cloud.discoveryengine_v1.types.GenerateGroundedContentRequest]"
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.RankRequest"
},
{
"name": "retry",
@@ -8027,22 +13414,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "Iterable[google.cloud.discoveryengine_v1.types.GenerateGroundedContentResponse]",
- "shortName": "stream_generate_grounded_content"
+ "resultType": "google.cloud.discoveryengine_v1.types.RankResponse",
+ "shortName": "rank"
},
- "description": "Sample for StreamGenerateGroundedContent",
- "file": "discoveryengine_v1_generated_grounded_generation_service_stream_generate_grounded_content_sync.py",
+ "description": "Sample for Rank",
+ "file": "discoveryengine_v1_generated_rank_service_rank_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_GroundedGenerationService_StreamGenerateGroundedContent_sync",
+ "regionTag": "discoveryengine_v1_generated_RankService_Rank_sync",
"segments": [
{
- "end": 62,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 62,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -8052,56 +13439,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 55,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 58,
- "start": 56,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 63,
- "start": 59,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_grounded_generation_service_stream_generate_grounded_content_sync.py"
+ "title": "discoveryengine_v1_generated_rank_service_rank_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
- "shortName": "IdentityMappingStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.RecommendationServiceAsyncClient",
+ "shortName": "RecommendationServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.create_identity_mapping_store",
+ "fullName": "google.cloud.discoveryengine_v1.RecommendationServiceAsyncClient.recommend",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.CreateIdentityMappingStore",
+ "fullName": "google.cloud.discoveryengine.v1.RecommendationService.Recommend",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.RecommendationService",
+ "shortName": "RecommendationService"
},
- "shortName": "CreateIdentityMappingStore"
+ "shortName": "Recommend"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateIdentityMappingStoreRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "identity_mapping_store",
- "type": "google.cloud.discoveryengine_v1.types.IdentityMappingStore"
- },
- {
- "name": "identity_mapping_store_id",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.RecommendRequest"
},
{
"name": "retry",
@@ -8116,22 +13491,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.IdentityMappingStore",
- "shortName": "create_identity_mapping_store"
+ "resultType": "google.cloud.discoveryengine_v1.types.RecommendResponse",
+ "shortName": "recommend"
},
- "description": "Sample for CreateIdentityMappingStore",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_create_identity_mapping_store_async.py",
+ "description": "Sample for Recommend",
+ "file": "discoveryengine_v1_generated_recommendation_service_recommend_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_CreateIdentityMappingStore_async",
+ "regionTag": "discoveryengine_v1_generated_RecommendationService_Recommend_async",
"segments": [
{
- "end": 53,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 53,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -8141,55 +13516,43 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 47,
+ "end": 50,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 50,
- "start": 48,
+ "end": 53,
+ "start": 51,
"type": "REQUEST_EXECUTION"
},
{
- "end": 54,
- "start": 51,
+ "end": 57,
+ "start": 54,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_create_identity_mapping_store_async.py"
+ "title": "discoveryengine_v1_generated_recommendation_service_recommend_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
- "shortName": "IdentityMappingStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.RecommendationServiceClient",
+ "shortName": "RecommendationServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.create_identity_mapping_store",
+ "fullName": "google.cloud.discoveryengine_v1.RecommendationServiceClient.recommend",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.CreateIdentityMappingStore",
+ "fullName": "google.cloud.discoveryengine.v1.RecommendationService.Recommend",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.RecommendationService",
+ "shortName": "RecommendationService"
},
- "shortName": "CreateIdentityMappingStore"
+ "shortName": "Recommend"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateIdentityMappingStoreRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "identity_mapping_store",
- "type": "google.cloud.discoveryengine_v1.types.IdentityMappingStore"
- },
- {
- "name": "identity_mapping_store_id",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.RecommendRequest"
},
{
"name": "retry",
@@ -8204,22 +13567,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.IdentityMappingStore",
- "shortName": "create_identity_mapping_store"
+ "resultType": "google.cloud.discoveryengine_v1.types.RecommendResponse",
+ "shortName": "recommend"
},
- "description": "Sample for CreateIdentityMappingStore",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_create_identity_mapping_store_sync.py",
+ "description": "Sample for Recommend",
+ "file": "discoveryengine_v1_generated_recommendation_service_recommend_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_CreateIdentityMappingStore_sync",
+ "regionTag": "discoveryengine_v1_generated_RecommendationService_Recommend_sync",
"segments": [
{
- "end": 53,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 53,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -8229,47 +13592,55 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 47,
+ "end": 50,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 50,
- "start": 48,
+ "end": 53,
+ "start": 51,
"type": "REQUEST_EXECUTION"
},
{
- "end": 54,
- "start": 51,
+ "end": 57,
+ "start": 54,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_create_identity_mapping_store_sync.py"
+ "title": "discoveryengine_v1_generated_recommendation_service_recommend_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
- "shortName": "IdentityMappingStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
+ "shortName": "SchemaServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.delete_identity_mapping_store",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.create_schema",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.DeleteIdentityMappingStore",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.CreateSchema",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "DeleteIdentityMappingStore"
+ "shortName": "CreateSchema"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteIdentityMappingStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateSchemaRequest"
},
{
- "name": "name",
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "schema",
+ "type": "google.cloud.discoveryengine_v1.types.Schema"
+ },
+ {
+ "name": "schema_id",
"type": "str"
},
{
@@ -8286,21 +13657,21 @@
}
],
"resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "delete_identity_mapping_store"
+ "shortName": "create_schema"
},
- "description": "Sample for DeleteIdentityMappingStore",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_delete_identity_mapping_store_async.py",
+ "description": "Sample for CreateSchema",
+ "file": "discoveryengine_v1_generated_schema_service_create_schema_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_DeleteIdentityMappingStore_async",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_CreateSchema_async",
"segments": [
{
- "end": 55,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -8310,46 +13681,54 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 46,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 46,
+ "end": 53,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 57,
+ "start": 54,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_delete_identity_mapping_store_async.py"
+ "title": "discoveryengine_v1_generated_schema_service_create_schema_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
- "shortName": "IdentityMappingStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
+ "shortName": "SchemaServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.delete_identity_mapping_store",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.create_schema",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.DeleteIdentityMappingStore",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.CreateSchema",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "DeleteIdentityMappingStore"
+ "shortName": "CreateSchema"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteIdentityMappingStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateSchemaRequest"
},
{
- "name": "name",
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "schema",
+ "type": "google.cloud.discoveryengine_v1.types.Schema"
+ },
+ {
+ "name": "schema_id",
"type": "str"
},
{
@@ -8366,21 +13745,21 @@
}
],
"resultType": "google.api_core.operation.Operation",
- "shortName": "delete_identity_mapping_store"
+ "shortName": "create_schema"
},
- "description": "Sample for DeleteIdentityMappingStore",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_delete_identity_mapping_store_sync.py",
+ "description": "Sample for CreateSchema",
+ "file": "discoveryengine_v1_generated_schema_service_create_schema_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_DeleteIdentityMappingStore_sync",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_CreateSchema_sync",
"segments": [
{
- "end": 55,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -8390,44 +13769,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 46,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
- "start": 46,
+ "end": 53,
+ "start": 47,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 57,
+ "start": 54,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_delete_identity_mapping_store_sync.py"
+ "title": "discoveryengine_v1_generated_schema_service_create_schema_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
- "shortName": "IdentityMappingStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
+ "shortName": "SchemaServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.get_identity_mapping_store",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.delete_schema",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.GetIdentityMappingStore",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.DeleteSchema",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "GetIdentityMappingStore"
+ "shortName": "DeleteSchema"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetIdentityMappingStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteSchemaRequest"
},
{
"name": "name",
@@ -8446,22 +13825,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.IdentityMappingStore",
- "shortName": "get_identity_mapping_store"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "delete_schema"
},
- "description": "Sample for GetIdentityMappingStore",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_get_identity_mapping_store_async.py",
+ "description": "Sample for DeleteSchema",
+ "file": "discoveryengine_v1_generated_schema_service_delete_schema_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_GetIdentityMappingStore_async",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_DeleteSchema_async",
"segments": [
{
- "end": 51,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -8476,38 +13855,38 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_get_identity_mapping_store_async.py"
+ "title": "discoveryengine_v1_generated_schema_service_delete_schema_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
- "shortName": "IdentityMappingStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
+ "shortName": "SchemaServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.get_identity_mapping_store",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.delete_schema",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.GetIdentityMappingStore",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.DeleteSchema",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "GetIdentityMappingStore"
+ "shortName": "DeleteSchema"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetIdentityMappingStoreRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteSchemaRequest"
},
{
"name": "name",
@@ -8526,22 +13905,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.IdentityMappingStore",
- "shortName": "get_identity_mapping_store"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "delete_schema"
},
- "description": "Sample for GetIdentityMappingStore",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_get_identity_mapping_store_sync.py",
+ "description": "Sample for DeleteSchema",
+ "file": "discoveryengine_v1_generated_schema_service_delete_schema_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_GetIdentityMappingStore_sync",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_DeleteSchema_sync",
"segments": [
{
- "end": 51,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -8556,39 +13935,43 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_get_identity_mapping_store_sync.py"
+ "title": "discoveryengine_v1_generated_schema_service_delete_schema_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
- "shortName": "IdentityMappingStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
+ "shortName": "SchemaServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.import_identity_mappings",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.get_schema",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ImportIdentityMappings",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.GetSchema",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "ImportIdentityMappings"
+ "shortName": "GetSchema"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportIdentityMappingsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetSchemaRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -8603,22 +13986,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "import_identity_mappings"
+ "resultType": "google.cloud.discoveryengine_v1.types.Schema",
+ "shortName": "get_schema"
},
- "description": "Sample for ImportIdentityMappings",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_import_identity_mappings_async.py",
+ "description": "Sample for GetSchema",
+ "file": "discoveryengine_v1_generated_schema_service_get_schema_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ImportIdentityMappings_async",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_GetSchema_async",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -8633,38 +14016,42 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_import_identity_mappings_async.py"
+ "title": "discoveryengine_v1_generated_schema_service_get_schema_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
- "shortName": "IdentityMappingStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
+ "shortName": "SchemaServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.import_identity_mappings",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.get_schema",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ImportIdentityMappings",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.GetSchema",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "ImportIdentityMappings"
+ "shortName": "GetSchema"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportIdentityMappingsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetSchemaRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -8679,22 +14066,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "import_identity_mappings"
+ "resultType": "google.cloud.discoveryengine_v1.types.Schema",
+ "shortName": "get_schema"
},
- "description": "Sample for ImportIdentityMappings",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_import_identity_mappings_sync.py",
+ "description": "Sample for GetSchema",
+ "file": "discoveryengine_v1_generated_schema_service_get_schema_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ImportIdentityMappings_sync",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_GetSchema_sync",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -8709,39 +14096,39 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_import_identity_mappings_sync.py"
+ "title": "discoveryengine_v1_generated_schema_service_get_schema_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
- "shortName": "IdentityMappingStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
+ "shortName": "SchemaServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.list_identity_mapping_stores",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.list_schemas",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ListIdentityMappingStores",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.ListSchemas",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "ListIdentityMappingStores"
+ "shortName": "ListSchemas"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListIdentityMappingStoresRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListSchemasRequest"
},
{
"name": "parent",
@@ -8760,14 +14147,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.identity_mapping_store_service.pagers.ListIdentityMappingStoresAsyncPager",
- "shortName": "list_identity_mapping_stores"
+ "resultType": "google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasAsyncPager",
+ "shortName": "list_schemas"
},
- "description": "Sample for ListIdentityMappingStores",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mapping_stores_async.py",
+ "description": "Sample for ListSchemas",
+ "file": "discoveryengine_v1_generated_schema_service_list_schemas_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ListIdentityMappingStores_async",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_ListSchemas_async",
"segments": [
{
"end": 52,
@@ -8800,28 +14187,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mapping_stores_async.py"
+ "title": "discoveryengine_v1_generated_schema_service_list_schemas_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
- "shortName": "IdentityMappingStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
+ "shortName": "SchemaServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.list_identity_mapping_stores",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.list_schemas",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ListIdentityMappingStores",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.ListSchemas",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "ListIdentityMappingStores"
+ "shortName": "ListSchemas"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListIdentityMappingStoresRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListSchemasRequest"
},
{
"name": "parent",
@@ -8840,14 +14227,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.identity_mapping_store_service.pagers.ListIdentityMappingStoresPager",
- "shortName": "list_identity_mapping_stores"
+ "resultType": "google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasPager",
+ "shortName": "list_schemas"
},
- "description": "Sample for ListIdentityMappingStores",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mapping_stores_sync.py",
+ "description": "Sample for ListSchemas",
+ "file": "discoveryengine_v1_generated_schema_service_list_schemas_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ListIdentityMappingStores_sync",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_ListSchemas_sync",
"segments": [
{
"end": 52,
@@ -8880,29 +14267,29 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mapping_stores_sync.py"
+ "title": "discoveryengine_v1_generated_schema_service_list_schemas_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
- "shortName": "IdentityMappingStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
+ "shortName": "SchemaServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.list_identity_mappings",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.update_schema",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ListIdentityMappings",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.UpdateSchema",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "ListIdentityMappings"
+ "shortName": "UpdateSchema"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListIdentityMappingsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateSchemaRequest"
},
{
"name": "retry",
@@ -8917,22 +14304,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.identity_mapping_store_service.pagers.ListIdentityMappingsAsyncPager",
- "shortName": "list_identity_mappings"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "update_schema"
},
- "description": "Sample for ListIdentityMappings",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mappings_async.py",
+ "description": "Sample for UpdateSchema",
+ "file": "discoveryengine_v1_generated_schema_service_update_schema_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ListIdentityMappings_async",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_UpdateSchema_async",
"segments": [
{
- "end": 52,
+ "end": 54,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 54,
"start": 27,
"type": "SHORT"
},
@@ -8942,43 +14329,43 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 44,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 51,
+ "start": 45,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 49,
+ "end": 55,
+ "start": 52,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mappings_async.py"
+ "title": "discoveryengine_v1_generated_schema_service_update_schema_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
- "shortName": "IdentityMappingStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
+ "shortName": "SchemaServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.list_identity_mappings",
+ "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.update_schema",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.ListIdentityMappings",
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService.UpdateSchema",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SchemaService",
+ "shortName": "SchemaService"
},
- "shortName": "ListIdentityMappings"
+ "shortName": "UpdateSchema"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListIdentityMappingsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateSchemaRequest"
},
{
"name": "retry",
@@ -8993,22 +14380,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.identity_mapping_store_service.pagers.ListIdentityMappingsPager",
- "shortName": "list_identity_mappings"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "update_schema"
},
- "description": "Sample for ListIdentityMappings",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mappings_sync.py",
+ "description": "Sample for UpdateSchema",
+ "file": "discoveryengine_v1_generated_schema_service_update_schema_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_ListIdentityMappings_sync",
+ "regionTag": "discoveryengine_v1_generated_SchemaService_UpdateSchema_sync",
"segments": [
{
- "end": 52,
+ "end": 54,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 54,
"start": 27,
"type": "SHORT"
},
@@ -9018,44 +14405,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 44,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 51,
+ "start": 45,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 49,
+ "end": 55,
+ "start": 52,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_list_identity_mappings_sync.py"
+ "title": "discoveryengine_v1_generated_schema_service_update_schema_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient",
- "shortName": "IdentityMappingStoreServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient",
+ "shortName": "SearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceAsyncClient.purge_identity_mappings",
+ "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient.search_lite",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.PurgeIdentityMappings",
+ "fullName": "google.cloud.discoveryengine.v1.SearchService.SearchLite",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SearchService",
+ "shortName": "SearchService"
},
- "shortName": "PurgeIdentityMappings"
+ "shortName": "SearchLite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeIdentityMappingsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.SearchRequest"
},
{
"name": "retry",
@@ -9070,22 +14457,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "purge_identity_mappings"
+ "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchLiteAsyncPager",
+ "shortName": "search_lite"
},
- "description": "Sample for PurgeIdentityMappings",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_purge_identity_mappings_async.py",
+ "description": "Sample for SearchLite",
+ "file": "discoveryengine_v1_generated_search_service_search_lite_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_PurgeIdentityMappings_async",
+ "regionTag": "discoveryengine_v1_generated_SearchService_SearchLite_async",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -9100,38 +14487,38 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_purge_identity_mappings_async.py"
+ "title": "discoveryengine_v1_generated_search_service_search_lite_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient",
- "shortName": "IdentityMappingStoreServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient",
+ "shortName": "SearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.IdentityMappingStoreServiceClient.purge_identity_mappings",
+ "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient.search_lite",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService.PurgeIdentityMappings",
+ "fullName": "google.cloud.discoveryengine.v1.SearchService.SearchLite",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.IdentityMappingStoreService",
- "shortName": "IdentityMappingStoreService"
+ "fullName": "google.cloud.discoveryengine.v1.SearchService",
+ "shortName": "SearchService"
},
- "shortName": "PurgeIdentityMappings"
+ "shortName": "SearchLite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeIdentityMappingsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.SearchRequest"
},
{
"name": "retry",
@@ -9146,22 +14533,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "purge_identity_mappings"
+ "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchLitePager",
+ "shortName": "search_lite"
},
- "description": "Sample for PurgeIdentityMappings",
- "file": "discoveryengine_v1_generated_identity_mapping_store_service_purge_identity_mappings_sync.py",
+ "description": "Sample for SearchLite",
+ "file": "discoveryengine_v1_generated_search_service_search_lite_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_IdentityMappingStoreService_PurgeIdentityMappings_sync",
+ "regionTag": "discoveryengine_v1_generated_SearchService_SearchLite_sync",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -9176,43 +14563,39 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_identity_mapping_store_service_purge_identity_mappings_sync.py"
+ "title": "discoveryengine_v1_generated_search_service_search_lite_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ProjectServiceAsyncClient",
- "shortName": "ProjectServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient",
+ "shortName": "SearchServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ProjectServiceAsyncClient.provision_project",
+ "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient.search",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ProjectService.ProvisionProject",
+ "fullName": "google.cloud.discoveryengine.v1.SearchService.Search",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ProjectService",
- "shortName": "ProjectService"
+ "fullName": "google.cloud.discoveryengine.v1.SearchService",
+ "shortName": "SearchService"
},
- "shortName": "ProvisionProject"
+ "shortName": "Search"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ProvisionProjectRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.SearchRequest"
},
{
"name": "retry",
@@ -9227,22 +14610,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "provision_project"
+ "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchAsyncPager",
+ "shortName": "search"
},
- "description": "Sample for ProvisionProject",
- "file": "discoveryengine_v1_generated_project_service_provision_project_async.py",
+ "description": "Sample for Search",
+ "file": "discoveryengine_v1_generated_search_service_search_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ProjectService_ProvisionProject_async",
+ "regionTag": "discoveryengine_v1_generated_SearchService_Search_async",
"segments": [
{
- "end": 57,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 57,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -9252,47 +14635,43 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 47,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 54,
- "start": 48,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 58,
- "start": 55,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_project_service_provision_project_async.py"
+ "title": "discoveryengine_v1_generated_search_service_search_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ProjectServiceClient",
- "shortName": "ProjectServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient",
+ "shortName": "SearchServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ProjectServiceClient.provision_project",
+ "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient.search",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ProjectService.ProvisionProject",
+ "fullName": "google.cloud.discoveryengine.v1.SearchService.Search",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ProjectService",
- "shortName": "ProjectService"
+ "fullName": "google.cloud.discoveryengine.v1.SearchService",
+ "shortName": "SearchService"
},
- "shortName": "ProvisionProject"
+ "shortName": "Search"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ProvisionProjectRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.SearchRequest"
},
{
"name": "retry",
@@ -9307,22 +14686,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "provision_project"
+ "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchPager",
+ "shortName": "search"
},
- "description": "Sample for ProvisionProject",
- "file": "discoveryengine_v1_generated_project_service_provision_project_sync.py",
+ "description": "Sample for Search",
+ "file": "discoveryengine_v1_generated_search_service_search_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ProjectService_ProvisionProject_sync",
+ "regionTag": "discoveryengine_v1_generated_SearchService_Search_sync",
"segments": [
{
- "end": 57,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 57,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -9332,44 +14711,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 47,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 54,
- "start": 48,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 58,
- "start": 55,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_project_service_provision_project_sync.py"
+ "title": "discoveryengine_v1_generated_search_service_search_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.RankServiceAsyncClient",
- "shortName": "RankServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceAsyncClient",
+ "shortName": "SearchTuningServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.RankServiceAsyncClient.rank",
+ "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceAsyncClient.list_custom_models",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.RankService.Rank",
+ "fullName": "google.cloud.discoveryengine.v1.SearchTuningService.ListCustomModels",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.RankService",
- "shortName": "RankService"
+ "fullName": "google.cloud.discoveryengine.v1.SearchTuningService",
+ "shortName": "SearchTuningService"
},
- "shortName": "Rank"
+ "shortName": "ListCustomModels"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.RankRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListCustomModelsRequest"
},
{
"name": "retry",
@@ -9384,14 +14763,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.RankResponse",
- "shortName": "rank"
+ "resultType": "google.cloud.discoveryengine_v1.types.ListCustomModelsResponse",
+ "shortName": "list_custom_models"
},
- "description": "Sample for Rank",
- "file": "discoveryengine_v1_generated_rank_service_rank_async.py",
+ "description": "Sample for ListCustomModels",
+ "file": "discoveryengine_v1_generated_search_tuning_service_list_custom_models_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_RankService_Rank_async",
+ "regionTag": "discoveryengine_v1_generated_SearchTuningService_ListCustomModels_async",
"segments": [
{
"end": 51,
@@ -9424,28 +14803,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_rank_service_rank_async.py"
+ "title": "discoveryengine_v1_generated_search_tuning_service_list_custom_models_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.RankServiceClient",
- "shortName": "RankServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceClient",
+ "shortName": "SearchTuningServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.RankServiceClient.rank",
+ "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceClient.list_custom_models",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.RankService.Rank",
+ "fullName": "google.cloud.discoveryengine.v1.SearchTuningService.ListCustomModels",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.RankService",
- "shortName": "RankService"
+ "fullName": "google.cloud.discoveryengine.v1.SearchTuningService",
+ "shortName": "SearchTuningService"
},
- "shortName": "Rank"
+ "shortName": "ListCustomModels"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.RankRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListCustomModelsRequest"
},
{
"name": "retry",
@@ -9460,14 +14839,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.RankResponse",
- "shortName": "rank"
+ "resultType": "google.cloud.discoveryengine_v1.types.ListCustomModelsResponse",
+ "shortName": "list_custom_models"
},
- "description": "Sample for Rank",
- "file": "discoveryengine_v1_generated_rank_service_rank_sync.py",
+ "description": "Sample for ListCustomModels",
+ "file": "discoveryengine_v1_generated_search_tuning_service_list_custom_models_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_RankService_Rank_sync",
+ "regionTag": "discoveryengine_v1_generated_SearchTuningService_ListCustomModels_sync",
"segments": [
{
"end": 51,
@@ -9500,29 +14879,29 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_rank_service_rank_sync.py"
+ "title": "discoveryengine_v1_generated_search_tuning_service_list_custom_models_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.RecommendationServiceAsyncClient",
- "shortName": "RecommendationServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceAsyncClient",
+ "shortName": "SearchTuningServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.RecommendationServiceAsyncClient.recommend",
+ "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceAsyncClient.train_custom_model",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.RecommendationService.Recommend",
+ "fullName": "google.cloud.discoveryengine.v1.SearchTuningService.TrainCustomModel",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.RecommendationService",
- "shortName": "RecommendationService"
+ "fullName": "google.cloud.discoveryengine.v1.SearchTuningService",
+ "shortName": "SearchTuningService"
},
- "shortName": "Recommend"
+ "shortName": "TrainCustomModel"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.RecommendRequest"
+ "type": "google.cloud.discoveryengine_v1.types.TrainCustomModelRequest"
},
{
"name": "retry",
@@ -9537,22 +14916,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.RecommendResponse",
- "shortName": "recommend"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "train_custom_model"
},
- "description": "Sample for Recommend",
- "file": "discoveryengine_v1_generated_recommendation_service_recommend_async.py",
+ "description": "Sample for TrainCustomModel",
+ "file": "discoveryengine_v1_generated_search_tuning_service_train_custom_model_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_RecommendationService_Recommend_async",
+ "regionTag": "discoveryengine_v1_generated_SearchTuningService_TrainCustomModel_async",
"segments": [
{
- "end": 56,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -9562,43 +14941,43 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 50,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 53,
- "start": 51,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
- "start": 54,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_recommendation_service_recommend_async.py"
+ "title": "discoveryengine_v1_generated_search_tuning_service_train_custom_model_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.RecommendationServiceClient",
- "shortName": "RecommendationServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceClient",
+ "shortName": "SearchTuningServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.RecommendationServiceClient.recommend",
+ "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceClient.train_custom_model",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.RecommendationService.Recommend",
+ "fullName": "google.cloud.discoveryengine.v1.SearchTuningService.TrainCustomModel",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.RecommendationService",
- "shortName": "RecommendationService"
+ "fullName": "google.cloud.discoveryengine.v1.SearchTuningService",
+ "shortName": "SearchTuningService"
},
- "shortName": "Recommend"
+ "shortName": "TrainCustomModel"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.RecommendRequest"
+ "type": "google.cloud.discoveryengine_v1.types.TrainCustomModelRequest"
},
{
"name": "retry",
@@ -9613,22 +14992,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.RecommendResponse",
- "shortName": "recommend"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "train_custom_model"
},
- "description": "Sample for Recommend",
- "file": "discoveryengine_v1_generated_recommendation_service_recommend_sync.py",
+ "description": "Sample for TrainCustomModel",
+ "file": "discoveryengine_v1_generated_search_tuning_service_train_custom_model_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_RecommendationService_Recommend_sync",
+ "regionTag": "discoveryengine_v1_generated_SearchTuningService_TrainCustomModel_sync",
"segments": [
{
- "end": 56,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -9638,55 +15017,55 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 50,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 53,
- "start": 51,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
- "start": 54,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_recommendation_service_recommend_sync.py"
+ "title": "discoveryengine_v1_generated_search_tuning_service_train_custom_model_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
- "shortName": "SchemaServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient",
+ "shortName": "ServingConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.create_schema",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient.create_serving_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.CreateSchema",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.CreateServingConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "CreateSchema"
+ "shortName": "CreateServingConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateSchemaRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateServingConfigRequest"
},
{
"name": "parent",
"type": "str"
},
{
- "name": "schema",
- "type": "google.cloud.discoveryengine_v1.types.Schema"
+ "name": "serving_config",
+ "type": "google.cloud.discoveryengine_v1.types.ServingConfig"
},
{
- "name": "schema_id",
+ "name": "serving_config_id",
"type": "str"
},
{
@@ -9702,22 +15081,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "create_schema"
+ "resultType": "google.cloud.discoveryengine_v1.types.ServingConfig",
+ "shortName": "create_serving_config"
},
- "description": "Sample for CreateSchema",
- "file": "discoveryengine_v1_generated_schema_service_create_schema_async.py",
+ "description": "Sample for CreateServingConfig",
+ "file": "discoveryengine_v1_generated_serving_config_service_create_serving_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_CreateSchema_async",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_CreateServingConfig_async",
"segments": [
{
- "end": 56,
+ "end": 58,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 58,
"start": 27,
"type": "SHORT"
},
@@ -9727,54 +15106,54 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 52,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 53,
- "start": 47,
+ "end": 55,
+ "start": 53,
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
- "start": 54,
+ "end": 59,
+ "start": 56,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_create_schema_async.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_create_serving_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
- "shortName": "SchemaServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient",
+ "shortName": "ServingConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.create_schema",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient.create_serving_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.CreateSchema",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.CreateServingConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "CreateSchema"
+ "shortName": "CreateServingConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateSchemaRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateServingConfigRequest"
},
{
"name": "parent",
"type": "str"
},
{
- "name": "schema",
- "type": "google.cloud.discoveryengine_v1.types.Schema"
+ "name": "serving_config",
+ "type": "google.cloud.discoveryengine_v1.types.ServingConfig"
},
{
- "name": "schema_id",
+ "name": "serving_config_id",
"type": "str"
},
{
@@ -9790,22 +15169,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "create_schema"
+ "resultType": "google.cloud.discoveryengine_v1.types.ServingConfig",
+ "shortName": "create_serving_config"
},
- "description": "Sample for CreateSchema",
- "file": "discoveryengine_v1_generated_schema_service_create_schema_sync.py",
+ "description": "Sample for CreateServingConfig",
+ "file": "discoveryengine_v1_generated_serving_config_service_create_serving_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_CreateSchema_sync",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_CreateServingConfig_sync",
"segments": [
{
- "end": 56,
+ "end": 58,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 58,
"start": 27,
"type": "SHORT"
},
@@ -9815,44 +15194,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 52,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 53,
- "start": 47,
+ "end": 55,
+ "start": 53,
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
- "start": 54,
+ "end": 59,
+ "start": 56,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_create_schema_sync.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_create_serving_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
- "shortName": "SchemaServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient",
+ "shortName": "ServingConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.delete_schema",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient.delete_serving_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.DeleteSchema",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.DeleteServingConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "DeleteSchema"
+ "shortName": "DeleteServingConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteSchemaRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteServingConfigRequest"
},
{
"name": "name",
@@ -9871,22 +15250,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "delete_schema"
+ "shortName": "delete_serving_config"
},
- "description": "Sample for DeleteSchema",
- "file": "discoveryengine_v1_generated_schema_service_delete_schema_async.py",
+ "description": "Sample for DeleteServingConfig",
+ "file": "discoveryengine_v1_generated_serving_config_service_delete_serving_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_DeleteSchema_async",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_DeleteServingConfig_async",
"segments": [
{
- "end": 55,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -9901,38 +15279,36 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_delete_schema_async.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_delete_serving_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
- "shortName": "SchemaServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient",
+ "shortName": "ServingConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.delete_schema",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient.delete_serving_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.DeleteSchema",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.DeleteServingConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "DeleteSchema"
+ "shortName": "DeleteServingConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteSchemaRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteServingConfigRequest"
},
{
"name": "name",
@@ -9951,22 +15327,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "delete_schema"
+ "shortName": "delete_serving_config"
},
- "description": "Sample for DeleteSchema",
- "file": "discoveryengine_v1_generated_schema_service_delete_schema_sync.py",
+ "description": "Sample for DeleteServingConfig",
+ "file": "discoveryengine_v1_generated_serving_config_service_delete_serving_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_DeleteSchema_sync",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_DeleteServingConfig_sync",
"segments": [
{
- "end": 55,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -9981,39 +15356,37 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_delete_schema_sync.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_delete_serving_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
- "shortName": "SchemaServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient",
+ "shortName": "ServingConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.get_schema",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient.get_serving_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.GetSchema",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.GetServingConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "GetSchema"
+ "shortName": "GetServingConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetSchemaRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetServingConfigRequest"
},
{
"name": "name",
@@ -10032,14 +15405,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Schema",
- "shortName": "get_schema"
+ "resultType": "google.cloud.discoveryengine_v1.types.ServingConfig",
+ "shortName": "get_serving_config"
},
- "description": "Sample for GetSchema",
- "file": "discoveryengine_v1_generated_schema_service_get_schema_async.py",
+ "description": "Sample for GetServingConfig",
+ "file": "discoveryengine_v1_generated_serving_config_service_get_serving_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_GetSchema_async",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_GetServingConfig_async",
"segments": [
{
"end": 51,
@@ -10072,28 +15445,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_get_schema_async.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_get_serving_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
- "shortName": "SchemaServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient",
+ "shortName": "ServingConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.get_schema",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient.get_serving_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.GetSchema",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.GetServingConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "GetSchema"
+ "shortName": "GetServingConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetSchemaRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetServingConfigRequest"
},
{
"name": "name",
@@ -10112,14 +15485,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Schema",
- "shortName": "get_schema"
+ "resultType": "google.cloud.discoveryengine_v1.types.ServingConfig",
+ "shortName": "get_serving_config"
},
- "description": "Sample for GetSchema",
- "file": "discoveryengine_v1_generated_schema_service_get_schema_sync.py",
+ "description": "Sample for GetServingConfig",
+ "file": "discoveryengine_v1_generated_serving_config_service_get_serving_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_GetSchema_sync",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_GetServingConfig_sync",
"segments": [
{
"end": 51,
@@ -10152,29 +15525,29 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_get_schema_sync.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_get_serving_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
- "shortName": "SchemaServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient",
+ "shortName": "ServingConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.list_schemas",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient.list_serving_configs",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.ListSchemas",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.ListServingConfigs",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "ListSchemas"
+ "shortName": "ListServingConfigs"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListSchemasRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListServingConfigsRequest"
},
{
"name": "parent",
@@ -10193,14 +15566,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasAsyncPager",
- "shortName": "list_schemas"
+ "resultType": "google.cloud.discoveryengine_v1.services.serving_config_service.pagers.ListServingConfigsAsyncPager",
+ "shortName": "list_serving_configs"
},
- "description": "Sample for ListSchemas",
- "file": "discoveryengine_v1_generated_schema_service_list_schemas_async.py",
+ "description": "Sample for ListServingConfigs",
+ "file": "discoveryengine_v1_generated_serving_config_service_list_serving_configs_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_ListSchemas_async",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_ListServingConfigs_async",
"segments": [
{
"end": 52,
@@ -10233,28 +15606,28 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_list_schemas_async.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_list_serving_configs_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
- "shortName": "SchemaServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient",
+ "shortName": "ServingConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.list_schemas",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient.list_serving_configs",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.ListSchemas",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.ListServingConfigs",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "ListSchemas"
+ "shortName": "ListServingConfigs"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListSchemasRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListServingConfigsRequest"
},
{
"name": "parent",
@@ -10273,14 +15646,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.schema_service.pagers.ListSchemasPager",
- "shortName": "list_schemas"
+ "resultType": "google.cloud.discoveryengine_v1.services.serving_config_service.pagers.ListServingConfigsPager",
+ "shortName": "list_serving_configs"
},
- "description": "Sample for ListSchemas",
- "file": "discoveryengine_v1_generated_schema_service_list_schemas_sync.py",
+ "description": "Sample for ListServingConfigs",
+ "file": "discoveryengine_v1_generated_serving_config_service_list_serving_configs_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_ListSchemas_sync",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_ListServingConfigs_sync",
"segments": [
{
"end": 52,
@@ -10313,29 +15686,37 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_list_schemas_sync.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_list_serving_configs_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient",
- "shortName": "SchemaServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient",
+ "shortName": "ServingConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceAsyncClient.update_schema",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient.update_serving_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.UpdateSchema",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.UpdateServingConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "UpdateSchema"
+ "shortName": "UpdateServingConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateSchemaRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateServingConfigRequest"
+ },
+ {
+ "name": "serving_config",
+ "type": "google.cloud.discoveryengine_v1.types.ServingConfig"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -10350,22 +15731,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "update_schema"
+ "resultType": "google.cloud.discoveryengine_v1.types.ServingConfig",
+ "shortName": "update_serving_config"
},
- "description": "Sample for UpdateSchema",
- "file": "discoveryengine_v1_generated_schema_service_update_schema_async.py",
+ "description": "Sample for UpdateServingConfig",
+ "file": "discoveryengine_v1_generated_serving_config_service_update_serving_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_UpdateSchema_async",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_UpdateServingConfig_async",
"segments": [
{
- "end": 54,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 54,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -10375,43 +15756,51 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 50,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 51,
- "start": 45,
+ "end": 53,
+ "start": 51,
"type": "REQUEST_EXECUTION"
},
{
- "end": 55,
- "start": 52,
+ "end": 57,
+ "start": 54,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_update_schema_async.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_update_serving_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient",
- "shortName": "SchemaServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient",
+ "shortName": "ServingConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SchemaServiceClient.update_schema",
+ "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient.update_serving_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService.UpdateSchema",
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.UpdateServingConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SchemaService",
- "shortName": "SchemaService"
+ "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
+ "shortName": "ServingConfigService"
},
- "shortName": "UpdateSchema"
+ "shortName": "UpdateServingConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateSchemaRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateServingConfigRequest"
+ },
+ {
+ "name": "serving_config",
+ "type": "google.cloud.discoveryengine_v1.types.ServingConfig"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -10426,22 +15815,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "update_schema"
+ "resultType": "google.cloud.discoveryengine_v1.types.ServingConfig",
+ "shortName": "update_serving_config"
},
- "description": "Sample for UpdateSchema",
- "file": "discoveryengine_v1_generated_schema_service_update_schema_sync.py",
+ "description": "Sample for UpdateServingConfig",
+ "file": "discoveryengine_v1_generated_serving_config_service_update_serving_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SchemaService_UpdateSchema_sync",
+ "regionTag": "discoveryengine_v1_generated_ServingConfigService_UpdateServingConfig_sync",
"segments": [
{
- "end": 54,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 54,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -10451,44 +15840,52 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 50,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 51,
- "start": 45,
+ "end": 53,
+ "start": 51,
"type": "REQUEST_EXECUTION"
},
{
- "end": 55,
- "start": 52,
+ "end": 57,
+ "start": 54,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_schema_service_update_schema_sync.py"
+ "title": "discoveryengine_v1_generated_serving_config_service_update_serving_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient",
- "shortName": "SearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
+ "shortName": "SessionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient.search_lite",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.create_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SearchService.SearchLite",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.CreateSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SearchService",
- "shortName": "SearchService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "SearchLite"
+ "shortName": "CreateSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.SearchRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateSessionRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "session",
+ "type": "google.cloud.discoveryengine_v1.types.Session"
},
{
"name": "retry",
@@ -10503,22 +15900,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchLiteAsyncPager",
- "shortName": "search_lite"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "create_session"
},
- "description": "Sample for SearchLite",
- "file": "discoveryengine_v1_generated_search_service_search_lite_async.py",
+ "description": "Sample for CreateSession",
+ "file": "discoveryengine_v1_generated_session_service_create_session_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SearchService_SearchLite_async",
+ "regionTag": "discoveryengine_v1_generated_SessionService_CreateSession_async",
"segments": [
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -10538,33 +15935,41 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
+ "end": 52,
"start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_search_service_search_lite_async.py"
+ "title": "discoveryengine_v1_generated_session_service_create_session_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient",
- "shortName": "SearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
+ "shortName": "SessionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient.search_lite",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.create_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SearchService.SearchLite",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.CreateSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SearchService",
- "shortName": "SearchService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "SearchLite"
+ "shortName": "CreateSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.SearchRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateSessionRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
+ },
+ {
+ "name": "session",
+ "type": "google.cloud.discoveryengine_v1.types.Session"
},
{
"name": "retry",
@@ -10579,22 +15984,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchLitePager",
- "shortName": "search_lite"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "create_session"
},
- "description": "Sample for SearchLite",
- "file": "discoveryengine_v1_generated_search_service_search_lite_sync.py",
+ "description": "Sample for CreateSession",
+ "file": "discoveryengine_v1_generated_session_service_create_session_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SearchService_SearchLite_sync",
+ "regionTag": "discoveryengine_v1_generated_SessionService_CreateSession_sync",
"segments": [
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -10614,34 +16019,38 @@
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
+ "end": 52,
"start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_search_service_search_lite_sync.py"
+ "title": "discoveryengine_v1_generated_session_service_create_session_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient",
- "shortName": "SearchServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
+ "shortName": "SessionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SearchServiceAsyncClient.search",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.delete_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SearchService.Search",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.DeleteSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SearchService",
- "shortName": "SearchService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "Search"
+ "shortName": "DeleteSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.SearchRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteSessionRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -10656,22 +16065,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchAsyncPager",
- "shortName": "search"
+ "shortName": "delete_session"
},
- "description": "Sample for Search",
- "file": "discoveryengine_v1_generated_search_service_search_async.py",
+ "description": "Sample for DeleteSession",
+ "file": "discoveryengine_v1_generated_session_service_delete_session_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SearchService_Search_async",
+ "regionTag": "discoveryengine_v1_generated_SessionService_DeleteSession_async",
"segments": [
{
- "end": 52,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -10686,38 +16094,40 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 49,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_search_service_search_async.py"
+ "title": "discoveryengine_v1_generated_session_service_delete_session_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient",
- "shortName": "SearchServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
+ "shortName": "SessionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SearchServiceClient.search",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.delete_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SearchService.Search",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.DeleteSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SearchService",
- "shortName": "SearchService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "Search"
+ "shortName": "DeleteSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.SearchRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteSessionRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -10732,22 +16142,21 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.search_service.pagers.SearchPager",
- "shortName": "search"
+ "shortName": "delete_session"
},
- "description": "Sample for Search",
- "file": "discoveryengine_v1_generated_search_service_search_sync.py",
+ "description": "Sample for DeleteSession",
+ "file": "discoveryengine_v1_generated_session_service_delete_session_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SearchService_Search_sync",
+ "regionTag": "discoveryengine_v1_generated_SessionService_DeleteSession_sync",
"segments": [
{
- "end": 52,
+ "end": 49,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 49,
"start": 27,
"type": "SHORT"
},
@@ -10762,39 +16171,41 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 49,
+ "end": 50,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_search_service_search_sync.py"
+ "title": "discoveryengine_v1_generated_session_service_delete_session_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceAsyncClient",
- "shortName": "SearchTuningServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
+ "shortName": "SessionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceAsyncClient.list_custom_models",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.get_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SearchTuningService.ListCustomModels",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.GetSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SearchTuningService",
- "shortName": "SearchTuningService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "ListCustomModels"
+ "shortName": "GetSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListCustomModelsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetSessionRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -10809,14 +16220,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.ListCustomModelsResponse",
- "shortName": "list_custom_models"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "get_session"
},
- "description": "Sample for ListCustomModels",
- "file": "discoveryengine_v1_generated_search_tuning_service_list_custom_models_async.py",
+ "description": "Sample for GetSession",
+ "file": "discoveryengine_v1_generated_session_service_get_session_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SearchTuningService_ListCustomModels_async",
+ "regionTag": "discoveryengine_v1_generated_SessionService_GetSession_async",
"segments": [
{
"end": 51,
@@ -10849,28 +16260,32 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_search_tuning_service_list_custom_models_async.py"
+ "title": "discoveryengine_v1_generated_session_service_get_session_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceClient",
- "shortName": "SearchTuningServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
+ "shortName": "SessionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceClient.list_custom_models",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.get_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SearchTuningService.ListCustomModels",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.GetSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SearchTuningService",
- "shortName": "SearchTuningService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "ListCustomModels"
+ "shortName": "GetSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListCustomModelsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetSessionRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -10885,14 +16300,14 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.ListCustomModelsResponse",
- "shortName": "list_custom_models"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "get_session"
},
- "description": "Sample for ListCustomModels",
- "file": "discoveryengine_v1_generated_search_tuning_service_list_custom_models_sync.py",
+ "description": "Sample for GetSession",
+ "file": "discoveryengine_v1_generated_session_service_get_session_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SearchTuningService_ListCustomModels_sync",
+ "regionTag": "discoveryengine_v1_generated_SessionService_GetSession_sync",
"segments": [
{
"end": 51,
@@ -10925,29 +16340,33 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_search_tuning_service_list_custom_models_sync.py"
+ "title": "discoveryengine_v1_generated_session_service_get_session_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceAsyncClient",
- "shortName": "SearchTuningServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
+ "shortName": "SessionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceAsyncClient.train_custom_model",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.list_sessions",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SearchTuningService.TrainCustomModel",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.ListSessions",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SearchTuningService",
- "shortName": "SearchTuningService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "TrainCustomModel"
+ "shortName": "ListSessions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.TrainCustomModelRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListSessionsRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -10962,22 +16381,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "train_custom_model"
+ "resultType": "google.cloud.discoveryengine_v1.services.session_service.pagers.ListSessionsAsyncPager",
+ "shortName": "list_sessions"
},
- "description": "Sample for TrainCustomModel",
- "file": "discoveryengine_v1_generated_search_tuning_service_train_custom_model_async.py",
+ "description": "Sample for ListSessions",
+ "file": "discoveryengine_v1_generated_session_service_list_sessions_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SearchTuningService_TrainCustomModel_async",
+ "regionTag": "discoveryengine_v1_generated_SessionService_ListSessions_async",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -10992,38 +16411,42 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_search_tuning_service_train_custom_model_async.py"
+ "title": "discoveryengine_v1_generated_session_service_list_sessions_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceClient",
- "shortName": "SearchTuningServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
+ "shortName": "SessionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SearchTuningServiceClient.train_custom_model",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.list_sessions",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SearchTuningService.TrainCustomModel",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.ListSessions",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SearchTuningService",
- "shortName": "SearchTuningService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "TrainCustomModel"
+ "shortName": "ListSessions"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.TrainCustomModelRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListSessionsRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -11038,22 +16461,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "train_custom_model"
+ "resultType": "google.cloud.discoveryengine_v1.services.session_service.pagers.ListSessionsPager",
+ "shortName": "list_sessions"
},
- "description": "Sample for TrainCustomModel",
- "file": "discoveryengine_v1_generated_search_tuning_service_train_custom_model_sync.py",
+ "description": "Sample for ListSessions",
+ "file": "discoveryengine_v1_generated_session_service_list_sessions_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SearchTuningService_TrainCustomModel_sync",
+ "regionTag": "discoveryengine_v1_generated_SessionService_ListSessions_sync",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -11068,43 +16491,43 @@
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 52,
+ "end": 48,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 56,
- "start": 53,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_search_tuning_service_train_custom_model_sync.py"
+ "title": "discoveryengine_v1_generated_session_service_list_sessions_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient",
- "shortName": "ServingConfigServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
+ "shortName": "SessionServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceAsyncClient.update_serving_config",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.update_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.UpdateServingConfig",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.UpdateSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
- "shortName": "ServingConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "UpdateServingConfig"
+ "shortName": "UpdateSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateServingConfigRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateSessionRequest"
},
{
- "name": "serving_config",
- "type": "google.cloud.discoveryengine_v1.types.ServingConfig"
+ "name": "session",
+ "type": "google.cloud.discoveryengine_v1.types.Session"
},
{
"name": "update_mask",
@@ -11123,22 +16546,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.ServingConfig",
- "shortName": "update_serving_config"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "update_session"
},
- "description": "Sample for UpdateServingConfig",
- "file": "discoveryengine_v1_generated_serving_config_service_update_serving_config_async.py",
+ "description": "Sample for UpdateSession",
+ "file": "discoveryengine_v1_generated_session_service_update_session_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ServingConfigService_UpdateServingConfig_async",
+ "regionTag": "discoveryengine_v1_generated_SessionService_UpdateSession_async",
"segments": [
{
- "end": 56,
+ "end": 50,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 50,
"start": 27,
"type": "SHORT"
},
@@ -11148,47 +16571,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 50,
+ "end": 44,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 53,
- "start": 51,
+ "end": 47,
+ "start": 45,
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
- "start": 54,
+ "end": 51,
+ "start": 48,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_serving_config_service_update_serving_config_async.py"
+ "title": "discoveryengine_v1_generated_session_service_update_session_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient",
- "shortName": "ServingConfigServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
+ "shortName": "SessionServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.ServingConfigServiceClient.update_serving_config",
+ "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.update_session",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.ServingConfigService.UpdateServingConfig",
+ "fullName": "google.cloud.discoveryengine.v1.SessionService.UpdateSession",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.ServingConfigService",
- "shortName": "ServingConfigService"
+ "fullName": "google.cloud.discoveryengine.v1.SessionService",
+ "shortName": "SessionService"
},
- "shortName": "UpdateServingConfig"
+ "shortName": "UpdateSession"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateServingConfigRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateSessionRequest"
},
{
- "name": "serving_config",
- "type": "google.cloud.discoveryengine_v1.types.ServingConfig"
+ "name": "session",
+ "type": "google.cloud.discoveryengine_v1.types.Session"
},
{
"name": "update_mask",
@@ -11207,22 +16630,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.ServingConfig",
- "shortName": "update_serving_config"
+ "resultType": "google.cloud.discoveryengine_v1.types.Session",
+ "shortName": "update_session"
},
- "description": "Sample for UpdateServingConfig",
- "file": "discoveryengine_v1_generated_serving_config_service_update_serving_config_sync.py",
+ "description": "Sample for UpdateSession",
+ "file": "discoveryengine_v1_generated_session_service_update_session_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_ServingConfigService_UpdateServingConfig_sync",
+ "regionTag": "discoveryengine_v1_generated_SessionService_UpdateSession_sync",
"segments": [
{
- "end": 56,
+ "end": 50,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 50,
"start": 27,
"type": "SHORT"
},
@@ -11232,52 +16655,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 50,
+ "end": 44,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 53,
- "start": 51,
+ "end": 47,
+ "start": 45,
"type": "REQUEST_EXECUTION"
},
{
- "end": 57,
- "start": 54,
+ "end": 51,
+ "start": 48,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_serving_config_service_update_serving_config_sync.py"
+ "title": "discoveryengine_v1_generated_session_service_update_session_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
- "shortName": "SessionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
+ "shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.create_session",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.batch_create_target_sites",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.CreateSession",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.BatchCreateTargetSites",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "CreateSession"
+ "shortName": "BatchCreateTargetSites"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateSessionRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "session",
- "type": "google.cloud.discoveryengine_v1.types.Session"
+ "type": "google.cloud.discoveryengine_v1.types.BatchCreateTargetSitesRequest"
},
{
"name": "retry",
@@ -11292,22 +16707,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "create_session"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "batch_create_target_sites"
},
- "description": "Sample for CreateSession",
- "file": "discoveryengine_v1_generated_session_service_create_session_async.py",
+ "description": "Sample for BatchCreateTargetSites",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_batch_create_target_sites_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_CreateSession_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_BatchCreateTargetSites_async",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -11317,51 +16732,43 @@
"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": "discoveryengine_v1_generated_session_service_create_session_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_batch_create_target_sites_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
- "shortName": "SessionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
+ "shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.create_session",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.batch_create_target_sites",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.CreateSession",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.BatchCreateTargetSites",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "CreateSession"
+ "shortName": "BatchCreateTargetSites"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateSessionRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "session",
- "type": "google.cloud.discoveryengine_v1.types.Session"
+ "type": "google.cloud.discoveryengine_v1.types.BatchCreateTargetSitesRequest"
},
{
"name": "retry",
@@ -11376,22 +16783,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "create_session"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "batch_create_target_sites"
},
- "description": "Sample for CreateSession",
- "file": "discoveryengine_v1_generated_session_service_create_session_sync.py",
+ "description": "Sample for BatchCreateTargetSites",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_batch_create_target_sites_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_CreateSession_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_BatchCreateTargetSites_sync",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -11401,48 +16808,44 @@
"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": "discoveryengine_v1_generated_session_service_create_session_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_batch_create_target_sites_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
- "shortName": "SessionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
+ "shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.delete_session",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.batch_verify_target_sites",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.DeleteSession",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.BatchVerifyTargetSites",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "DeleteSession"
+ "shortName": "BatchVerifyTargetSites"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteSessionRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.BatchVerifyTargetSitesRequest"
},
{
"name": "retry",
@@ -11457,21 +16860,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_session"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "batch_verify_target_sites"
},
- "description": "Sample for DeleteSession",
- "file": "discoveryengine_v1_generated_session_service_delete_session_async.py",
+ "description": "Sample for BatchVerifyTargetSites",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_batch_verify_target_sites_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_DeleteSession_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_BatchVerifyTargetSites_async",
"segments": [
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -11486,40 +16890,38 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_session_service_delete_session_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_batch_verify_target_sites_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
- "shortName": "SessionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
+ "shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.delete_session",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.batch_verify_target_sites",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.DeleteSession",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.BatchVerifyTargetSites",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "DeleteSession"
+ "shortName": "BatchVerifyTargetSites"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteSessionRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.BatchVerifyTargetSitesRequest"
},
{
"name": "retry",
@@ -11534,21 +16936,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "shortName": "delete_session"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "batch_verify_target_sites"
},
- "description": "Sample for DeleteSession",
- "file": "discoveryengine_v1_generated_session_service_delete_session_sync.py",
+ "description": "Sample for BatchVerifyTargetSites",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_batch_verify_target_sites_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_DeleteSession_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_BatchVerifyTargetSites_sync",
"segments": [
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 49,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -11563,42 +16966,48 @@
"type": "REQUEST_INITIALIZATION"
},
{
+ "end": 52,
"start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 50,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_session_service_delete_session_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_batch_verify_target_sites_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
- "shortName": "SessionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
+ "shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.get_session",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.create_sitemap",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.GetSession",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.CreateSitemap",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "GetSession"
+ "shortName": "CreateSitemap"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetSessionRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateSitemapRequest"
},
{
- "name": "name",
+ "name": "parent",
"type": "str"
},
+ {
+ "name": "sitemap",
+ "type": "google.cloud.discoveryengine_v1.types.Sitemap"
+ },
{
"name": "retry",
"type": "google.api_core.retry.Retry"
@@ -11612,22 +17021,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "get_session"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "create_sitemap"
},
- "description": "Sample for GetSession",
- "file": "discoveryengine_v1_generated_session_service_get_session_async.py",
+ "description": "Sample for CreateSitemap",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_create_sitemap_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_GetSession_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_CreateSitemap_async",
"segments": [
{
- "end": 51,
+ "end": 59,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 59,
"start": 27,
"type": "SHORT"
},
@@ -11637,48 +17046,52 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 49,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 56,
+ "start": 50,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 60,
+ "start": 57,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_session_service_get_session_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_create_sitemap_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
- "shortName": "SessionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
+ "shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.get_session",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.create_sitemap",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.GetSession",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.CreateSitemap",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "GetSession"
+ "shortName": "CreateSitemap"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetSessionRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateSitemapRequest"
},
{
- "name": "name",
+ "name": "parent",
"type": "str"
},
+ {
+ "name": "sitemap",
+ "type": "google.cloud.discoveryengine_v1.types.Sitemap"
+ },
{
"name": "retry",
"type": "google.api_core.retry.Retry"
@@ -11692,22 +17105,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "get_session"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "create_sitemap"
},
- "description": "Sample for GetSession",
- "file": "discoveryengine_v1_generated_session_service_get_session_sync.py",
+ "description": "Sample for CreateSitemap",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_create_sitemap_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_GetSession_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_CreateSitemap_sync",
"segments": [
{
- "end": 51,
+ "end": 59,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 59,
"start": 27,
"type": "SHORT"
},
@@ -11717,49 +17130,53 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 49,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 56,
+ "start": 50,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 60,
+ "start": 57,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_session_service_get_session_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_create_sitemap_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
- "shortName": "SessionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
+ "shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.list_sessions",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.create_target_site",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.ListSessions",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.CreateTargetSite",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "ListSessions"
+ "shortName": "CreateTargetSite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListSessionsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateTargetSiteRequest"
},
{
"name": "parent",
"type": "str"
},
+ {
+ "name": "target_site",
+ "type": "google.cloud.discoveryengine_v1.types.TargetSite"
+ },
{
"name": "retry",
"type": "google.api_core.retry.Retry"
@@ -11773,22 +17190,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.session_service.pagers.ListSessionsAsyncPager",
- "shortName": "list_sessions"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "create_target_site"
},
- "description": "Sample for ListSessions",
- "file": "discoveryengine_v1_generated_session_service_list_sessions_async.py",
+ "description": "Sample for CreateTargetSite",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_create_target_site_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_ListSessions_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_CreateTargetSite_async",
"segments": [
{
- "end": 52,
+ "end": 59,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 59,
"start": 27,
"type": "SHORT"
},
@@ -11798,48 +17215,52 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 49,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 56,
+ "start": 50,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 49,
+ "end": 60,
+ "start": 57,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_session_service_list_sessions_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_create_target_site_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
- "shortName": "SessionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
+ "shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.list_sessions",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.create_target_site",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.ListSessions",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.CreateTargetSite",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "ListSessions"
+ "shortName": "CreateTargetSite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListSessionsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.CreateTargetSiteRequest"
},
{
"name": "parent",
"type": "str"
},
+ {
+ "name": "target_site",
+ "type": "google.cloud.discoveryengine_v1.types.TargetSite"
+ },
{
"name": "retry",
"type": "google.api_core.retry.Retry"
@@ -11853,22 +17274,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.session_service.pagers.ListSessionsPager",
- "shortName": "list_sessions"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "create_target_site"
},
- "description": "Sample for ListSessions",
- "file": "discoveryengine_v1_generated_session_service_list_sessions_sync.py",
+ "description": "Sample for CreateTargetSite",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_create_target_site_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_ListSessions_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_CreateTargetSite_sync",
"segments": [
{
- "end": 52,
+ "end": 59,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 59,
"start": 27,
"type": "SHORT"
},
@@ -11878,52 +17299,48 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 49,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 56,
+ "start": 50,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 49,
+ "end": 60,
+ "start": 57,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_session_service_list_sessions_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_create_target_site_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient",
- "shortName": "SessionServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
+ "shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceAsyncClient.update_session",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.delete_sitemap",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.UpdateSession",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DeleteSitemap",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "UpdateSession"
+ "shortName": "DeleteSitemap"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateSessionRequest"
- },
- {
- "name": "session",
- "type": "google.cloud.discoveryengine_v1.types.Session"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteSitemapRequest"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -11938,22 +17355,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "update_session"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "delete_sitemap"
},
- "description": "Sample for UpdateSession",
- "file": "discoveryengine_v1_generated_session_service_update_session_async.py",
+ "description": "Sample for DeleteSitemap",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_delete_sitemap_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_UpdateSession_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DeleteSitemap_async",
"segments": [
{
- "end": 50,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 50,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -11963,51 +17380,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 47,
- "start": 45,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 51,
- "start": 48,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_session_service_update_session_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_delete_sitemap_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient",
- "shortName": "SessionServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
+ "shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SessionServiceClient.update_session",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.delete_sitemap",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService.UpdateSession",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DeleteSitemap",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SessionService",
- "shortName": "SessionService"
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
+ "shortName": "SiteSearchEngineService"
},
- "shortName": "UpdateSession"
+ "shortName": "DeleteSitemap"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateSessionRequest"
- },
- {
- "name": "session",
- "type": "google.cloud.discoveryengine_v1.types.Session"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteSitemapRequest"
},
{
- "name": "update_mask",
- "type": "google.protobuf.field_mask_pb2.FieldMask"
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -12022,22 +17435,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.Session",
- "shortName": "update_session"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "delete_sitemap"
},
- "description": "Sample for UpdateSession",
- "file": "discoveryengine_v1_generated_session_service_update_session_sync.py",
+ "description": "Sample for DeleteSitemap",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_delete_sitemap_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SessionService_UpdateSession_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DeleteSitemap_sync",
"segments": [
{
- "end": 50,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 50,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -12047,22 +17460,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 44,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 47,
- "start": 45,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 51,
- "start": 48,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_session_service_update_session_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_delete_sitemap_sync.py"
},
{
"canonical": true,
@@ -12072,19 +17485,23 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.batch_create_target_sites",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.delete_target_site",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.BatchCreateTargetSites",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DeleteTargetSite",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "BatchCreateTargetSites"
+ "shortName": "DeleteTargetSite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.BatchCreateTargetSitesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteTargetSiteRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -12100,21 +17517,21 @@
}
],
"resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "batch_create_target_sites"
+ "shortName": "delete_target_site"
},
- "description": "Sample for BatchCreateTargetSites",
- "file": "discoveryengine_v1_generated_site_search_engine_service_batch_create_target_sites_async.py",
+ "description": "Sample for DeleteTargetSite",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_delete_target_site_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_BatchCreateTargetSites_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DeleteTargetSite_async",
"segments": [
{
- "end": 60,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -12124,22 +17541,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": "discoveryengine_v1_generated_site_search_engine_service_batch_create_target_sites_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_delete_target_site_async.py"
},
{
"canonical": true,
@@ -12148,19 +17565,23 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.batch_create_target_sites",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.delete_target_site",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.BatchCreateTargetSites",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DeleteTargetSite",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "BatchCreateTargetSites"
+ "shortName": "DeleteTargetSite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.BatchCreateTargetSitesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DeleteTargetSiteRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -12176,21 +17597,21 @@
}
],
"resultType": "google.api_core.operation.Operation",
- "shortName": "batch_create_target_sites"
+ "shortName": "delete_target_site"
},
- "description": "Sample for BatchCreateTargetSites",
- "file": "discoveryengine_v1_generated_site_search_engine_service_batch_create_target_sites_sync.py",
+ "description": "Sample for DeleteTargetSite",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_delete_target_site_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_BatchCreateTargetSites_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DeleteTargetSite_sync",
"segments": [
{
- "end": 60,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -12200,22 +17621,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": "discoveryengine_v1_generated_site_search_engine_service_batch_create_target_sites_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_delete_target_site_sync.py"
},
{
"canonical": true,
@@ -12225,19 +17646,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.batch_verify_target_sites",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.disable_advanced_site_search",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.BatchVerifyTargetSites",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DisableAdvancedSiteSearch",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "BatchVerifyTargetSites"
+ "shortName": "DisableAdvancedSiteSearch"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.BatchVerifyTargetSitesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DisableAdvancedSiteSearchRequest"
},
{
"name": "retry",
@@ -12253,13 +17674,13 @@
}
],
"resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "batch_verify_target_sites"
+ "shortName": "disable_advanced_site_search"
},
- "description": "Sample for BatchVerifyTargetSites",
- "file": "discoveryengine_v1_generated_site_search_engine_service_batch_verify_target_sites_async.py",
+ "description": "Sample for DisableAdvancedSiteSearch",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_disable_advanced_site_search_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_BatchVerifyTargetSites_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DisableAdvancedSiteSearch_async",
"segments": [
{
"end": 55,
@@ -12292,7 +17713,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_batch_verify_target_sites_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_disable_advanced_site_search_async.py"
},
{
"canonical": true,
@@ -12301,19 +17722,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.batch_verify_target_sites",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.disable_advanced_site_search",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.BatchVerifyTargetSites",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DisableAdvancedSiteSearch",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "BatchVerifyTargetSites"
+ "shortName": "DisableAdvancedSiteSearch"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.BatchVerifyTargetSitesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.DisableAdvancedSiteSearchRequest"
},
{
"name": "retry",
@@ -12329,13 +17750,13 @@
}
],
"resultType": "google.api_core.operation.Operation",
- "shortName": "batch_verify_target_sites"
+ "shortName": "disable_advanced_site_search"
},
- "description": "Sample for BatchVerifyTargetSites",
- "file": "discoveryengine_v1_generated_site_search_engine_service_batch_verify_target_sites_sync.py",
+ "description": "Sample for DisableAdvancedSiteSearch",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_disable_advanced_site_search_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_BatchVerifyTargetSites_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DisableAdvancedSiteSearch_sync",
"segments": [
{
"end": 55,
@@ -12368,7 +17789,7 @@
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_batch_verify_target_sites_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_disable_advanced_site_search_sync.py"
},
{
"canonical": true,
@@ -12378,27 +17799,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.create_sitemap",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.enable_advanced_site_search",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.CreateSitemap",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.EnableAdvancedSiteSearch",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "CreateSitemap"
+ "shortName": "EnableAdvancedSiteSearch"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateSitemapRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "sitemap",
- "type": "google.cloud.discoveryengine_v1.types.Sitemap"
+ "type": "google.cloud.discoveryengine_v1.types.EnableAdvancedSiteSearchRequest"
},
{
"name": "retry",
@@ -12414,21 +17827,21 @@
}
],
"resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "create_sitemap"
+ "shortName": "enable_advanced_site_search"
},
- "description": "Sample for CreateSitemap",
- "file": "discoveryengine_v1_generated_site_search_engine_service_create_sitemap_async.py",
+ "description": "Sample for EnableAdvancedSiteSearch",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_enable_advanced_site_search_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_CreateSitemap_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_EnableAdvancedSiteSearch_async",
"segments": [
{
- "end": 59,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 59,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -12438,22 +17851,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 56,
- "start": 50,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 60,
- "start": 57,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_create_sitemap_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_enable_advanced_site_search_async.py"
},
{
"canonical": true,
@@ -12462,27 +17875,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.create_sitemap",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.enable_advanced_site_search",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.CreateSitemap",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.EnableAdvancedSiteSearch",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "CreateSitemap"
+ "shortName": "EnableAdvancedSiteSearch"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateSitemapRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "sitemap",
- "type": "google.cloud.discoveryengine_v1.types.Sitemap"
+ "type": "google.cloud.discoveryengine_v1.types.EnableAdvancedSiteSearchRequest"
},
{
"name": "retry",
@@ -12498,21 +17903,21 @@
}
],
"resultType": "google.api_core.operation.Operation",
- "shortName": "create_sitemap"
+ "shortName": "enable_advanced_site_search"
},
- "description": "Sample for CreateSitemap",
- "file": "discoveryengine_v1_generated_site_search_engine_service_create_sitemap_sync.py",
+ "description": "Sample for EnableAdvancedSiteSearch",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_enable_advanced_site_search_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_CreateSitemap_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_EnableAdvancedSiteSearch_sync",
"segments": [
{
- "end": 59,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 59,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -12522,22 +17927,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 56,
- "start": 50,
+ "end": 52,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 60,
- "start": 57,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_create_sitemap_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_enable_advanced_site_search_sync.py"
},
{
"canonical": true,
@@ -12547,27 +17952,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.create_target_site",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.fetch_domain_verification_status",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.CreateTargetSite",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.FetchDomainVerificationStatus",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "CreateTargetSite"
+ "shortName": "FetchDomainVerificationStatus"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateTargetSiteRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "target_site",
- "type": "google.cloud.discoveryengine_v1.types.TargetSite"
+ "type": "google.cloud.discoveryengine_v1.types.FetchDomainVerificationStatusRequest"
},
{
"name": "retry",
@@ -12582,22 +17979,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "create_target_site"
+ "resultType": "google.cloud.discoveryengine_v1.services.site_search_engine_service.pagers.FetchDomainVerificationStatusAsyncPager",
+ "shortName": "fetch_domain_verification_status"
},
- "description": "Sample for CreateTargetSite",
- "file": "discoveryengine_v1_generated_site_search_engine_service_create_target_site_async.py",
+ "description": "Sample for FetchDomainVerificationStatus",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_fetch_domain_verification_status_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_CreateTargetSite_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_FetchDomainVerificationStatus_async",
"segments": [
{
- "end": 59,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 59,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -12607,22 +18004,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 56,
- "start": 50,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 60,
- "start": 57,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_create_target_site_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_fetch_domain_verification_status_async.py"
},
{
"canonical": true,
@@ -12631,27 +18028,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.create_target_site",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.fetch_domain_verification_status",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.CreateTargetSite",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.FetchDomainVerificationStatus",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "CreateTargetSite"
+ "shortName": "FetchDomainVerificationStatus"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CreateTargetSiteRequest"
- },
- {
- "name": "parent",
- "type": "str"
- },
- {
- "name": "target_site",
- "type": "google.cloud.discoveryengine_v1.types.TargetSite"
+ "type": "google.cloud.discoveryengine_v1.types.FetchDomainVerificationStatusRequest"
},
{
"name": "retry",
@@ -12666,22 +18055,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "create_target_site"
+ "resultType": "google.cloud.discoveryengine_v1.services.site_search_engine_service.pagers.FetchDomainVerificationStatusPager",
+ "shortName": "fetch_domain_verification_status"
},
- "description": "Sample for CreateTargetSite",
- "file": "discoveryengine_v1_generated_site_search_engine_service_create_target_site_sync.py",
+ "description": "Sample for FetchDomainVerificationStatus",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_fetch_domain_verification_status_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_CreateTargetSite_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_FetchDomainVerificationStatus_sync",
"segments": [
{
- "end": 59,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 59,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -12691,22 +18080,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 56,
- "start": 50,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 60,
- "start": 57,
+ "end": 53,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_create_target_site_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_fetch_domain_verification_status_sync.py"
},
{
"canonical": true,
@@ -12716,22 +18105,22 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.delete_sitemap",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.fetch_sitemaps",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DeleteSitemap",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.FetchSitemaps",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "DeleteSitemap"
+ "shortName": "FetchSitemaps"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteSitemapRequest"
+ "type": "google.cloud.discoveryengine_v1.types.FetchSitemapsRequest"
},
{
- "name": "name",
+ "name": "parent",
"type": "str"
},
{
@@ -12747,22 +18136,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "delete_sitemap"
+ "resultType": "google.cloud.discoveryengine_v1.types.FetchSitemapsResponse",
+ "shortName": "fetch_sitemaps"
},
- "description": "Sample for DeleteSitemap",
- "file": "discoveryengine_v1_generated_site_search_engine_service_delete_sitemap_async.py",
+ "description": "Sample for FetchSitemaps",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_fetch_sitemaps_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DeleteSitemap_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_FetchSitemaps_async",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -12777,17 +18166,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": "discoveryengine_v1_generated_site_search_engine_service_delete_sitemap_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_fetch_sitemaps_async.py"
},
{
"canonical": true,
@@ -12796,22 +18185,22 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.delete_sitemap",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.fetch_sitemaps",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DeleteSitemap",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.FetchSitemaps",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "DeleteSitemap"
+ "shortName": "FetchSitemaps"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteSitemapRequest"
+ "type": "google.cloud.discoveryengine_v1.types.FetchSitemapsRequest"
},
{
- "name": "name",
+ "name": "parent",
"type": "str"
},
{
@@ -12827,22 +18216,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "delete_sitemap"
+ "resultType": "google.cloud.discoveryengine_v1.types.FetchSitemapsResponse",
+ "shortName": "fetch_sitemaps"
},
- "description": "Sample for DeleteSitemap",
- "file": "discoveryengine_v1_generated_site_search_engine_service_delete_sitemap_sync.py",
+ "description": "Sample for FetchSitemaps",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_fetch_sitemaps_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DeleteSitemap_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_FetchSitemaps_sync",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -12857,17 +18246,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": "discoveryengine_v1_generated_site_search_engine_service_delete_sitemap_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_fetch_sitemaps_sync.py"
},
{
"canonical": true,
@@ -12877,19 +18266,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.delete_target_site",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.get_site_search_engine",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DeleteTargetSite",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.GetSiteSearchEngine",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "DeleteTargetSite"
+ "shortName": "GetSiteSearchEngine"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteTargetSiteRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetSiteSearchEngineRequest"
},
{
"name": "name",
@@ -12908,22 +18297,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "delete_target_site"
+ "resultType": "google.cloud.discoveryengine_v1.types.SiteSearchEngine",
+ "shortName": "get_site_search_engine"
},
- "description": "Sample for DeleteTargetSite",
- "file": "discoveryengine_v1_generated_site_search_engine_service_delete_target_site_async.py",
+ "description": "Sample for GetSiteSearchEngine",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_get_site_search_engine_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DeleteTargetSite_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_GetSiteSearchEngine_async",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -12938,17 +18327,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": "discoveryengine_v1_generated_site_search_engine_service_delete_target_site_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_get_site_search_engine_async.py"
},
{
"canonical": true,
@@ -12957,19 +18346,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.delete_target_site",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.get_site_search_engine",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DeleteTargetSite",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.GetSiteSearchEngine",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "DeleteTargetSite"
+ "shortName": "GetSiteSearchEngine"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DeleteTargetSiteRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetSiteSearchEngineRequest"
},
{
"name": "name",
@@ -12988,22 +18377,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "delete_target_site"
+ "resultType": "google.cloud.discoveryengine_v1.types.SiteSearchEngine",
+ "shortName": "get_site_search_engine"
},
- "description": "Sample for DeleteTargetSite",
- "file": "discoveryengine_v1_generated_site_search_engine_service_delete_target_site_sync.py",
+ "description": "Sample for GetSiteSearchEngine",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_get_site_search_engine_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DeleteTargetSite_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_GetSiteSearchEngine_sync",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -13018,17 +18407,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": "discoveryengine_v1_generated_site_search_engine_service_delete_target_site_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_get_site_search_engine_sync.py"
},
{
"canonical": true,
@@ -13038,19 +18427,23 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.disable_advanced_site_search",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.get_target_site",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DisableAdvancedSiteSearch",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.GetTargetSite",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "DisableAdvancedSiteSearch"
+ "shortName": "GetTargetSite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DisableAdvancedSiteSearchRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetTargetSiteRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -13065,22 +18458,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "disable_advanced_site_search"
+ "resultType": "google.cloud.discoveryengine_v1.types.TargetSite",
+ "shortName": "get_target_site"
},
- "description": "Sample for DisableAdvancedSiteSearch",
- "file": "discoveryengine_v1_generated_site_search_engine_service_disable_advanced_site_search_async.py",
+ "description": "Sample for GetTargetSite",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_get_target_site_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DisableAdvancedSiteSearch_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_GetTargetSite_async",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -13095,17 +18488,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": "discoveryengine_v1_generated_site_search_engine_service_disable_advanced_site_search_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_get_target_site_async.py"
},
{
"canonical": true,
@@ -13114,19 +18507,23 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.disable_advanced_site_search",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.get_target_site",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.DisableAdvancedSiteSearch",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.GetTargetSite",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "DisableAdvancedSiteSearch"
+ "shortName": "GetTargetSite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.DisableAdvancedSiteSearchRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetTargetSiteRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -13141,22 +18538,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "disable_advanced_site_search"
+ "resultType": "google.cloud.discoveryengine_v1.types.TargetSite",
+ "shortName": "get_target_site"
},
- "description": "Sample for DisableAdvancedSiteSearch",
- "file": "discoveryengine_v1_generated_site_search_engine_service_disable_advanced_site_search_sync.py",
+ "description": "Sample for GetTargetSite",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_get_target_site_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_DisableAdvancedSiteSearch_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_GetTargetSite_sync",
"segments": [
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -13171,17 +18568,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": "discoveryengine_v1_generated_site_search_engine_service_disable_advanced_site_search_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_get_target_site_sync.py"
},
{
"canonical": true,
@@ -13191,19 +18588,23 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.enable_advanced_site_search",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.list_target_sites",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.EnableAdvancedSiteSearch",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.ListTargetSites",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "EnableAdvancedSiteSearch"
+ "shortName": "ListTargetSites"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.EnableAdvancedSiteSearchRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListTargetSitesRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -13218,22 +18619,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "enable_advanced_site_search"
+ "resultType": "google.cloud.discoveryengine_v1.services.site_search_engine_service.pagers.ListTargetSitesAsyncPager",
+ "shortName": "list_target_sites"
},
- "description": "Sample for EnableAdvancedSiteSearch",
- "file": "discoveryengine_v1_generated_site_search_engine_service_enable_advanced_site_search_async.py",
+ "description": "Sample for ListTargetSites",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_list_target_sites_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_EnableAdvancedSiteSearch_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_ListTargetSites_async",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -13248,17 +18649,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": "discoveryengine_v1_generated_site_search_engine_service_enable_advanced_site_search_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_list_target_sites_async.py"
},
{
"canonical": true,
@@ -13267,19 +18668,23 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.enable_advanced_site_search",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.list_target_sites",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.EnableAdvancedSiteSearch",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.ListTargetSites",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "EnableAdvancedSiteSearch"
+ "shortName": "ListTargetSites"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.EnableAdvancedSiteSearchRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListTargetSitesRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -13294,22 +18699,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "enable_advanced_site_search"
+ "resultType": "google.cloud.discoveryengine_v1.services.site_search_engine_service.pagers.ListTargetSitesPager",
+ "shortName": "list_target_sites"
},
- "description": "Sample for EnableAdvancedSiteSearch",
- "file": "discoveryengine_v1_generated_site_search_engine_service_enable_advanced_site_search_sync.py",
+ "description": "Sample for ListTargetSites",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_list_target_sites_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_EnableAdvancedSiteSearch_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_ListTargetSites_sync",
"segments": [
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 55,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -13324,17 +18729,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": "discoveryengine_v1_generated_site_search_engine_service_enable_advanced_site_search_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_list_target_sites_sync.py"
},
{
"canonical": true,
@@ -13344,19 +18749,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.fetch_domain_verification_status",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.recrawl_uris",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.FetchDomainVerificationStatus",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.RecrawlUris",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "FetchDomainVerificationStatus"
+ "shortName": "RecrawlUris"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.FetchDomainVerificationStatusRequest"
+ "type": "google.cloud.discoveryengine_v1.types.RecrawlUrisRequest"
},
{
"name": "retry",
@@ -13371,22 +18776,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.site_search_engine_service.pagers.FetchDomainVerificationStatusAsyncPager",
- "shortName": "fetch_domain_verification_status"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "recrawl_uris"
},
- "description": "Sample for FetchDomainVerificationStatus",
- "file": "discoveryengine_v1_generated_site_search_engine_service_fetch_domain_verification_status_async.py",
+ "description": "Sample for RecrawlUris",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_recrawl_uris_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_FetchDomainVerificationStatus_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_RecrawlUris_async",
"segments": [
{
- "end": 52,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -13396,22 +18801,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": "discoveryengine_v1_generated_site_search_engine_service_fetch_domain_verification_status_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_recrawl_uris_async.py"
},
{
"canonical": true,
@@ -13420,19 +18825,19 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.fetch_domain_verification_status",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.recrawl_uris",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.FetchDomainVerificationStatus",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.RecrawlUris",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "FetchDomainVerificationStatus"
+ "shortName": "RecrawlUris"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.FetchDomainVerificationStatusRequest"
+ "type": "google.cloud.discoveryengine_v1.types.RecrawlUrisRequest"
},
{
"name": "retry",
@@ -13447,22 +18852,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.site_search_engine_service.pagers.FetchDomainVerificationStatusPager",
- "shortName": "fetch_domain_verification_status"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "recrawl_uris"
},
- "description": "Sample for FetchDomainVerificationStatus",
- "file": "discoveryengine_v1_generated_site_search_engine_service_fetch_domain_verification_status_sync.py",
+ "description": "Sample for RecrawlUris",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_recrawl_uris_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_FetchDomainVerificationStatus_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_RecrawlUris_sync",
"segments": [
{
- "end": 52,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -13472,22 +18877,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": "discoveryengine_v1_generated_site_search_engine_service_fetch_domain_verification_status_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_recrawl_uris_sync.py"
},
{
"canonical": true,
@@ -13497,23 +18902,23 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
"shortName": "SiteSearchEngineServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.fetch_sitemaps",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.update_target_site",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.FetchSitemaps",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.UpdateTargetSite",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "FetchSitemaps"
+ "shortName": "UpdateTargetSite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.FetchSitemapsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateTargetSiteRequest"
},
{
- "name": "parent",
- "type": "str"
+ "name": "target_site",
+ "type": "google.cloud.discoveryengine_v1.types.TargetSite"
},
{
"name": "retry",
@@ -13528,22 +18933,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.FetchSitemapsResponse",
- "shortName": "fetch_sitemaps"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "update_target_site"
},
- "description": "Sample for FetchSitemaps",
- "file": "discoveryengine_v1_generated_site_search_engine_service_fetch_sitemaps_async.py",
+ "description": "Sample for UpdateTargetSite",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_update_target_site_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_FetchSitemaps_async",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_UpdateTargetSite_async",
"segments": [
{
- "end": 51,
+ "end": 58,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 58,
"start": 27,
"type": "SHORT"
},
@@ -13553,22 +18958,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 48,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 55,
+ "start": 49,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 59,
+ "start": 56,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_fetch_sitemaps_async.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_update_target_site_async.py"
},
{
"canonical": true,
@@ -13577,23 +18982,23 @@
"fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
"shortName": "SiteSearchEngineServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.fetch_sitemaps",
+ "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.update_target_site",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.FetchSitemaps",
+ "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.UpdateTargetSite",
"service": {
"fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
"shortName": "SiteSearchEngineService"
},
- "shortName": "FetchSitemaps"
+ "shortName": "UpdateTargetSite"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.FetchSitemapsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateTargetSiteRequest"
},
{
- "name": "parent",
- "type": "str"
+ "name": "target_site",
+ "type": "google.cloud.discoveryengine_v1.types.TargetSite"
},
{
"name": "retry",
@@ -13608,22 +19013,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.FetchSitemapsResponse",
- "shortName": "fetch_sitemaps"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "update_target_site"
},
- "description": "Sample for FetchSitemaps",
- "file": "discoveryengine_v1_generated_site_search_engine_service_fetch_sitemaps_sync.py",
+ "description": "Sample for UpdateTargetSite",
+ "file": "discoveryengine_v1_generated_site_search_engine_service_update_target_site_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_FetchSitemaps_sync",
+ "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_UpdateTargetSite_sync",
"segments": [
{
- "end": 51,
+ "end": 58,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 58,
"start": 27,
"type": "SHORT"
},
@@ -13633,48 +19038,44 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 48,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 55,
+ "start": 49,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 59,
+ "start": 56,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_fetch_sitemaps_sync.py"
+ "title": "discoveryengine_v1_generated_site_search_engine_service_update_target_site_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
- "shortName": "SiteSearchEngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient",
+ "shortName": "UserEventServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.get_site_search_engine",
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.collect_user_event",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.GetSiteSearchEngine",
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService",
+ "shortName": "UserEventService"
},
- "shortName": "GetSiteSearchEngine"
+ "shortName": "CollectUserEvent"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetSiteSearchEngineRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.CollectUserEventRequest"
},
{
"name": "retry",
@@ -13689,22 +19090,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.SiteSearchEngine",
- "shortName": "get_site_search_engine"
+ "resultType": "google.api.httpbody_pb2.HttpBody",
+ "shortName": "collect_user_event"
},
- "description": "Sample for GetSiteSearchEngine",
- "file": "discoveryengine_v1_generated_site_search_engine_service_get_site_search_engine_async.py",
+ "description": "Sample for CollectUserEvent",
+ "file": "discoveryengine_v1_generated_user_event_service_collect_user_event_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_GetSiteSearchEngine_async",
+ "regionTag": "discoveryengine_v1_generated_UserEventService_CollectUserEvent_async",
"segments": [
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -13714,47 +19115,43 @@
"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": "discoveryengine_v1_generated_site_search_engine_service_get_site_search_engine_async.py"
+ "title": "discoveryengine_v1_generated_user_event_service_collect_user_event_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
- "shortName": "SiteSearchEngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient",
+ "shortName": "UserEventServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.get_site_search_engine",
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.collect_user_event",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.GetSiteSearchEngine",
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService",
+ "shortName": "UserEventService"
},
- "shortName": "GetSiteSearchEngine"
+ "shortName": "CollectUserEvent"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetSiteSearchEngineRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.CollectUserEventRequest"
},
{
"name": "retry",
@@ -13769,22 +19166,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.SiteSearchEngine",
- "shortName": "get_site_search_engine"
+ "resultType": "google.api.httpbody_pb2.HttpBody",
+ "shortName": "collect_user_event"
},
- "description": "Sample for GetSiteSearchEngine",
- "file": "discoveryengine_v1_generated_site_search_engine_service_get_site_search_engine_sync.py",
+ "description": "Sample for CollectUserEvent",
+ "file": "discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_GetSiteSearchEngine_sync",
+ "regionTag": "discoveryengine_v1_generated_UserEventService_CollectUserEvent_sync",
"segments": [
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -13794,48 +19191,44 @@
"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": "discoveryengine_v1_generated_site_search_engine_service_get_site_search_engine_sync.py"
+ "title": "discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
- "shortName": "SiteSearchEngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient",
+ "shortName": "UserEventServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.get_target_site",
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.import_user_events",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.GetTargetSite",
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService",
+ "shortName": "UserEventService"
},
- "shortName": "GetTargetSite"
+ "shortName": "ImportUserEvents"
},
"parameters": [
{
- "name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetTargetSiteRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.ImportUserEventsRequest"
},
{
"name": "retry",
@@ -13850,22 +19243,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.TargetSite",
- "shortName": "get_target_site"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "import_user_events"
},
- "description": "Sample for GetTargetSite",
- "file": "discoveryengine_v1_generated_site_search_engine_service_get_target_site_async.py",
+ "description": "Sample for ImportUserEvents",
+ "file": "discoveryengine_v1_generated_user_event_service_import_user_events_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_GetTargetSite_async",
+ "regionTag": "discoveryengine_v1_generated_UserEventService_ImportUserEvents_async",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -13875,47 +19268,43 @@
"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": "discoveryengine_v1_generated_site_search_engine_service_get_target_site_async.py"
+ "title": "discoveryengine_v1_generated_user_event_service_import_user_events_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
- "shortName": "SiteSearchEngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient",
+ "shortName": "UserEventServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.get_target_site",
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.import_user_events",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.GetTargetSite",
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService",
+ "shortName": "UserEventService"
},
- "shortName": "GetTargetSite"
+ "shortName": "ImportUserEvents"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.GetTargetSiteRequest"
- },
- {
- "name": "name",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.ImportUserEventsRequest"
},
{
"name": "retry",
@@ -13930,22 +19319,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.TargetSite",
- "shortName": "get_target_site"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "import_user_events"
},
- "description": "Sample for GetTargetSite",
- "file": "discoveryengine_v1_generated_site_search_engine_service_get_target_site_sync.py",
+ "description": "Sample for ImportUserEvents",
+ "file": "discoveryengine_v1_generated_user_event_service_import_user_events_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_GetTargetSite_sync",
+ "regionTag": "discoveryengine_v1_generated_UserEventService_ImportUserEvents_sync",
"segments": [
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 60,
"start": 27,
"type": "SHORT"
},
@@ -13955,48 +19344,44 @@
"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": "discoveryengine_v1_generated_site_search_engine_service_get_target_site_sync.py"
+ "title": "discoveryengine_v1_generated_user_event_service_import_user_events_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
- "shortName": "SiteSearchEngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient",
+ "shortName": "UserEventServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.list_target_sites",
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.purge_user_events",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.ListTargetSites",
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService.PurgeUserEvents",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService",
+ "shortName": "UserEventService"
},
- "shortName": "ListTargetSites"
+ "shortName": "PurgeUserEvents"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListTargetSitesRequest"
- },
- {
- "name": "parent",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.PurgeUserEventsRequest"
},
{
"name": "retry",
@@ -14011,22 +19396,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.site_search_engine_service.pagers.ListTargetSitesAsyncPager",
- "shortName": "list_target_sites"
+ "resultType": "google.api_core.operation_async.AsyncOperation",
+ "shortName": "purge_user_events"
},
- "description": "Sample for ListTargetSites",
- "file": "discoveryengine_v1_generated_site_search_engine_service_list_target_sites_async.py",
+ "description": "Sample for PurgeUserEvents",
+ "file": "discoveryengine_v1_generated_user_event_service_purge_user_events_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_ListTargetSites_async",
+ "regionTag": "discoveryengine_v1_generated_UserEventService_PurgeUserEvents_async",
"segments": [
{
- "end": 52,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -14036,47 +19421,43 @@
"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": "discoveryengine_v1_generated_site_search_engine_service_list_target_sites_async.py"
+ "title": "discoveryengine_v1_generated_user_event_service_purge_user_events_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
- "shortName": "SiteSearchEngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient",
+ "shortName": "UserEventServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.list_target_sites",
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.purge_user_events",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.ListTargetSites",
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService.PurgeUserEvents",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService",
+ "shortName": "UserEventService"
},
- "shortName": "ListTargetSites"
+ "shortName": "PurgeUserEvents"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListTargetSitesRequest"
- },
- {
- "name": "parent",
- "type": "str"
+ "type": "google.cloud.discoveryengine_v1.types.PurgeUserEventsRequest"
},
{
"name": "retry",
@@ -14091,22 +19472,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.site_search_engine_service.pagers.ListTargetSitesPager",
- "shortName": "list_target_sites"
+ "resultType": "google.api_core.operation.Operation",
+ "shortName": "purge_user_events"
},
- "description": "Sample for ListTargetSites",
- "file": "discoveryengine_v1_generated_site_search_engine_service_list_target_sites_sync.py",
+ "description": "Sample for PurgeUserEvents",
+ "file": "discoveryengine_v1_generated_user_event_service_purge_user_events_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_ListTargetSites_sync",
+ "regionTag": "discoveryengine_v1_generated_UserEventService_PurgeUserEvents_sync",
"segments": [
{
- "end": 52,
+ "end": 56,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 56,
"start": 27,
"type": "SHORT"
},
@@ -14116,44 +19497,44 @@
"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": "discoveryengine_v1_generated_site_search_engine_service_list_target_sites_sync.py"
+ "title": "discoveryengine_v1_generated_user_event_service_purge_user_events_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
- "shortName": "SiteSearchEngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient",
+ "shortName": "UserEventServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.recrawl_uris",
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.write_user_event",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.RecrawlUris",
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService.WriteUserEvent",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService",
+ "shortName": "UserEventService"
},
- "shortName": "RecrawlUris"
+ "shortName": "WriteUserEvent"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.RecrawlUrisRequest"
+ "type": "google.cloud.discoveryengine_v1.types.WriteUserEventRequest"
},
{
"name": "retry",
@@ -14168,22 +19549,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "recrawl_uris"
+ "resultType": "google.cloud.discoveryengine_v1.types.UserEvent",
+ "shortName": "write_user_event"
},
- "description": "Sample for RecrawlUris",
- "file": "discoveryengine_v1_generated_site_search_engine_service_recrawl_uris_async.py",
+ "description": "Sample for WriteUserEvent",
+ "file": "discoveryengine_v1_generated_user_event_service_write_user_event_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_RecrawlUris_async",
+ "regionTag": "discoveryengine_v1_generated_UserEventService_WriteUserEvent_async",
"segments": [
{
- "end": 56,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -14193,43 +19574,43 @@
"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": "discoveryengine_v1_generated_site_search_engine_service_recrawl_uris_async.py"
+ "title": "discoveryengine_v1_generated_user_event_service_write_user_event_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
- "shortName": "SiteSearchEngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient",
+ "shortName": "UserEventServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.recrawl_uris",
+ "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.write_user_event",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.RecrawlUris",
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService.WriteUserEvent",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserEventService",
+ "shortName": "UserEventService"
},
- "shortName": "RecrawlUris"
+ "shortName": "WriteUserEvent"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.RecrawlUrisRequest"
+ "type": "google.cloud.discoveryengine_v1.types.WriteUserEventRequest"
},
{
"name": "retry",
@@ -14244,22 +19625,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "recrawl_uris"
+ "resultType": "google.cloud.discoveryengine_v1.types.UserEvent",
+ "shortName": "write_user_event"
},
- "description": "Sample for RecrawlUris",
- "file": "discoveryengine_v1_generated_site_search_engine_service_recrawl_uris_sync.py",
+ "description": "Sample for WriteUserEvent",
+ "file": "discoveryengine_v1_generated_user_event_service_write_user_event_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_RecrawlUris_sync",
+ "regionTag": "discoveryengine_v1_generated_UserEventService_WriteUserEvent_sync",
"segments": [
{
- "end": 56,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -14269,48 +19650,44 @@
"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": "discoveryengine_v1_generated_site_search_engine_service_recrawl_uris_sync.py"
+ "title": "discoveryengine_v1_generated_user_event_service_write_user_event_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient",
- "shortName": "SiteSearchEngineServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient",
+ "shortName": "UserLicenseServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceAsyncClient.update_target_site",
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient.batch_update_user_licenses",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.UpdateTargetSite",
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.BatchUpdateUserLicenses",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
+ "shortName": "UserLicenseService"
},
- "shortName": "UpdateTargetSite"
+ "shortName": "BatchUpdateUserLicenses"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateTargetSiteRequest"
- },
- {
- "name": "target_site",
- "type": "google.cloud.discoveryengine_v1.types.TargetSite"
+ "type": "google.cloud.discoveryengine_v1.types.BatchUpdateUserLicensesRequest"
},
{
"name": "retry",
@@ -14326,21 +19703,21 @@
}
],
"resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "update_target_site"
+ "shortName": "batch_update_user_licenses"
},
- "description": "Sample for UpdateTargetSite",
- "file": "discoveryengine_v1_generated_site_search_engine_service_update_target_site_async.py",
+ "description": "Sample for BatchUpdateUserLicenses",
+ "file": "discoveryengine_v1_generated_user_license_service_batch_update_user_licenses_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_UpdateTargetSite_async",
+ "regionTag": "discoveryengine_v1_generated_UserLicenseService_BatchUpdateUserLicenses_async",
"segments": [
{
- "end": 58,
+ "end": 59,
"start": 27,
"type": "FULL"
},
{
- "end": 58,
+ "end": 59,
"start": 27,
"type": "SHORT"
},
@@ -14350,47 +19727,43 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 48,
+ "end": 49,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 55,
- "start": 49,
+ "end": 56,
+ "start": 50,
"type": "REQUEST_EXECUTION"
},
{
- "end": 59,
- "start": 56,
+ "end": 60,
+ "start": 57,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_update_target_site_async.py"
+ "title": "discoveryengine_v1_generated_user_license_service_batch_update_user_licenses_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient",
- "shortName": "SiteSearchEngineServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient",
+ "shortName": "UserLicenseServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.SiteSearchEngineServiceClient.update_target_site",
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient.batch_update_user_licenses",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService.UpdateTargetSite",
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.BatchUpdateUserLicenses",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.SiteSearchEngineService",
- "shortName": "SiteSearchEngineService"
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
+ "shortName": "UserLicenseService"
},
- "shortName": "UpdateTargetSite"
+ "shortName": "BatchUpdateUserLicenses"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.UpdateTargetSiteRequest"
- },
- {
- "name": "target_site",
- "type": "google.cloud.discoveryengine_v1.types.TargetSite"
+ "type": "google.cloud.discoveryengine_v1.types.BatchUpdateUserLicensesRequest"
},
{
"name": "retry",
@@ -14406,21 +19779,21 @@
}
],
"resultType": "google.api_core.operation.Operation",
- "shortName": "update_target_site"
+ "shortName": "batch_update_user_licenses"
},
- "description": "Sample for UpdateTargetSite",
- "file": "discoveryengine_v1_generated_site_search_engine_service_update_target_site_sync.py",
+ "description": "Sample for BatchUpdateUserLicenses",
+ "file": "discoveryengine_v1_generated_user_license_service_batch_update_user_licenses_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_SiteSearchEngineService_UpdateTargetSite_sync",
+ "regionTag": "discoveryengine_v1_generated_UserLicenseService_BatchUpdateUserLicenses_sync",
"segments": [
{
- "end": 58,
+ "end": 59,
"start": 27,
"type": "FULL"
},
{
- "end": 58,
+ "end": 59,
"start": 27,
"type": "SHORT"
},
@@ -14430,44 +19803,48 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 48,
+ "end": 49,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 55,
- "start": 49,
+ "end": 56,
+ "start": 50,
"type": "REQUEST_EXECUTION"
},
{
- "end": 59,
- "start": 56,
+ "end": 60,
+ "start": 57,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_site_search_engine_service_update_target_site_sync.py"
+ "title": "discoveryengine_v1_generated_user_license_service_batch_update_user_licenses_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient",
- "shortName": "UserEventServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient",
+ "shortName": "UserLicenseServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.collect_user_event",
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient.list_license_configs_usage_stats",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent",
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService",
- "shortName": "UserEventService"
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
+ "shortName": "UserLicenseService"
},
- "shortName": "CollectUserEvent"
+ "shortName": "ListLicenseConfigsUsageStats"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CollectUserEventRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListLicenseConfigsUsageStatsRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -14482,22 +19859,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api.httpbody_pb2.HttpBody",
- "shortName": "collect_user_event"
+ "resultType": "google.cloud.discoveryengine_v1.types.ListLicenseConfigsUsageStatsResponse",
+ "shortName": "list_license_configs_usage_stats"
},
- "description": "Sample for CollectUserEvent",
- "file": "discoveryengine_v1_generated_user_event_service_collect_user_event_async.py",
+ "description": "Sample for ListLicenseConfigsUsageStats",
+ "file": "discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserEventService_CollectUserEvent_async",
+ "regionTag": "discoveryengine_v1_generated_UserLicenseService_ListLicenseConfigsUsageStats_async",
"segments": [
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -14507,43 +19884,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 49,
- "start": 47,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 50,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_user_event_service_collect_user_event_async.py"
+ "title": "discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient",
- "shortName": "UserEventServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient",
+ "shortName": "UserLicenseServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.collect_user_event",
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient.list_license_configs_usage_stats",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService.CollectUserEvent",
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.ListLicenseConfigsUsageStats",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService",
- "shortName": "UserEventService"
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
+ "shortName": "UserLicenseService"
},
- "shortName": "CollectUserEvent"
+ "shortName": "ListLicenseConfigsUsageStats"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.CollectUserEventRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListLicenseConfigsUsageStatsRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -14558,22 +19939,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api.httpbody_pb2.HttpBody",
- "shortName": "collect_user_event"
+ "resultType": "google.cloud.discoveryengine_v1.types.ListLicenseConfigsUsageStatsResponse",
+ "shortName": "list_license_configs_usage_stats"
},
- "description": "Sample for CollectUserEvent",
- "file": "discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py",
+ "description": "Sample for ListLicenseConfigsUsageStats",
+ "file": "discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserEventService_CollectUserEvent_sync",
+ "regionTag": "discoveryengine_v1_generated_UserLicenseService_ListLicenseConfigsUsageStats_sync",
"segments": [
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -14583,44 +19964,48 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 46,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 49,
- "start": 47,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 50,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_user_event_service_collect_user_event_sync.py"
+ "title": "discoveryengine_v1_generated_user_license_service_list_license_configs_usage_stats_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient",
- "shortName": "UserEventServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient",
+ "shortName": "UserLicenseServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.import_user_events",
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient.list_user_licenses",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents",
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.ListUserLicenses",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService",
- "shortName": "UserEventService"
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
+ "shortName": "UserLicenseService"
},
- "shortName": "ImportUserEvents"
+ "shortName": "ListUserLicenses"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportUserEventsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListUserLicensesRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -14635,22 +20020,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "import_user_events"
+ "resultType": "google.cloud.discoveryengine_v1.services.user_license_service.pagers.ListUserLicensesAsyncPager",
+ "shortName": "list_user_licenses"
},
- "description": "Sample for ImportUserEvents",
- "file": "discoveryengine_v1_generated_user_event_service_import_user_events_async.py",
+ "description": "Sample for ListUserLicenses",
+ "file": "discoveryengine_v1_generated_user_license_service_list_user_licenses_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserEventService_ImportUserEvents_async",
+ "regionTag": "discoveryengine_v1_generated_UserLicenseService_ListUserLicenses_async",
"segments": [
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -14660,43 +20045,47 @@
"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": "discoveryengine_v1_generated_user_event_service_import_user_events_async.py"
+ "title": "discoveryengine_v1_generated_user_license_service_list_user_licenses_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient",
- "shortName": "UserEventServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient",
+ "shortName": "UserLicenseServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.import_user_events",
+ "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient.list_user_licenses",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService.ImportUserEvents",
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.ListUserLicenses",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService",
- "shortName": "UserEventService"
+ "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
+ "shortName": "UserLicenseService"
},
- "shortName": "ImportUserEvents"
+ "shortName": "ListUserLicenses"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ImportUserEventsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.ListUserLicensesRequest"
+ },
+ {
+ "name": "parent",
+ "type": "str"
},
{
"name": "retry",
@@ -14711,22 +20100,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "import_user_events"
+ "resultType": "google.cloud.discoveryengine_v1.services.user_license_service.pagers.ListUserLicensesPager",
+ "shortName": "list_user_licenses"
},
- "description": "Sample for ImportUserEvents",
- "file": "discoveryengine_v1_generated_user_event_service_import_user_events_sync.py",
+ "description": "Sample for ListUserLicenses",
+ "file": "discoveryengine_v1_generated_user_license_service_list_user_licenses_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserEventService_ImportUserEvents_sync",
+ "regionTag": "discoveryengine_v1_generated_UserLicenseService_ListUserLicenses_sync",
"segments": [
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "FULL"
},
{
- "end": 60,
+ "end": 52,
"start": 27,
"type": "SHORT"
},
@@ -14736,44 +20125,48 @@
"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": "discoveryengine_v1_generated_user_event_service_import_user_events_sync.py"
+ "title": "discoveryengine_v1_generated_user_license_service_list_user_licenses_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient",
- "shortName": "UserEventServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserStoreServiceAsyncClient",
+ "shortName": "UserStoreServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.purge_user_events",
+ "fullName": "google.cloud.discoveryengine_v1.UserStoreServiceAsyncClient.get_user_store",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService.PurgeUserEvents",
+ "fullName": "google.cloud.discoveryengine.v1.UserStoreService.GetUserStore",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService",
- "shortName": "UserEventService"
+ "fullName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "shortName": "UserStoreService"
},
- "shortName": "PurgeUserEvents"
+ "shortName": "GetUserStore"
},
"parameters": [
{
- "name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeUserEventsRequest"
+ "name": "request",
+ "type": "google.cloud.discoveryengine_v1.types.GetUserStoreRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -14788,22 +20181,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "purge_user_events"
+ "resultType": "google.cloud.discoveryengine_v1.types.UserStore",
+ "shortName": "get_user_store"
},
- "description": "Sample for PurgeUserEvents",
- "file": "discoveryengine_v1_generated_user_event_service_purge_user_events_async.py",
+ "description": "Sample for GetUserStore",
+ "file": "discoveryengine_v1_generated_user_store_service_get_user_store_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserEventService_PurgeUserEvents_async",
+ "regionTag": "discoveryengine_v1_generated_UserStoreService_GetUserStore_async",
"segments": [
{
- "end": 56,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -14813,43 +20206,47 @@
"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": "discoveryengine_v1_generated_user_event_service_purge_user_events_async.py"
+ "title": "discoveryengine_v1_generated_user_store_service_get_user_store_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient",
- "shortName": "UserEventServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserStoreServiceClient",
+ "shortName": "UserStoreServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.purge_user_events",
+ "fullName": "google.cloud.discoveryengine_v1.UserStoreServiceClient.get_user_store",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService.PurgeUserEvents",
+ "fullName": "google.cloud.discoveryengine.v1.UserStoreService.GetUserStore",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService",
- "shortName": "UserEventService"
+ "fullName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "shortName": "UserStoreService"
},
- "shortName": "PurgeUserEvents"
+ "shortName": "GetUserStore"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.PurgeUserEventsRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetUserStoreRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -14864,22 +20261,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "purge_user_events"
+ "resultType": "google.cloud.discoveryengine_v1.types.UserStore",
+ "shortName": "get_user_store"
},
- "description": "Sample for PurgeUserEvents",
- "file": "discoveryengine_v1_generated_user_event_service_purge_user_events_sync.py",
+ "description": "Sample for GetUserStore",
+ "file": "discoveryengine_v1_generated_user_store_service_get_user_store_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserEventService_PurgeUserEvents_sync",
+ "regionTag": "discoveryengine_v1_generated_UserStoreService_GetUserStore_sync",
"segments": [
{
- "end": 56,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 56,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -14889,44 +20286,52 @@
"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": "discoveryengine_v1_generated_user_event_service_purge_user_events_sync.py"
+ "title": "discoveryengine_v1_generated_user_store_service_get_user_store_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient",
- "shortName": "UserEventServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserStoreServiceAsyncClient",
+ "shortName": "UserStoreServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceAsyncClient.write_user_event",
+ "fullName": "google.cloud.discoveryengine_v1.UserStoreServiceAsyncClient.update_user_store",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService.WriteUserEvent",
+ "fullName": "google.cloud.discoveryengine.v1.UserStoreService.UpdateUserStore",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService",
- "shortName": "UserEventService"
+ "fullName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "shortName": "UserStoreService"
},
- "shortName": "WriteUserEvent"
+ "shortName": "UpdateUserStore"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.WriteUserEventRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateUserStoreRequest"
+ },
+ {
+ "name": "user_store",
+ "type": "google.cloud.discoveryengine_v1.types.UserStore"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -14941,22 +20346,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.UserEvent",
- "shortName": "write_user_event"
+ "resultType": "google.cloud.discoveryengine_v1.types.UserStore",
+ "shortName": "update_user_store"
},
- "description": "Sample for WriteUserEvent",
- "file": "discoveryengine_v1_generated_user_event_service_write_user_event_async.py",
+ "description": "Sample for UpdateUserStore",
+ "file": "discoveryengine_v1_generated_user_store_service_update_user_store_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserEventService_WriteUserEvent_async",
+ "regionTag": "discoveryengine_v1_generated_UserStoreService_UpdateUserStore_async",
"segments": [
{
- "end": 51,
+ "end": 50,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 50,
"start": 27,
"type": "SHORT"
},
@@ -14966,43 +20371,51 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 44,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 47,
+ "start": 45,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 51,
+ "start": 48,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_user_event_service_write_user_event_async.py"
+ "title": "discoveryengine_v1_generated_user_store_service_update_user_store_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient",
- "shortName": "UserEventServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.UserStoreServiceClient",
+ "shortName": "UserStoreServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserEventServiceClient.write_user_event",
+ "fullName": "google.cloud.discoveryengine_v1.UserStoreServiceClient.update_user_store",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService.WriteUserEvent",
+ "fullName": "google.cloud.discoveryengine.v1.UserStoreService.UpdateUserStore",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserEventService",
- "shortName": "UserEventService"
+ "fullName": "google.cloud.discoveryengine.v1.UserStoreService",
+ "shortName": "UserStoreService"
},
- "shortName": "WriteUserEvent"
+ "shortName": "UpdateUserStore"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.WriteUserEventRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateUserStoreRequest"
+ },
+ {
+ "name": "user_store",
+ "type": "google.cloud.discoveryengine_v1.types.UserStore"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -15017,22 +20430,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.types.UserEvent",
- "shortName": "write_user_event"
+ "resultType": "google.cloud.discoveryengine_v1.types.UserStore",
+ "shortName": "update_user_store"
},
- "description": "Sample for WriteUserEvent",
- "file": "discoveryengine_v1_generated_user_event_service_write_user_event_sync.py",
+ "description": "Sample for UpdateUserStore",
+ "file": "discoveryengine_v1_generated_user_store_service_update_user_store_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserEventService_WriteUserEvent_sync",
+ "regionTag": "discoveryengine_v1_generated_UserStoreService_UpdateUserStore_sync",
"segments": [
{
- "end": 51,
+ "end": 50,
"start": 27,
"type": "FULL"
},
{
- "end": 51,
+ "end": 50,
"start": 27,
"type": "SHORT"
},
@@ -15042,44 +20455,48 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 44,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 47,
+ "start": 45,
"type": "REQUEST_EXECUTION"
},
{
- "end": 52,
- "start": 49,
+ "end": 51,
+ "start": 48,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_user_event_service_write_user_event_sync.py"
+ "title": "discoveryengine_v1_generated_user_store_service_update_user_store_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient",
- "shortName": "UserLicenseServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.WidgetConfigServiceAsyncClient",
+ "shortName": "WidgetConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient.batch_update_user_licenses",
+ "fullName": "google.cloud.discoveryengine_v1.WidgetConfigServiceAsyncClient.get_widget_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.BatchUpdateUserLicenses",
+ "fullName": "google.cloud.discoveryengine.v1.WidgetConfigService.GetWidgetConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
- "shortName": "UserLicenseService"
+ "fullName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "shortName": "WidgetConfigService"
},
- "shortName": "BatchUpdateUserLicenses"
+ "shortName": "GetWidgetConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.BatchUpdateUserLicensesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetWidgetConfigRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -15094,22 +20511,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation_async.AsyncOperation",
- "shortName": "batch_update_user_licenses"
+ "resultType": "google.cloud.discoveryengine_v1.types.WidgetConfig",
+ "shortName": "get_widget_config"
},
- "description": "Sample for BatchUpdateUserLicenses",
- "file": "discoveryengine_v1_generated_user_license_service_batch_update_user_licenses_async.py",
+ "description": "Sample for GetWidgetConfig",
+ "file": "discoveryengine_v1_generated_widget_config_service_get_widget_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserLicenseService_BatchUpdateUserLicenses_async",
+ "regionTag": "discoveryengine_v1_generated_WidgetConfigService_GetWidgetConfig_async",
"segments": [
{
- "end": 59,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 59,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -15119,43 +20536,47 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 56,
- "start": 50,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 60,
- "start": 57,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_user_license_service_batch_update_user_licenses_async.py"
+ "title": "discoveryengine_v1_generated_widget_config_service_get_widget_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient",
- "shortName": "UserLicenseServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.WidgetConfigServiceClient",
+ "shortName": "WidgetConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient.batch_update_user_licenses",
+ "fullName": "google.cloud.discoveryengine_v1.WidgetConfigServiceClient.get_widget_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.BatchUpdateUserLicenses",
+ "fullName": "google.cloud.discoveryengine.v1.WidgetConfigService.GetWidgetConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
- "shortName": "UserLicenseService"
+ "fullName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "shortName": "WidgetConfigService"
},
- "shortName": "BatchUpdateUserLicenses"
+ "shortName": "GetWidgetConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.BatchUpdateUserLicensesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.GetWidgetConfigRequest"
+ },
+ {
+ "name": "name",
+ "type": "str"
},
{
"name": "retry",
@@ -15170,22 +20591,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.api_core.operation.Operation",
- "shortName": "batch_update_user_licenses"
+ "resultType": "google.cloud.discoveryengine_v1.types.WidgetConfig",
+ "shortName": "get_widget_config"
},
- "description": "Sample for BatchUpdateUserLicenses",
- "file": "discoveryengine_v1_generated_user_license_service_batch_update_user_licenses_sync.py",
+ "description": "Sample for GetWidgetConfig",
+ "file": "discoveryengine_v1_generated_widget_config_service_get_widget_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserLicenseService_BatchUpdateUserLicenses_sync",
+ "regionTag": "discoveryengine_v1_generated_WidgetConfigService_GetWidgetConfig_sync",
"segments": [
{
- "end": 59,
+ "end": 51,
"start": 27,
"type": "FULL"
},
{
- "end": 59,
+ "end": 51,
"start": 27,
"type": "SHORT"
},
@@ -15195,48 +20616,52 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 49,
+ "end": 45,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 56,
- "start": 50,
+ "end": 48,
+ "start": 46,
"type": "REQUEST_EXECUTION"
},
{
- "end": 60,
- "start": 57,
+ "end": 52,
+ "start": 49,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_user_license_service_batch_update_user_licenses_sync.py"
+ "title": "discoveryengine_v1_generated_widget_config_service_get_widget_config_sync.py"
},
{
"canonical": true,
"clientMethod": {
"async": true,
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient",
- "shortName": "UserLicenseServiceAsyncClient"
+ "fullName": "google.cloud.discoveryengine_v1.WidgetConfigServiceAsyncClient",
+ "shortName": "WidgetConfigServiceAsyncClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceAsyncClient.list_user_licenses",
+ "fullName": "google.cloud.discoveryengine_v1.WidgetConfigServiceAsyncClient.update_widget_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.ListUserLicenses",
+ "fullName": "google.cloud.discoveryengine.v1.WidgetConfigService.UpdateWidgetConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
- "shortName": "UserLicenseService"
+ "fullName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "shortName": "WidgetConfigService"
},
- "shortName": "ListUserLicenses"
+ "shortName": "UpdateWidgetConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListUserLicensesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateWidgetConfigRequest"
},
{
- "name": "parent",
- "type": "str"
+ "name": "widget_config",
+ "type": "google.cloud.discoveryengine_v1.types.WidgetConfig"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -15251,22 +20676,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.user_license_service.pagers.ListUserLicensesAsyncPager",
- "shortName": "list_user_licenses"
+ "resultType": "google.cloud.discoveryengine_v1.types.WidgetConfig",
+ "shortName": "update_widget_config"
},
- "description": "Sample for ListUserLicenses",
- "file": "discoveryengine_v1_generated_user_license_service_list_user_licenses_async.py",
+ "description": "Sample for UpdateWidgetConfig",
+ "file": "discoveryengine_v1_generated_widget_config_service_update_widget_config_async.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserLicenseService_ListUserLicenses_async",
+ "regionTag": "discoveryengine_v1_generated_WidgetConfigService_UpdateWidgetConfig_async",
"segments": [
{
- "end": 52,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -15276,47 +20701,51 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 49,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 52,
+ "start": 50,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 49,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_user_license_service_list_user_licenses_async.py"
+ "title": "discoveryengine_v1_generated_widget_config_service_update_widget_config_async.py"
},
{
"canonical": true,
"clientMethod": {
"client": {
- "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient",
- "shortName": "UserLicenseServiceClient"
+ "fullName": "google.cloud.discoveryengine_v1.WidgetConfigServiceClient",
+ "shortName": "WidgetConfigServiceClient"
},
- "fullName": "google.cloud.discoveryengine_v1.UserLicenseServiceClient.list_user_licenses",
+ "fullName": "google.cloud.discoveryengine_v1.WidgetConfigServiceClient.update_widget_config",
"method": {
- "fullName": "google.cloud.discoveryengine.v1.UserLicenseService.ListUserLicenses",
+ "fullName": "google.cloud.discoveryengine.v1.WidgetConfigService.UpdateWidgetConfig",
"service": {
- "fullName": "google.cloud.discoveryengine.v1.UserLicenseService",
- "shortName": "UserLicenseService"
+ "fullName": "google.cloud.discoveryengine.v1.WidgetConfigService",
+ "shortName": "WidgetConfigService"
},
- "shortName": "ListUserLicenses"
+ "shortName": "UpdateWidgetConfig"
},
"parameters": [
{
"name": "request",
- "type": "google.cloud.discoveryengine_v1.types.ListUserLicensesRequest"
+ "type": "google.cloud.discoveryengine_v1.types.UpdateWidgetConfigRequest"
},
{
- "name": "parent",
- "type": "str"
+ "name": "widget_config",
+ "type": "google.cloud.discoveryengine_v1.types.WidgetConfig"
+ },
+ {
+ "name": "update_mask",
+ "type": "google.protobuf.field_mask_pb2.FieldMask"
},
{
"name": "retry",
@@ -15331,22 +20760,22 @@
"type": "Sequence[Tuple[str, Union[str, bytes]]]"
}
],
- "resultType": "google.cloud.discoveryengine_v1.services.user_license_service.pagers.ListUserLicensesPager",
- "shortName": "list_user_licenses"
+ "resultType": "google.cloud.discoveryengine_v1.types.WidgetConfig",
+ "shortName": "update_widget_config"
},
- "description": "Sample for ListUserLicenses",
- "file": "discoveryengine_v1_generated_user_license_service_list_user_licenses_sync.py",
+ "description": "Sample for UpdateWidgetConfig",
+ "file": "discoveryengine_v1_generated_widget_config_service_update_widget_config_sync.py",
"language": "PYTHON",
"origin": "API_DEFINITION",
- "regionTag": "discoveryengine_v1_generated_UserLicenseService_ListUserLicenses_sync",
+ "regionTag": "discoveryengine_v1_generated_WidgetConfigService_UpdateWidgetConfig_sync",
"segments": [
{
- "end": 52,
+ "end": 55,
"start": 27,
"type": "FULL"
},
{
- "end": 52,
+ "end": 55,
"start": 27,
"type": "SHORT"
},
@@ -15356,22 +20785,22 @@
"type": "CLIENT_INITIALIZATION"
},
{
- "end": 45,
+ "end": 49,
"start": 41,
"type": "REQUEST_INITIALIZATION"
},
{
- "end": 48,
- "start": 46,
+ "end": 52,
+ "start": 50,
"type": "REQUEST_EXECUTION"
},
{
- "end": 53,
- "start": 49,
+ "end": 56,
+ "start": 53,
"type": "RESPONSE_HANDLING"
}
],
- "title": "discoveryengine_v1_generated_user_license_service_list_user_licenses_sync.py"
+ "title": "discoveryengine_v1_generated_widget_config_service_update_widget_config_sync.py"
}
]
}
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_acl_config_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_acl_config_service.py
new file mode 100644
index 000000000000..4411285b1f7a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_acl_config_service.py
@@ -0,0 +1,3957 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import asyncio
+import json
+import math
+import os
+from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
+from unittest import mock
+from unittest.mock import AsyncMock
+
+import grpc
+import pytest
+from google.api_core import api_core_version
+from google.protobuf import json_format
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
+
+try:
+ from google.auth.aio import credentials as ga_credentials_async
+
+ HAS_GOOGLE_AUTH_AIO = True
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_AUTH_AIO = False
+
+import google.auth
+from google.api_core import (
+ client_options,
+ gapic_v1,
+ grpc_helpers,
+ grpc_helpers_async,
+ path_template,
+)
+from google.api_core import exceptions as core_exceptions
+from google.api_core import retry as retries
+from google.auth import credentials as ga_credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.location import locations_pb2
+from google.longrunning import operations_pb2 # type: ignore
+from google.oauth2 import service_account
+
+from google.cloud.discoveryengine_v1.services.acl_config_service import (
+ AclConfigServiceAsyncClient,
+ AclConfigServiceClient,
+ transports,
+)
+from google.cloud.discoveryengine_v1.types import acl_config, acl_config_service, common
+
+CRED_INFO_JSON = {
+ "credential_source": "/path/to/file",
+ "credential_type": "service account credentials",
+ "principal": "service-account@example.com",
+}
+CRED_INFO_STRING = json.dumps(CRED_INFO_JSON)
+
+
+@pytest.fixture(autouse=True)
+def disable_mtls_env():
+ with mock.patch.dict(
+ os.environ,
+ {
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false",
+ "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false",
+ },
+ ):
+ yield
+
+
+async def mock_async_gen(data, chunk_size=1):
+ for i in range(0, len(data)): # pragma: NO COVER
+ chunk = data[i : i + chunk_size]
+ yield chunk.encode("utf-8")
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
+# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
+def async_anonymous_credentials():
+ if HAS_GOOGLE_AUTH_AIO:
+ return ga_credentials_async.AnonymousCredentials()
+ return ga_credentials.AnonymousCredentials()
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+# If default endpoint template is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint template so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint_template(client):
+ return (
+ "test.{UNIVERSE_DOMAIN}"
+ if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE)
+ else client._DEFAULT_ENDPOINT_TEMPLATE
+ )
+
+
+@pytest.fixture(autouse=True)
+def set_event_loop():
+ try:
+ asyncio.get_running_loop()
+ yield
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ yield
+ finally:
+ loop.close()
+ asyncio.set_event_loop(None)
+
+
+def test__get_client_cert_source():
+ mock_provided_cert_source = mock.Mock()
+ mock_default_cert_source = mock.Mock()
+
+ assert AclConfigServiceClient._get_client_cert_source(None, False) is None
+ assert (
+ AclConfigServiceClient._get_client_cert_source(mock_provided_cert_source, False)
+ is None
+ )
+ assert (
+ AclConfigServiceClient._get_client_cert_source(mock_provided_cert_source, True)
+ == mock_provided_cert_source
+ )
+
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source", return_value=True
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_default_cert_source,
+ ):
+ assert (
+ AclConfigServiceClient._get_client_cert_source(None, True)
+ is mock_default_cert_source
+ )
+ assert (
+ AclConfigServiceClient._get_client_cert_source(
+ mock_provided_cert_source, "true"
+ )
+ is mock_provided_cert_source
+ )
+
+
+@pytest.mark.parametrize(
+ "error_code,cred_info_json,show_cred_info",
+ [
+ (401, CRED_INFO_JSON, True),
+ (403, CRED_INFO_JSON, True),
+ (404, CRED_INFO_JSON, True),
+ (500, CRED_INFO_JSON, False),
+ (401, None, False),
+ (403, None, False),
+ (404, None, False),
+ (500, None, False),
+ ],
+)
+def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info):
+ cred = mock.Mock(["get_cred_info"])
+ cred.get_cred_info = mock.Mock(return_value=cred_info_json)
+ client = AclConfigServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=["foo"])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ if show_cred_info:
+ assert error.details == ["foo", CRED_INFO_STRING]
+ else:
+ assert error.details == ["foo"]
+
+
+@pytest.mark.parametrize("error_code", [401, 403, 404, 500])
+def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code):
+ cred = mock.Mock([])
+ assert not hasattr(cred, "get_cred_info")
+ client = AclConfigServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=[])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ assert error.details == []
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (AclConfigServiceClient, "grpc"),
+ (AclConfigServiceAsyncClient, "grpc_asyncio"),
+ (AclConfigServiceClient, "rest"),
+ ],
+)
+def test_acl_config_service_client_from_service_account_info(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info, transport=transport_name)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.AclConfigServiceGrpcTransport, "grpc"),
+ (transports.AclConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ (transports.AclConfigServiceRestTransport, "rest"),
+ ],
+)
+def test_acl_config_service_client_service_account_always_use_jwt(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=False)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (AclConfigServiceClient, "grpc"),
+ (AclConfigServiceAsyncClient, "grpc_asyncio"),
+ (AclConfigServiceClient, "rest"),
+ ],
+)
+def test_acl_config_service_client_from_service_account_file(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+def test_acl_config_service_client_get_transport_class():
+ transport = AclConfigServiceClient.get_transport_class()
+ available_transports = [
+ transports.AclConfigServiceGrpcTransport,
+ transports.AclConfigServiceRestTransport,
+ ]
+ assert transport in available_transports
+
+ transport = AclConfigServiceClient.get_transport_class("grpc")
+ assert transport == transports.AclConfigServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (AclConfigServiceClient, transports.AclConfigServiceGrpcTransport, "grpc"),
+ (
+ AclConfigServiceAsyncClient,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (AclConfigServiceClient, transports.AclConfigServiceRestTransport, "rest"),
+ ],
+)
+@mock.patch.object(
+ AclConfigServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(AclConfigServiceClient),
+)
+@mock.patch.object(
+ AclConfigServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(AclConfigServiceAsyncClient),
+)
+def test_acl_config_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(AclConfigServiceClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(AclConfigServiceClient, "get_transport_class") as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name, client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ # Check the case quota_project_id is provided
+ options = client_options.ClientOptions(quota_project_id="octopus")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id="octopus",
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+ # Check the case api_endpoint is provided
+ options = client_options.ClientOptions(
+ api_audience="https://language.googleapis.com"
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience="https://language.googleapis.com",
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (
+ AclConfigServiceClient,
+ transports.AclConfigServiceGrpcTransport,
+ "grpc",
+ "true",
+ ),
+ (
+ AclConfigServiceAsyncClient,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (
+ AclConfigServiceClient,
+ transports.AclConfigServiceGrpcTransport,
+ "grpc",
+ "false",
+ ),
+ (
+ AclConfigServiceAsyncClient,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ (
+ AclConfigServiceClient,
+ transports.AclConfigServiceRestTransport,
+ "rest",
+ "true",
+ ),
+ (
+ AclConfigServiceClient,
+ transports.AclConfigServiceRestTransport,
+ "rest",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ AclConfigServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(AclConfigServiceClient),
+)
+@mock.patch.object(
+ AclConfigServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(AclConfigServiceAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_acl_config_service_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [AclConfigServiceClient, AclConfigServiceAsyncClient]
+)
+@mock.patch.object(
+ AclConfigServiceClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AclConfigServiceClient),
+)
+@mock.patch.object(
+ AclConfigServiceAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(AclConfigServiceAsyncClient),
+)
+def test_acl_config_service_client_get_mtls_endpoint_and_cert_source(client_class):
+ mock_client_cert_source = mock.Mock()
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source == mock_client_cert_source
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported".
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset.
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None)
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None)
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty).
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "")
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "")
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_client_cert_source,
+ ):
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source()
+ )
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source == mock_client_cert_source
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [AclConfigServiceClient, AclConfigServiceAsyncClient]
+)
+@mock.patch.object(
+ AclConfigServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(AclConfigServiceClient),
+)
+@mock.patch.object(
+ AclConfigServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(AclConfigServiceAsyncClient),
+)
+def test_acl_config_service_client_client_api_endpoint(client_class):
+ mock_client_cert_source = client_cert_source_callback
+ api_override = "foo.com"
+ default_universe = AclConfigServiceClient._DEFAULT_UNIVERSE
+ default_endpoint = AclConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = AclConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true",
+ # use ClientOptions.api_endpoint as the api endpoint regardless.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=api_override
+ )
+ client = client_class(
+ client_options=options,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert client.api_endpoint == api_override
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == default_endpoint
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always",
+ # use the DEFAULT_MTLS_ENDPOINT as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+
+ # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default),
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist,
+ # and ClientOptions.universe_domain="bar.com",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint.
+ options = client_options.ClientOptions()
+ universe_exists = hasattr(options, "universe_domain")
+ if universe_exists:
+ options = client_options.ClientOptions(universe_domain=mock_universe)
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ else:
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == (
+ mock_endpoint if universe_exists else default_endpoint
+ )
+ assert client.universe_domain == (
+ mock_universe if universe_exists else default_universe
+ )
+
+ # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ options = client_options.ClientOptions()
+ if hasattr(options, "universe_domain"):
+ delattr(options, "universe_domain")
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == default_endpoint
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (AclConfigServiceClient, transports.AclConfigServiceGrpcTransport, "grpc"),
+ (
+ AclConfigServiceAsyncClient,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (AclConfigServiceClient, transports.AclConfigServiceRestTransport, "rest"),
+ ],
+)
+def test_acl_config_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(
+ scopes=["1", "2"],
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ AclConfigServiceClient,
+ transports.AclConfigServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ AclConfigServiceAsyncClient,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ (
+ AclConfigServiceClient,
+ transports.AclConfigServiceRestTransport,
+ "rest",
+ None,
+ ),
+ ],
+)
+def test_acl_config_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+def test_acl_config_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.acl_config_service.transports.AclConfigServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = AclConfigServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ AclConfigServiceClient,
+ transports.AclConfigServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ AclConfigServiceAsyncClient,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ ],
+)
+def test_acl_config_service_client_create_channel_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # test that the credentials from file are saved and used as the credentials.
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(grpc_helpers, "create_channel") as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ file_creds = ga_credentials.AnonymousCredentials()
+ load_creds.return_value = (file_creds, None)
+ adc.return_value = (creds, None)
+ client = client_class(client_options=options, transport=transport_name)
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=file_creds,
+ credentials_file=None,
+ quota_project_id=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=None,
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ acl_config_service.UpdateAclConfigRequest(),
+ {},
+ ],
+)
+def test_update_acl_config(request_type, transport: str = "grpc"):
+ client = AclConfigServiceClient(
+ 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_acl_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = acl_config.AclConfig(
+ name="name_value",
+ )
+ response = client.update_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = acl_config_service.UpdateAclConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, acl_config.AclConfig)
+ assert response.name == "name_value"
+
+
+def test_update_acl_config_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 = AclConfigServiceClient(
+ 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 = acl_config_service.UpdateAclConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_acl_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_acl_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = acl_config_service.UpdateAclConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_update_acl_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AclConfigServiceClient(
+ 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.update_acl_config in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_acl_config] = (
+ mock_rpc
+ )
+ request = {}
+ client.update_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_acl_config(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_update_acl_config_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 = AclConfigServiceAsyncClient(
+ 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.update_acl_config
+ 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.update_acl_config
+ ] = mock_rpc
+
+ request = {}
+ await client.update_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_acl_config(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",
+ [
+ acl_config_service.UpdateAclConfigRequest(),
+ {},
+ ],
+)
+async def test_update_acl_config_async(request_type, transport: str = "grpc_asyncio"):
+ client = AclConfigServiceAsyncClient(
+ 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.update_acl_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ acl_config.AclConfig(
+ name="name_value",
+ )
+ )
+ response = await client.update_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = acl_config_service.UpdateAclConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, acl_config.AclConfig)
+ assert response.name == "name_value"
+
+
+def test_update_acl_config_field_headers():
+ client = AclConfigServiceClient(
+ 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 = acl_config_service.UpdateAclConfigRequest()
+
+ request.acl_config.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_acl_config), "__call__"
+ ) as call:
+ call.return_value = acl_config.AclConfig()
+ client.update_acl_config(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",
+ "acl_config.name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_acl_config_field_headers_async():
+ client = AclConfigServiceAsyncClient(
+ 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 = acl_config_service.UpdateAclConfigRequest()
+
+ request.acl_config.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_acl_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ acl_config.AclConfig()
+ )
+ await client.update_acl_config(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",
+ "acl_config.name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ acl_config_service.GetAclConfigRequest(),
+ {},
+ ],
+)
+def test_get_acl_config(request_type, transport: str = "grpc"):
+ client = AclConfigServiceClient(
+ 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_acl_config), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = acl_config.AclConfig(
+ name="name_value",
+ )
+ response = client.get_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = acl_config_service.GetAclConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, acl_config.AclConfig)
+ assert response.name == "name_value"
+
+
+def test_get_acl_config_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 = AclConfigServiceClient(
+ 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 = acl_config_service.GetAclConfigRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_acl_config), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_acl_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = acl_config_service.GetAclConfigRequest(
+ name="name_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_acl_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AclConfigServiceClient(
+ 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_acl_config in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_acl_config] = mock_rpc
+ request = {}
+ client.get_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_acl_config(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_acl_config_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 = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_acl_config
+ 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_acl_config
+ ] = mock_rpc
+
+ request = {}
+ await client.get_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_acl_config(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",
+ [
+ acl_config_service.GetAclConfigRequest(),
+ {},
+ ],
+)
+async def test_get_acl_config_async(request_type, transport: str = "grpc_asyncio"):
+ client = AclConfigServiceAsyncClient(
+ 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_acl_config), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ acl_config.AclConfig(
+ name="name_value",
+ )
+ )
+ response = await client.get_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = acl_config_service.GetAclConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, acl_config.AclConfig)
+ assert response.name == "name_value"
+
+
+def test_get_acl_config_field_headers():
+ client = AclConfigServiceClient(
+ 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 = acl_config_service.GetAclConfigRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_acl_config), "__call__") as call:
+ call.return_value = acl_config.AclConfig()
+ client.get_acl_config(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_acl_config_field_headers_async():
+ client = AclConfigServiceAsyncClient(
+ 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 = acl_config_service.GetAclConfigRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_acl_config), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ acl_config.AclConfig()
+ )
+ await client.get_acl_config(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_acl_config_flattened():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_acl_config), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = acl_config.AclConfig()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_acl_config(
+ 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_acl_config_flattened_error():
+ client = AclConfigServiceClient(
+ 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_acl_config(
+ acl_config_service.GetAclConfigRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_acl_config_flattened_async():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_acl_config), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = acl_config.AclConfig()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ acl_config.AclConfig()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_acl_config(
+ 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_acl_config_flattened_error_async():
+ client = AclConfigServiceAsyncClient(
+ 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_acl_config(
+ acl_config_service.GetAclConfigRequest(),
+ name="name_value",
+ )
+
+
+def test_update_acl_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AclConfigServiceClient(
+ 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_acl_config in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_acl_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.update_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_acl_config(request)
+
+ # Establish 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_acl_config_rest_required_fields(
+ request_type=acl_config_service.UpdateAclConfigRequest,
+):
+ transport_class = transports.AclConfigServiceRestTransport
+
+ 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._BaseUpdateAclConfig,
+ "_BaseUpdateAclConfig__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
+
+ # verify required fields with non-default values are left alone
+
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = acl_config.AclConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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
+
+ # Convert return value to protobuf type
+ return_value = acl_config.AclConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_acl_config(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_acl_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AclConfigServiceClient(
+ 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_acl_config in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_acl_config] = mock_rpc
+
+ request = {}
+ client.get_acl_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_acl_config(request)
+
+ # Establish 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_acl_config_rest_required_fields(
+ request_type=acl_config_service.GetAclConfigRequest,
+):
+ transport_class = transports.AclConfigServiceRestTransport
+
+ 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._BaseGetAclConfig,
+ "_BaseGetAclConfig__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 = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = acl_config.AclConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = acl_config.AclConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_acl_config(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_acl_config_rest_flattened():
+ client = AclConfigServiceClient(
+ 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 = acl_config.AclConfig()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {"name": "projects/sample1/locations/sample2/aclConfig"}
+
+ # 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 = acl_config.AclConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_acl_config(**mock_args)
+
+ # Establish that the underlying call 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/*/aclConfig}" % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_acl_config_rest_flattened_error(transport: str = "rest"):
+ client = AclConfigServiceClient(
+ 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_acl_config(
+ acl_config_service.GetAclConfigRequest(),
+ name="name_value",
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.AclConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.AclConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AclConfigServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.AclConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = AclConfigServiceClient(
+ 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 = AclConfigServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.AclConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AclConfigServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AclConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = AclConfigServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AclConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.AclConfigServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AclConfigServiceGrpcTransport,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ transports.AclConfigServiceRestTransport,
+ ],
+)
+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 = AclConfigServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = AclConfigServiceClient(
+ 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_update_acl_config_empty_call_grpc():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_acl_config), "__call__"
+ ) as call:
+ call.return_value = acl_config.AclConfig()
+ client.update_acl_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = acl_config_service.UpdateAclConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_acl_config_empty_call_grpc():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_acl_config), "__call__") as call:
+ call.return_value = acl_config.AclConfig()
+ client.get_acl_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = acl_config_service.GetAclConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = AclConfigServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = AclConfigServiceAsyncClient(
+ 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_update_acl_config_empty_call_grpc_asyncio():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_acl_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ acl_config.AclConfig(
+ name="name_value",
+ )
+ )
+ await client.update_acl_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = acl_config_service.UpdateAclConfigRequest()
+ assert args[0] == request_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_acl_config_empty_call_grpc_asyncio():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_acl_config), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ acl_config.AclConfig(
+ name="name_value",
+ )
+ )
+ await client.get_acl_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = acl_config_service.GetAclConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = AclConfigServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_update_acl_config_rest_bad_request(
+ request_type=acl_config_service.UpdateAclConfigRequest,
+):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "acl_config": {"name": "projects/sample1/locations/sample2/aclConfig"}
+ }
+ 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_acl_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ acl_config_service.UpdateAclConfigRequest,
+ dict,
+ ],
+)
+def test_update_acl_config_rest_call_success(request_type):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "acl_config": {"name": "projects/sample1/locations/sample2/aclConfig"}
+ }
+ request_init["acl_config"] = {
+ "name": "projects/sample1/locations/sample2/aclConfig",
+ "idp_config": {
+ "idp_type": 1,
+ "external_idp_config": {"workforce_pool_name": "workforce_pool_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 = acl_config_service.UpdateAclConfigRequest.meta.fields["acl_config"]
+
+ 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["acl_config"].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["acl_config"][field])):
+ del request_init["acl_config"][field][i][subfield]
+ else:
+ del request_init["acl_config"][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 = acl_config.AclConfig(
+ name="name_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+
+ # Convert return value to protobuf type
+ return_value = acl_config.AclConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_acl_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, acl_config.AclConfig)
+ assert response.name == "name_value"
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_acl_config_rest_interceptors(null_interceptor):
+ transport = transports.AclConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.AclConfigServiceRestInterceptor(),
+ )
+ client = AclConfigServiceClient(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.AclConfigServiceRestInterceptor, "post_update_acl_config"
+ ) as post,
+ mock.patch.object(
+ transports.AclConfigServiceRestInterceptor,
+ "post_update_acl_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.AclConfigServiceRestInterceptor, "pre_update_acl_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = acl_config_service.UpdateAclConfigRequest.pb(
+ acl_config_service.UpdateAclConfigRequest()
+ )
+ 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 = acl_config.AclConfig.to_json(acl_config.AclConfig())
+ req.return_value.content = return_value
+
+ request = acl_config_service.UpdateAclConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = acl_config.AclConfig()
+ post_with_metadata.return_value = acl_config.AclConfig(), metadata
+
+ client.update_acl_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_get_acl_config_rest_bad_request(
+ request_type=acl_config_service.GetAclConfigRequest,
+):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/aclConfig"}
+ 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_acl_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ acl_config_service.GetAclConfigRequest,
+ dict,
+ ],
+)
+def test_get_acl_config_rest_call_success(request_type):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/aclConfig"}
+ 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 = acl_config.AclConfig(
+ name="name_value",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+
+ # Convert return value to protobuf type
+ return_value = acl_config.AclConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_acl_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, acl_config.AclConfig)
+ assert response.name == "name_value"
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_acl_config_rest_interceptors(null_interceptor):
+ transport = transports.AclConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.AclConfigServiceRestInterceptor(),
+ )
+ client = AclConfigServiceClient(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.AclConfigServiceRestInterceptor, "post_get_acl_config"
+ ) as post,
+ mock.patch.object(
+ transports.AclConfigServiceRestInterceptor,
+ "post_get_acl_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.AclConfigServiceRestInterceptor, "pre_get_acl_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = acl_config_service.GetAclConfigRequest.pb(
+ acl_config_service.GetAclConfigRequest()
+ )
+ 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 = acl_config.AclConfig.to_json(acl_config.AclConfig())
+ req.return_value.content = return_value
+
+ request = acl_config_service.GetAclConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = acl_config.AclConfig()
+ post_with_metadata.return_value = acl_config.AclConfig(), metadata
+
+ client.get_acl_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_cancel_operation_rest_bad_request(
+ request_type=operations_pb2.CancelOperationRequest,
+):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = "{}"
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.cancel_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_get_operation_rest_bad_request(
+ request_type=operations_pb2.GetOperationRequest,
+):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.get_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_list_operations_rest_bad_request(
+ request_type=operations_pb2.ListOperationsRequest,
+):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.list_operations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_initialize_client_w_rest():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_update_acl_config_empty_call_rest():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_acl_config), "__call__"
+ ) as call:
+ client.update_acl_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = acl_config_service.UpdateAclConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_acl_config_empty_call_rest():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_acl_config), "__call__") as call:
+ client.get_acl_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = acl_config_service.GetAclConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert isinstance(
+ client.transport,
+ transports.AclConfigServiceGrpcTransport,
+ )
+
+
+def test_acl_config_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
+ transport = transports.AclConfigServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_acl_config_service_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.acl_config_service.transports.AclConfigServiceTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.AclConfigServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "update_acl_config",
+ "get_acl_config",
+ "get_operation",
+ "cancel_operation",
+ "list_operations",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ with pytest.raises(NotImplementedError):
+ transport.close()
+
+ # Catch all for all remaining methods and properties
+ remainder = [
+ "kind",
+ ]
+ for r in remainder:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, r)()
+
+
+def test_acl_config_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.acl_config_service.transports.AclConfigServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.AclConfigServiceTransport(
+ credentials_file="credentials.json",
+ quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_acl_config_service_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.acl_config_service.transports.AclConfigServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.AclConfigServiceTransport()
+ adc.assert_called_once()
+
+
+def test_acl_config_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ AclConfigServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AclConfigServiceGrpcTransport,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_acl_config_service_transport_auth_adc(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AclConfigServiceGrpcTransport,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ transports.AclConfigServiceRestTransport,
+ ],
+)
+def test_acl_config_service_transport_auth_gdch_credentials(transport_class):
+ host = "https://language.com"
+ api_audience_tests = [None, "https://language2.com"]
+ api_audience_expect = [host, "https://language2.com"]
+ for t, e in zip(api_audience_tests, api_audience_expect):
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ gdch_mock = mock.MagicMock()
+ type(gdch_mock).with_gdch_audience = mock.PropertyMock(
+ return_value=gdch_mock
+ )
+ adc.return_value = (gdch_mock, None)
+ transport_class(host=host, api_audience=t)
+ gdch_mock.with_gdch_audience.assert_called_once_with(e)
+
+
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.AclConfigServiceGrpcTransport, grpc_helpers),
+ (transports.AclConfigServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_acl_config_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=["1", "2"],
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AclConfigServiceGrpcTransport,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_acl_config_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_acl_config_service_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.AclConfigServiceRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_acl_config_service_host_no_port(transport_name):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_acl_config_service_host_with_port(transport_name):
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com:8000"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:8000"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com:8000"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "rest",
+ ],
+)
+def test_acl_config_service_client_transport_session_collision(transport_name):
+ creds1 = ga_credentials.AnonymousCredentials()
+ creds2 = ga_credentials.AnonymousCredentials()
+ client1 = AclConfigServiceClient(
+ credentials=creds1,
+ transport=transport_name,
+ )
+ client2 = AclConfigServiceClient(
+ credentials=creds2,
+ transport=transport_name,
+ )
+ session1 = client1.transport.update_acl_config._session
+ session2 = client2.transport.update_acl_config._session
+ assert session1 != session2
+ session1 = client1.transport.get_acl_config._session
+ session2 = client2.transport.get_acl_config._session
+ assert session1 != session2
+
+
+def test_acl_config_service_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.AclConfigServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_acl_config_service_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.AclConfigServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.filterwarnings("ignore::FutureWarning")
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AclConfigServiceGrpcTransport,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_acl_config_service_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = ga_credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AclConfigServiceGrpcTransport,
+ transports.AclConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_acl_config_service_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_acl_config_path():
+ project = "squid"
+ location = "clam"
+ expected = "projects/{project}/locations/{location}/aclConfig".format(
+ project=project,
+ location=location,
+ )
+ actual = AclConfigServiceClient.acl_config_path(project, location)
+ assert expected == actual
+
+
+def test_parse_acl_config_path():
+ expected = {
+ "project": "whelk",
+ "location": "octopus",
+ }
+ path = AclConfigServiceClient.acl_config_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AclConfigServiceClient.parse_acl_config_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "oyster"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = AclConfigServiceClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "nudibranch",
+ }
+ path = AclConfigServiceClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AclConfigServiceClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "cuttlefish"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = AclConfigServiceClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "mussel",
+ }
+ path = AclConfigServiceClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AclConfigServiceClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "winkle"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = AclConfigServiceClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nautilus",
+ }
+ path = AclConfigServiceClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AclConfigServiceClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "scallop"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = AclConfigServiceClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "abalone",
+ }
+ path = AclConfigServiceClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AclConfigServiceClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "squid"
+ location = "clam"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = AclConfigServiceClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "whelk",
+ "location": "octopus",
+ }
+ path = AclConfigServiceClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AclConfigServiceClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.AclConfigServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.AclConfigServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = AclConfigServiceClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+def test_cancel_operation(transport: str = "grpc"):
+ client = AclConfigServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
+ client = AclConfigServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+def test_cancel_operation_field_headers():
+ client = AclConfigServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = None
+
+ client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_field_headers_async():
+ client = AclConfigServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_cancel_operation_from_dict():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_from_dict_async():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_cancel_operation_flattened():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_flattened_async():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+def test_get_operation(transport: str = "grpc"):
+ client = AclConfigServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+@pytest.mark.asyncio
+async def test_get_operation_async(transport: str = "grpc_asyncio"):
+ client = AclConfigServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_get_operation_field_headers():
+ client = AclConfigServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_operation_field_headers_async():
+ client = AclConfigServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_get_operation_from_dict():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ response = client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_from_dict_async():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_get_operation_flattened():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_flattened_async():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+def test_list_operations(transport: str = "grpc"):
+ client = AclConfigServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+ response = client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+@pytest.mark.asyncio
+async def test_list_operations_async(transport: str = "grpc_asyncio"):
+ client = AclConfigServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_list_operations_field_headers():
+ client = AclConfigServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_operations_field_headers_async():
+ client = AclConfigServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+def test_list_operations_from_dict():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ response = client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_from_dict_async():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_list_operations_flattened():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_flattened_async():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+def test_transport_close_grpc():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+@pytest.mark.asyncio
+async def test_transport_close_grpc_asyncio():
+ client = AclConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_transport_close_rest():
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_session")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_client_ctx():
+ transports = [
+ "rest",
+ "grpc",
+ ]
+ for transport in transports:
+ client = AclConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ # Test client calls underlying transport.
+ with mock.patch.object(type(client.transport), "close") as close:
+ close.assert_not_called()
+ with client:
+ pass
+ close.assert_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class",
+ [
+ (AclConfigServiceClient, transports.AclConfigServiceGrpcTransport),
+ (AclConfigServiceAsyncClient, transports.AclConfigServiceGrpcAsyncIOTransport),
+ ],
+)
+def test_api_key_credentials(client_class, transport_class):
+ with mock.patch.object(
+ google.auth._default, "get_api_key_credentials", create=True
+ ) as get_api_key_credentials:
+ mock_cred = mock.Mock()
+ get_api_key_credentials.return_value = mock_cred
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=mock_cred,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_assistant_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_assistant_service.py
index d54cadb965c7..42c841d0c4db 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_assistant_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_assistant_service.py
@@ -39,6 +39,8 @@
HAS_GOOGLE_AUTH_AIO = False
import google.auth
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
from google.api_core import (
client_options,
gapic_v1,
@@ -57,14 +59,18 @@
from google.cloud.discoveryengine_v1.services.assistant_service import (
AssistantServiceAsyncClient,
AssistantServiceClient,
+ pagers,
transports,
)
from google.cloud.discoveryengine_v1.types import (
assist_answer,
+ assistant,
assistant_service,
+ common,
search_service,
session,
)
+from google.cloud.discoveryengine_v1.types import assistant as gcd_assistant
CRED_INFO_JSON = {
"credential_source": "/path/to/file",
@@ -1080,7 +1086,12 @@ def test_assistant_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -1333,13 +1344,91 @@ async def test_stream_assist_field_headers_async():
) in kw["metadata"]
-def test_stream_assist_rest_use_cached_wrapped_rpc():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.CreateAssistantRequest(),
+ {},
+ ],
+)
+def test_create_assistant(request_type, transport: str = "grpc"):
+ client = AssistantServiceClient(
+ 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_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=True,
+ )
+ response = client.create_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.CreateAssistantRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, assistant.Assistant)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert (
+ response.web_grounding_type
+ == assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED
+ )
+ assert response.default_web_grounding_toggle_off is True
+
+
+def test_create_assistant_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 = AssistantServiceClient(
+ 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 = assistant_service.CreateAssistantRequest(
+ parent="parent_value",
+ assistant_id="assistant_id_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_assistant), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_assistant(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.CreateAssistantRequest(
+ parent="parent_value",
+ assistant_id="assistant_id_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_create_assistant_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
client = AssistantServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport="grpc",
)
# Should wrap all calls on client creation
@@ -1347,288 +1436,4041 @@ def test_stream_assist_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.stream_assist in client._transport._wrapped_methods
+ assert client._transport.create_assistant in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = mock.Mock()
mock_rpc.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client._transport._wrapped_methods[client._transport.stream_assist] = mock_rpc
-
+ client._transport._wrapped_methods[client._transport.create_assistant] = (
+ mock_rpc
+ )
request = {}
- client.stream_assist(request)
+ client.create_assistant(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.stream_assist(request)
+ client.create_assistant(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
assert mock_rpc.call_count == 2
-def test_stream_assist_rest_required_fields(
- request_type=assistant_service.StreamAssistRequest,
+@pytest.mark.asyncio
+async def test_create_assistant_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
):
- transport_class = transports.AssistantServiceRestTransport
-
- 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
+ # Clients should use _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 = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
- default_values = getattr(
- transport_class._BaseStreamAssist,
- "_BaseStreamAssist__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)
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- # verify required fields with default values are now present
+ # Ensure method has been cached
+ assert (
+ client._client._transport.create_assistant
+ in client._client._transport._wrapped_methods
+ )
- jsonified_request["name"] = "name_value"
+ # 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_assistant
+ ] = mock_rpc
- # verify required fields with non-default values are left alone
- assert "name" in jsonified_request
- assert jsonified_request["name"] == "name_value"
+ request = {}
+ await client.create_assistant(request)
- client = AssistantServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
- )
- request = request_type(**request_init)
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
- # Designate an appropriate value for the returned response.
- return_value = assistant_service.StreamAssistResponse()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force 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
+ await client.create_assistant(request)
- response_value = Response()
- response_value.status_code = 200
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
- # Convert return value to protobuf type
- return_value = assistant_service.StreamAssistResponse.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- json_return_value = "[{}]".format(json_return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.CreateAssistantRequest(),
+ {},
+ ],
+)
+async def test_create_assistant_async(request_type, transport: str = "grpc_asyncio"):
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
- with mock.patch.object(response_value, "iter_content") as iter_content:
- iter_content.return_value = iter(json_return_value)
- response = client.stream_assist(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
- 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.create_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=True,
+ )
+ )
+ response = await client.create_assistant(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.CreateAssistantRequest()
+ assert args[0] == request
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.AssistantServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, assistant.Assistant)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert (
+ response.web_grounding_type
+ == assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED
)
- with pytest.raises(ValueError):
- client = AssistantServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
+ assert response.default_web_grounding_toggle_off is True
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.AssistantServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = AssistantServiceClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
- # It is an error to provide an api_key and a transport instance.
- transport = transports.AssistantServiceGrpcTransport(
+def test_create_assistant_field_headers():
+ client = AssistantServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
)
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = AssistantServiceClient(
- 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 = AssistantServiceClient(
- client_options=options, 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 = assistant_service.CreateAssistantRequest()
- # It is an error to provide scopes and a transport instance.
- transport = transports.AssistantServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = AssistantServiceClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
+ request.parent = "parent_value"
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_assistant), "__call__") as call:
+ call.return_value = assistant.Assistant()
+ client.create_assistant(request)
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.AssistantServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = AssistantServiceClient(transport=transport)
- assert client.transport is transport
+ # 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"]
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.AssistantServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
- transport = transports.AssistantServiceGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
+@pytest.mark.asyncio
+async def test_create_assistant_field_headers_async():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
)
- channel = transport.grpc_channel
- assert channel
+
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = assistant_service.CreateAssistantRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.create_assistant), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(assistant.Assistant())
+ await client.create_assistant(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"]
@pytest.mark.parametrize(
- "transport_class",
+ "request_type",
[
- transports.AssistantServiceGrpcTransport,
- transports.AssistantServiceGrpcAsyncIOTransport,
- transports.AssistantServiceRestTransport,
+ assistant_service.DeleteAssistantRequest(),
+ {},
],
)
-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_delete_assistant(request_type, transport: str = "grpc"):
+ client = AssistantServiceClient(
+ 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
-def test_transport_kind_grpc():
- transport = AssistantServiceClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.delete_assistant(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.DeleteAssistantRequest()
+ assert args[0] == request
-def test_initialize_client_w_grpc():
- client = AssistantServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
+ # Establish that the response is the type that we expect.
+ assert response is 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_stream_assist_empty_call_grpc():
+def test_delete_assistant_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 = AssistantServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="grpc",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.stream_assist), "__call__") as call:
- call.return_value = iter([assistant_service.StreamAssistResponse()])
- client.stream_assist(request=None)
+ # Populate all string fields in the request which are not UUID4
+ # since we want to check that UUID4 are populated automatically
+ # if they meet the requirements of AIP 4235.
+ request = assistant_service.DeleteAssistantRequest(
+ name="name_value",
+ )
- # Establish that the underlying stub method was called.
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_assistant), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_assistant(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- request_msg = assistant_service.StreamAssistRequest()
+ request_msg = assistant_service.DeleteAssistantRequest(
+ name="name_value",
+ )
assert args[0] == request_msg
-def test_transport_kind_grpc_asyncio():
- transport = AssistantServiceAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
+def test_delete_assistant_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_assistant in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_assistant] = (
+ mock_rpc
+ )
+ request = {}
+ client.delete_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_assistant(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_assistant_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 = AssistantServiceAsyncClient(
+ 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_assistant
+ 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_assistant
+ ] = mock_rpc
+
+ request = {}
+ await client.delete_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.delete_assistant(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",
+ [
+ assistant_service.DeleteAssistantRequest(),
+ {},
+ ],
+)
+async def test_delete_assistant_async(request_type, transport: str = "grpc_asyncio"):
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
)
- assert transport.kind == "grpc_asyncio"
+ # 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_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_assistant(request)
-def test_initialize_client_w_grpc_asyncio():
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.DeleteAssistantRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_assistant_field_headers():
+ client = AssistantServiceClient(
+ 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 = assistant_service.DeleteAssistantRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_assistant), "__call__") as call:
+ call.return_value = None
+ client.delete_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_assistant_field_headers_async():
client = AssistantServiceAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ credentials=async_anonymous_credentials(),
)
- assert client is not 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 = assistant_service.DeleteAssistantRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_assistant), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.delete_assistant(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_assistant_flattened():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.delete_assistant(
+ 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_assistant_flattened_error():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_assistant(
+ assistant_service.DeleteAssistantRequest(),
+ name="name_value",
+ )
-# This test is a coverage failsafe to make sure that totally empty calls,
-# i.e. request == None and no flattened fields passed, work.
@pytest.mark.asyncio
-async def test_stream_assist_empty_call_grpc_asyncio():
+async def test_delete_assistant_flattened_async():
client = AssistantServiceAsyncClient(
credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.stream_assist), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
- call.return_value.read = mock.AsyncMock(
- side_effect=[assistant_service.StreamAssistResponse()]
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.delete_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.delete_assistant(
+ 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_assistant_flattened_error_async():
+ client = AssistantServiceAsyncClient(
+ 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_assistant(
+ assistant_service.DeleteAssistantRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.UpdateAssistantRequest(),
+ {},
+ ],
+)
+def test_update_assistant(request_type, transport: str = "grpc"):
+ client = AssistantServiceClient(
+ 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_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=gcd_assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=True,
+ )
+ response = client.update_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.UpdateAssistantRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_assistant.Assistant)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert (
+ response.web_grounding_type
+ == gcd_assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED
+ )
+ assert response.default_web_grounding_toggle_off is True
+
+
+def test_update_assistant_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 = AssistantServiceClient(
+ 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 = assistant_service.UpdateAssistantRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_assistant), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_assistant(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.UpdateAssistantRequest()
+ assert args[0] == request_msg
+
+
+def test_update_assistant_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ 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.update_assistant in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_assistant] = (
+ mock_rpc
+ )
+ request = {}
+ client.update_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_assistant(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_update_assistant_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 = AssistantServiceAsyncClient(
+ 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.update_assistant
+ 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.update_assistant
+ ] = mock_rpc
+
+ request = {}
+ await client.update_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_assistant(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",
+ [
+ assistant_service.UpdateAssistantRequest(),
+ {},
+ ],
+)
+async def test_update_assistant_async(request_type, transport: str = "grpc_asyncio"):
+ client = AssistantServiceAsyncClient(
+ 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.update_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=gcd_assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=True,
+ )
+ )
+ response = await client.update_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.UpdateAssistantRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_assistant.Assistant)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert (
+ response.web_grounding_type
+ == gcd_assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED
+ )
+ assert response.default_web_grounding_toggle_off is True
+
+
+def test_update_assistant_field_headers():
+ client = AssistantServiceClient(
+ 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 = assistant_service.UpdateAssistantRequest()
+
+ request.assistant.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_assistant), "__call__") as call:
+ call.return_value = gcd_assistant.Assistant()
+ client.update_assistant(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",
+ "assistant.name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_assistant_field_headers_async():
+ client = AssistantServiceAsyncClient(
+ 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 = assistant_service.UpdateAssistantRequest()
+
+ request.assistant.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_assistant), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_assistant.Assistant()
+ )
+ await client.update_assistant(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",
+ "assistant.name=name_value",
+ ) in kw["metadata"]
+
+
+def test_update_assistant_flattened():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_assistant.Assistant()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_assistant(
+ assistant=gcd_assistant.Assistant(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].assistant
+ mock_val = gcd_assistant.Assistant(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+def test_update_assistant_flattened_error():
+ client = AssistantServiceClient(
+ 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_assistant(
+ assistant_service.UpdateAssistantRequest(),
+ assistant=gcd_assistant.Assistant(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_assistant_flattened_async():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.update_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_assistant.Assistant()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_assistant.Assistant()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_assistant(
+ assistant=gcd_assistant.Assistant(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].assistant
+ mock_val = gcd_assistant.Assistant(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_update_assistant_flattened_error_async():
+ client = AssistantServiceAsyncClient(
+ 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_assistant(
+ assistant_service.UpdateAssistantRequest(),
+ assistant=gcd_assistant.Assistant(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.GetAssistantRequest(),
+ {},
+ ],
+)
+def test_get_assistant(request_type, transport: str = "grpc"):
+ client = AssistantServiceClient(
+ 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_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=True,
+ )
+ response = client.get_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.GetAssistantRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, assistant.Assistant)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert (
+ response.web_grounding_type
+ == assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED
+ )
+ assert response.default_web_grounding_toggle_off is True
+
+
+def test_get_assistant_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 = AssistantServiceClient(
+ 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 = assistant_service.GetAssistantRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_assistant), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_assistant(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.GetAssistantRequest(
+ name="name_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_assistant_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ 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_assistant in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_assistant] = mock_rpc
+ request = {}
+ client.get_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_assistant(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_assistant_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 = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_assistant
+ 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_assistant
+ ] = mock_rpc
+
+ request = {}
+ await client.get_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_assistant(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",
+ [
+ assistant_service.GetAssistantRequest(),
+ {},
+ ],
+)
+async def test_get_assistant_async(request_type, transport: str = "grpc_asyncio"):
+ client = AssistantServiceAsyncClient(
+ 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_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=True,
+ )
+ )
+ response = await client.get_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.GetAssistantRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, assistant.Assistant)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert (
+ response.web_grounding_type
+ == assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED
+ )
+ assert response.default_web_grounding_toggle_off is True
+
+
+def test_get_assistant_field_headers():
+ client = AssistantServiceClient(
+ 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 = assistant_service.GetAssistantRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_assistant), "__call__") as call:
+ call.return_value = assistant.Assistant()
+ client.get_assistant(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_assistant_field_headers_async():
+ client = AssistantServiceAsyncClient(
+ 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 = assistant_service.GetAssistantRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_assistant), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(assistant.Assistant())
+ await client.get_assistant(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_assistant_flattened():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = assistant.Assistant()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_assistant(
+ 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_assistant_flattened_error():
+ client = AssistantServiceClient(
+ 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_assistant(
+ assistant_service.GetAssistantRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_assistant_flattened_async():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = assistant.Assistant()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(assistant.Assistant())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_assistant(
+ 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_assistant_flattened_error_async():
+ client = AssistantServiceAsyncClient(
+ 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_assistant(
+ assistant_service.GetAssistantRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.ListAssistantsRequest(),
+ {},
+ ],
+)
+def test_list_assistants(request_type, transport: str = "grpc"):
+ client = AssistantServiceClient(
+ 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_assistants), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = assistant_service.ListAssistantsResponse(
+ next_page_token="next_page_token_value",
+ )
+ response = client.list_assistants(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.ListAssistantsRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListAssistantsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_assistants_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 = AssistantServiceClient(
+ 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 = assistant_service.ListAssistantsRequest(
+ 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.list_assistants), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_assistants(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.ListAssistantsRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_list_assistants_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ 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_assistants in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_assistants] = mock_rpc
+ request = {}
+ client.list_assistants(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_assistants(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_assistants_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 = AssistantServiceAsyncClient(
+ 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_assistants
+ 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_assistants
+ ] = mock_rpc
+
+ request = {}
+ await client.list_assistants(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_assistants(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",
+ [
+ assistant_service.ListAssistantsRequest(),
+ {},
+ ],
+)
+async def test_list_assistants_async(request_type, transport: str = "grpc_asyncio"):
+ client = AssistantServiceAsyncClient(
+ 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_assistants), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ assistant_service.ListAssistantsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_assistants(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = assistant_service.ListAssistantsRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListAssistantsAsyncPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_assistants_field_headers():
+ client = AssistantServiceClient(
+ 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 = assistant_service.ListAssistantsRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_assistants), "__call__") as call:
+ call.return_value = assistant_service.ListAssistantsResponse()
+ client.list_assistants(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_assistants_field_headers_async():
+ client = AssistantServiceAsyncClient(
+ 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 = assistant_service.ListAssistantsRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_assistants), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ assistant_service.ListAssistantsResponse()
+ )
+ await client.list_assistants(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_assistants_flattened():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_assistants), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = assistant_service.ListAssistantsResponse()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_assistants(
+ 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_assistants_flattened_error():
+ client = AssistantServiceClient(
+ 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_assistants(
+ assistant_service.ListAssistantsRequest(),
+ parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_assistants_flattened_async():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_assistants), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = assistant_service.ListAssistantsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ assistant_service.ListAssistantsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_assistants(
+ 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_assistants_flattened_error_async():
+ client = AssistantServiceAsyncClient(
+ 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_assistants(
+ assistant_service.ListAssistantsRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_assistants_pager(transport_name: str = "grpc"):
+ client = AssistantServiceClient(
+ 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_assistants), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ next_page_token="abc",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[],
+ next_page_token="def",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ ],
+ next_page_token="ghi",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_assistants(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, assistant.Assistant) for i in results)
+
+
+def test_list_assistants_pages(transport_name: str = "grpc"):
+ client = AssistantServiceClient(
+ 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_assistants), "__call__") as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ next_page_token="abc",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[],
+ next_page_token="def",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ ],
+ next_page_token="ghi",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_assistants(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_assistants_async_pager():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_assistants), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ next_page_token="abc",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[],
+ next_page_token="def",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ ],
+ next_page_token="ghi",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_assistants(
+ 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, assistant.Assistant) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_assistants_async_pages():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_assistants), "__call__", new_callable=mock.AsyncMock
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ next_page_token="abc",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[],
+ next_page_token="def",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ ],
+ next_page_token="ghi",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (await client.list_assistants(request={})).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_stream_assist_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ 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.stream_assist in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.stream_assist] = mock_rpc
+
+ request = {}
+ client.stream_assist(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.stream_assist(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_stream_assist_rest_required_fields(
+ request_type=assistant_service.StreamAssistRequest,
+):
+ transport_class = transports.AssistantServiceRestTransport
+
+ 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._BaseStreamAssist,
+ "_BaseStreamAssist__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 = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = assistant_service.StreamAssistResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = assistant_service.StreamAssistResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ json_return_value = "[{}]".format(json_return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ with mock.patch.object(response_value, "iter_content") as iter_content:
+ iter_content.return_value = iter(json_return_value)
+ response = client.stream_assist(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_assistant_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ 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_assistant in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_assistant] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.create_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_assistant(request)
+
+ # Establish 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_assistant_rest_required_fields(
+ request_type=assistant_service.CreateAssistantRequest,
+):
+ transport_class = transports.AssistantServiceRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request_init["assistant_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 "assistantId" not in jsonified_request
+
+ default_values = getattr(
+ transport_class._BaseCreateAssistant,
+ "_BaseCreateAssistant__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 "assistantId" in jsonified_request
+ assert jsonified_request["assistantId"] == request_init["assistant_id"]
+
+ jsonified_request["parent"] = "parent_value"
+ jsonified_request["assistantId"] = "assistant_id_value"
+
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("assistantId",))
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
+ assert "assistantId" in jsonified_request
+ assert jsonified_request["assistantId"] == "assistant_id_value"
+
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = assistant.Assistant()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = assistant.Assistant.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_assistant(request)
+
+ expected_params = [
+ (
+ "assistantId",
+ "",
+ ),
+ ("$alt", "json;enum-encoding=int"),
+ ]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_delete_assistant_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ 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_assistant in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_assistant] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.delete_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_assistant(request)
+
+ # Establish 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_assistant_rest_required_fields(
+ request_type=assistant_service.DeleteAssistantRequest,
+):
+ transport_class = transports.AssistantServiceRestTransport
+
+ 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._BaseDeleteAssistant,
+ "_BaseDeleteAssistant__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 = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = ""
+
+ response_value._content = json_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_assistant(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_assistant_rest_flattened():
+ client = AssistantServiceClient(
+ 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 = None
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/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 = ""
+ response_value._content = 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_assistant(**mock_args)
+
+ # Establish that the underlying call 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/*/collections/*/engines/*/assistants/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_delete_assistant_rest_flattened_error(transport: str = "rest"):
+ client = AssistantServiceClient(
+ 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_assistant(
+ assistant_service.DeleteAssistantRequest(),
+ name="name_value",
+ )
+
+
+def test_update_assistant_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ 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_assistant in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_assistant] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.update_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_assistant(request)
+
+ # Establish 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_assistant_rest_required_fields(
+ request_type=assistant_service.UpdateAssistantRequest,
+):
+ transport_class = transports.AssistantServiceRestTransport
+
+ 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._BaseUpdateAssistant,
+ "_BaseUpdateAssistant__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(("updateMask",))
+
+ # verify required fields with non-default values are left alone
+
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_assistant.Assistant()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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
+
+ # Convert return value to protobuf type
+ return_value = gcd_assistant.Assistant.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_assistant(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_assistant_rest_flattened():
+ client = AssistantServiceClient(
+ 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 = gcd_assistant.Assistant()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "assistant": {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/sample5"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ assistant=gcd_assistant.Assistant(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
+ # Convert return value to protobuf type
+ return_value = gcd_assistant.Assistant.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_assistant(**mock_args)
+
+ # Establish that the underlying call 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/{assistant.name=projects/*/locations/*/collections/*/engines/*/assistants/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_update_assistant_rest_flattened_error(transport: str = "rest"):
+ client = AssistantServiceClient(
+ 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_assistant(
+ assistant_service.UpdateAssistantRequest(),
+ assistant=gcd_assistant.Assistant(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_get_assistant_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ 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_assistant in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_assistant] = mock_rpc
+
+ request = {}
+ client.get_assistant(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_assistant(request)
+
+ # Establish 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_assistant_rest_required_fields(
+ request_type=assistant_service.GetAssistantRequest,
+):
+ transport_class = transports.AssistantServiceRestTransport
+
+ 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._BaseGetAssistant,
+ "_BaseGetAssistant__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 = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = assistant.Assistant()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = assistant.Assistant.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_assistant(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_assistant_rest_flattened():
+ client = AssistantServiceClient(
+ 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 = assistant.Assistant()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/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 = assistant.Assistant.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_assistant(**mock_args)
+
+ # Establish that the underlying call 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/*/collections/*/engines/*/assistants/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_assistant_rest_flattened_error(transport: str = "rest"):
+ client = AssistantServiceClient(
+ 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_assistant(
+ assistant_service.GetAssistantRequest(),
+ name="name_value",
+ )
+
+
+def test_list_assistants_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = AssistantServiceClient(
+ 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_assistants in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_assistants] = mock_rpc
+
+ request = {}
+ client.list_assistants(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_assistants(request)
+
+ # Establish 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_assistants_rest_required_fields(
+ request_type=assistant_service.ListAssistantsRequest,
+):
+ transport_class = transports.AssistantServiceRestTransport
+
+ 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._BaseListAssistants,
+ "_BaseListAssistants__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 = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = assistant_service.ListAssistantsResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = assistant_service.ListAssistantsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_assistants(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_assistants_rest_flattened():
+ client = AssistantServiceClient(
+ 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 = assistant_service.ListAssistantsResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/collections/sample3/engines/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 = assistant_service.ListAssistantsResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_assistants(**mock_args)
+
+ # Establish that the underlying call 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/*/collections/*/engines/*}/assistants"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_list_assistants_rest_flattened_error(transport: str = "rest"):
+ client = AssistantServiceClient(
+ 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_assistants(
+ assistant_service.ListAssistantsRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_assistants_rest_pager(transport: str = "rest"):
+ client = AssistantServiceClient(
+ 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 = (
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ next_page_token="abc",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[],
+ next_page_token="def",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ ],
+ next_page_token="ghi",
+ ),
+ assistant_service.ListAssistantsResponse(
+ assistants=[
+ assistant.Assistant(),
+ assistant.Assistant(),
+ ],
+ ),
+ )
+ # Two responses for two calls
+ response = response + response
+
+ # Wrap the values into proper Response objs
+ response = tuple(
+ assistant_service.ListAssistantsResponse.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/collections/sample3/engines/sample4"
+ }
+
+ pager = client.list_assistants(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, assistant.Assistant) for i in results)
+
+ pages = list(client.list_assistants(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.AssistantServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.AssistantServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AssistantServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.AssistantServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = AssistantServiceClient(
+ 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 = AssistantServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.AssistantServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = AssistantServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AssistantServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = AssistantServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.AssistantServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.AssistantServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.AssistantServiceGrpcTransport,
+ transports.AssistantServiceGrpcAsyncIOTransport,
+ transports.AssistantServiceRestTransport,
+ ],
+)
+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 = AssistantServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = AssistantServiceClient(
+ 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_stream_assist_empty_call_grpc():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.stream_assist), "__call__") as call:
+ call.return_value = iter([assistant_service.StreamAssistResponse()])
+ client.stream_assist(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.StreamAssistRequest()
+ assert args[0] == request_msg
+
+
+# This 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_assistant_empty_call_grpc():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.create_assistant), "__call__") as call:
+ call.return_value = assistant.Assistant()
+ client.create_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.CreateAssistantRequest()
+ assert args[0] == request_msg
+
+
+# This 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_assistant_empty_call_grpc():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_assistant), "__call__") as call:
+ call.return_value = None
+ client.delete_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.DeleteAssistantRequest()
+ assert args[0] == request_msg
+
+
+# This 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_assistant_empty_call_grpc():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.update_assistant), "__call__") as call:
+ call.return_value = gcd_assistant.Assistant()
+ client.update_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.UpdateAssistantRequest()
+ assert args[0] == request_msg
+
+
+# This 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_assistant_empty_call_grpc():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_assistant), "__call__") as call:
+ call.return_value = assistant.Assistant()
+ client.get_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.GetAssistantRequest()
+ assert args[0] == request_msg
+
+
+# This 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_assistants_empty_call_grpc():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_assistants), "__call__") as call:
+ call.return_value = assistant_service.ListAssistantsResponse()
+ client.list_assistants(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.ListAssistantsRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = AssistantServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = AssistantServiceAsyncClient(
+ 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_stream_assist_empty_call_grpc_asyncio():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.stream_assist), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = mock.Mock(aio.UnaryStreamCall, autospec=True)
+ call.return_value.read = mock.AsyncMock(
+ side_effect=[assistant_service.StreamAssistResponse()]
+ )
+ await client.stream_assist(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.StreamAssistRequest()
+ assert args[0] == request_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_assistant_empty_call_grpc_asyncio():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.create_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=True,
+ )
+ )
+ await client.create_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.CreateAssistantRequest()
+ assert args[0] == request_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_assistant_empty_call_grpc_asyncio():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.delete_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.DeleteAssistantRequest()
+ assert args[0] == request_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_assistant_empty_call_grpc_asyncio():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.update_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=gcd_assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=True,
+ )
+ )
+ await client.update_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.UpdateAssistantRequest()
+ assert args[0] == request_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_assistant_empty_call_grpc_asyncio():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_assistant), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=True,
+ )
+ )
+ await client.get_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.GetAssistantRequest()
+ assert args[0] == request_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_assistants_empty_call_grpc_asyncio():
+ client = AssistantServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_assistants), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ assistant_service.ListAssistantsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ await client.list_assistants(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.ListAssistantsRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = AssistantServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_stream_assist_rest_bad_request(
+ request_type=assistant_service.StreamAssistRequest,
+):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/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.stream_assist(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.StreamAssistRequest,
+ dict,
+ ],
+)
+def test_stream_assist_rest_call_success(request_type):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/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 = assistant_service.StreamAssistResponse(
+ assist_token="assist_token_value",
+ invocation_tools=["invocation_tools_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 = assistant_service.StreamAssistResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ json_return_value = "[{}]".format(json_return_value)
+ response_value.iter_content = mock.Mock(return_value=iter(json_return_value))
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ response = client.stream_assist(request)
+
+ assert isinstance(response, Iterable)
+ response = next(response)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, assistant_service.StreamAssistResponse)
+ assert response.assist_token == "assist_token_value"
+ assert response.invocation_tools == ["invocation_tools_value"]
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_stream_assist_rest_interceptors(null_interceptor):
+ transport = transports.AssistantServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.AssistantServiceRestInterceptor(),
+ )
+ client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "post_stream_assist"
+ ) as post,
+ mock.patch.object(
+ transports.AssistantServiceRestInterceptor,
+ "post_stream_assist_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.AssistantServiceRestInterceptor, "pre_stream_assist"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = assistant_service.StreamAssistRequest.pb(
+ assistant_service.StreamAssistRequest()
+ )
+ 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 = assistant_service.StreamAssistResponse.to_json(
+ assistant_service.StreamAssistResponse()
+ )
+ req.return_value.iter_content = mock.Mock(return_value=iter(return_value))
+
+ request = assistant_service.StreamAssistRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = assistant_service.StreamAssistResponse()
+ post_with_metadata.return_value = (
+ assistant_service.StreamAssistResponse(),
+ metadata,
+ )
+
+ client.stream_assist(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_create_assistant_rest_bad_request(
+ request_type=assistant_service.CreateAssistantRequest,
+):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/collections/sample3/engines/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.create_assistant(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.CreateAssistantRequest,
+ dict,
+ ],
+)
+def test_create_assistant_rest_call_success(request_type):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "parent": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ }
+ request_init["assistant"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "generation_config": {
+ "default_model_id": "default_model_id_value",
+ "allowed_model_ids": [
+ "allowed_model_ids_value1",
+ "allowed_model_ids_value2",
+ ],
+ "system_instruction": {
+ "additional_system_instruction": "additional_system_instruction_value"
+ },
+ "default_language": "default_language_value",
+ },
+ "web_grounding_type": 1,
+ "default_web_grounding_toggle_off": True,
+ "enabled_tools": {},
+ "customer_policy": {
+ "banned_phrases": [
+ {"phrase": "phrase_value", "match_type": 1, "ignore_diacritics": True}
+ ],
+ "model_armor_config": {
+ "user_prompt_template": "user_prompt_template_value",
+ "response_template": "response_template_value",
+ "failure_mode": 1,
+ },
+ "data_protection_policy": {
+ "sensitive_data_protection_policy": {"policy": "policy_value"}
+ },
+ },
+ "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 = assistant_service.CreateAssistantRequest.meta.fields["assistant"]
+
+ 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["assistant"].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["assistant"][field])):
+ del request_init["assistant"][field][i][subfield]
+ else:
+ del request_init["assistant"][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 = assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=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 = assistant.Assistant.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_assistant(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, assistant.Assistant)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert (
+ response.web_grounding_type
+ == assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED
+ )
+ assert response.default_web_grounding_toggle_off is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_assistant_rest_interceptors(null_interceptor):
+ transport = transports.AssistantServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.AssistantServiceRestInterceptor(),
+ )
+ client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "post_create_assistant"
+ ) as post,
+ mock.patch.object(
+ transports.AssistantServiceRestInterceptor,
+ "post_create_assistant_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.AssistantServiceRestInterceptor, "pre_create_assistant"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = assistant_service.CreateAssistantRequest.pb(
+ assistant_service.CreateAssistantRequest()
+ )
+ 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 = assistant.Assistant.to_json(assistant.Assistant())
+ req.return_value.content = return_value
+
+ request = assistant_service.CreateAssistantRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = assistant.Assistant()
+ post_with_metadata.return_value = assistant.Assistant(), metadata
+
+ client.create_assistant(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_delete_assistant_rest_bad_request(
+ request_type=assistant_service.DeleteAssistantRequest,
+):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/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_assistant(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.DeleteAssistantRequest,
+ dict,
+ ],
+)
+def test_delete_assistant_rest_call_success(request_type):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/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 = None
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = ""
+ response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ response = client.delete_assistant(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_assistant_rest_interceptors(null_interceptor):
+ transport = transports.AssistantServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.AssistantServiceRestInterceptor(),
+ )
+ client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "pre_delete_assistant"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ pb_message = assistant_service.DeleteAssistantRequest.pb(
+ assistant_service.DeleteAssistantRequest()
+ )
+ transcode.return_value = {
+ "method": "post",
+ "uri": "my_uri",
+ "body": pb_message,
+ "query_params": pb_message,
+ }
+
+ req.return_value = mock.Mock()
+ req.return_value.status_code = 200
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ request = assistant_service.DeleteAssistantRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+
+ client.delete_assistant(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+
+
+def test_update_assistant_rest_bad_request(
+ request_type=assistant_service.UpdateAssistantRequest,
+):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "assistant": {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/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_assistant(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.UpdateAssistantRequest,
+ dict,
+ ],
+)
+def test_update_assistant_rest_call_success(request_type):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "assistant": {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/sample5"
+ }
+ }
+ request_init["assistant"] = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/sample5",
+ "display_name": "display_name_value",
+ "description": "description_value",
+ "generation_config": {
+ "default_model_id": "default_model_id_value",
+ "allowed_model_ids": [
+ "allowed_model_ids_value1",
+ "allowed_model_ids_value2",
+ ],
+ "system_instruction": {
+ "additional_system_instruction": "additional_system_instruction_value"
+ },
+ "default_language": "default_language_value",
+ },
+ "web_grounding_type": 1,
+ "default_web_grounding_toggle_off": True,
+ "enabled_tools": {},
+ "customer_policy": {
+ "banned_phrases": [
+ {"phrase": "phrase_value", "match_type": 1, "ignore_diacritics": True}
+ ],
+ "model_armor_config": {
+ "user_prompt_template": "user_prompt_template_value",
+ "response_template": "response_template_value",
+ "failure_mode": 1,
+ },
+ "data_protection_policy": {
+ "sensitive_data_protection_policy": {"policy": "policy_value"}
+ },
+ },
+ "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 = assistant_service.UpdateAssistantRequest.meta.fields["assistant"]
+
+ 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["assistant"].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["assistant"][field])):
+ del request_init["assistant"][field][i][subfield]
+ else:
+ del request_init["assistant"][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 = gcd_assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=gcd_assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=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 = gcd_assistant.Assistant.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_assistant(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_assistant.Assistant)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert (
+ response.web_grounding_type
+ == gcd_assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED
+ )
+ assert response.default_web_grounding_toggle_off is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_assistant_rest_interceptors(null_interceptor):
+ transport = transports.AssistantServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.AssistantServiceRestInterceptor(),
+ )
+ client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "post_update_assistant"
+ ) as post,
+ mock.patch.object(
+ transports.AssistantServiceRestInterceptor,
+ "post_update_assistant_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.AssistantServiceRestInterceptor, "pre_update_assistant"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = assistant_service.UpdateAssistantRequest.pb(
+ assistant_service.UpdateAssistantRequest()
+ )
+ 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 = gcd_assistant.Assistant.to_json(gcd_assistant.Assistant())
+ req.return_value.content = return_value
+
+ request = assistant_service.UpdateAssistantRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcd_assistant.Assistant()
+ post_with_metadata.return_value = gcd_assistant.Assistant(), metadata
+
+ client.update_assistant(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_get_assistant_rest_bad_request(
+ request_type=assistant_service.GetAssistantRequest,
+):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/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_assistant(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ assistant_service.GetAssistantRequest,
+ dict,
+ ],
+)
+def test_get_assistant_rest_call_success(request_type):
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/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 = assistant.Assistant(
+ name="name_value",
+ display_name="display_name_value",
+ description="description_value",
+ web_grounding_type=assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED,
+ default_web_grounding_toggle_off=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 = assistant.Assistant.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_assistant(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, assistant.Assistant)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.description == "description_value"
+ assert (
+ response.web_grounding_type
+ == assistant.Assistant.WebGroundingType.WEB_GROUNDING_TYPE_DISABLED
+ )
+ assert response.default_web_grounding_toggle_off is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_assistant_rest_interceptors(null_interceptor):
+ transport = transports.AssistantServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.AssistantServiceRestInterceptor(),
+ )
+ client = AssistantServiceClient(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.AssistantServiceRestInterceptor, "post_get_assistant"
+ ) as post,
+ mock.patch.object(
+ transports.AssistantServiceRestInterceptor,
+ "post_get_assistant_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.AssistantServiceRestInterceptor, "pre_get_assistant"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = assistant_service.GetAssistantRequest.pb(
+ assistant_service.GetAssistantRequest()
)
- await client.stream_assist(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 = assistant_service.StreamAssistRequest()
- 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 = assistant.Assistant.to_json(assistant.Assistant())
+ req.return_value.content = return_value
+ request = assistant_service.GetAssistantRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = assistant.Assistant()
+ post_with_metadata.return_value = assistant.Assistant(), metadata
-def test_transport_kind_rest():
- transport = AssistantServiceClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
+ client.get_assistant(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
-def test_stream_assist_rest_bad_request(
- request_type=assistant_service.StreamAssistRequest,
+
+def test_list_assistants_rest_bad_request(
+ request_type=assistant_service.ListAssistantsRequest,
):
client = AssistantServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/sample5"
+ "parent": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
}
request = request_type(**request_init)
@@ -1645,32 +5487,32 @@ def test_stream_assist_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.stream_assist(request)
+ client.list_assistants(request)
@pytest.mark.parametrize(
"request_type",
[
- assistant_service.StreamAssistRequest,
+ assistant_service.ListAssistantsRequest,
dict,
],
)
-def test_stream_assist_rest_call_success(request_type):
+def test_list_assistants_rest_call_success(request_type):
client = AssistantServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4/assistants/sample5"
+ "parent": "projects/sample1/locations/sample2/collections/sample3/engines/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 = assistant_service.StreamAssistResponse(
- assist_token="assist_token_value",
+ return_value = assistant_service.ListAssistantsResponse(
+ next_page_token="next_page_token_value",
)
# Wrap the value into a proper Response obj
@@ -1678,24 +5520,20 @@ def test_stream_assist_rest_call_success(request_type):
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = assistant_service.StreamAssistResponse.pb(return_value)
+ return_value = assistant_service.ListAssistantsResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
- json_return_value = "[{}]".format(json_return_value)
- response_value.iter_content = mock.Mock(return_value=iter(json_return_value))
+ response_value.content = json_return_value.encode("UTF-8")
req.return_value = response_value
req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
- response = client.stream_assist(request)
-
- assert isinstance(response, Iterable)
- response = next(response)
+ response = client.list_assistants(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, assistant_service.StreamAssistResponse)
- assert response.assist_token == "assist_token_value"
+ assert isinstance(response, pagers.ListAssistantsPager)
+ assert response.next_page_token == "next_page_token_value"
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_stream_assist_rest_interceptors(null_interceptor):
+def test_list_assistants_rest_interceptors(null_interceptor):
transport = transports.AssistantServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -1708,21 +5546,21 @@ def test_stream_assist_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.AssistantServiceRestInterceptor, "post_stream_assist"
+ transports.AssistantServiceRestInterceptor, "post_list_assistants"
) as post,
mock.patch.object(
transports.AssistantServiceRestInterceptor,
- "post_stream_assist_with_metadata",
+ "post_list_assistants_with_metadata",
) as post_with_metadata,
mock.patch.object(
- transports.AssistantServiceRestInterceptor, "pre_stream_assist"
+ transports.AssistantServiceRestInterceptor, "pre_list_assistants"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = assistant_service.StreamAssistRequest.pb(
- assistant_service.StreamAssistRequest()
+ pb_message = assistant_service.ListAssistantsRequest.pb(
+ assistant_service.ListAssistantsRequest()
)
transcode.return_value = {
"method": "post",
@@ -1734,24 +5572,24 @@ def test_stream_assist_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 = assistant_service.StreamAssistResponse.to_json(
- assistant_service.StreamAssistResponse()
+ return_value = assistant_service.ListAssistantsResponse.to_json(
+ assistant_service.ListAssistantsResponse()
)
- req.return_value.iter_content = mock.Mock(return_value=iter(return_value))
+ req.return_value.content = return_value
- request = assistant_service.StreamAssistRequest()
+ request = assistant_service.ListAssistantsRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = assistant_service.StreamAssistResponse()
+ post.return_value = assistant_service.ListAssistantsResponse()
post_with_metadata.return_value = (
- assistant_service.StreamAssistResponse(),
+ assistant_service.ListAssistantsResponse(),
metadata,
)
- client.stream_assist(
+ client.list_assistants(
request,
metadata=[
("key", "val"),
@@ -1977,6 +5815,101 @@ def test_stream_assist_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_assistant_empty_call_rest():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.create_assistant), "__call__") as call:
+ client.create_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.CreateAssistantRequest()
+ assert args[0] == request_msg
+
+
+# This 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_assistant_empty_call_rest():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_assistant), "__call__") as call:
+ client.delete_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.DeleteAssistantRequest()
+ assert args[0] == request_msg
+
+
+# This 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_assistant_empty_call_rest():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.update_assistant), "__call__") as call:
+ client.update_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.UpdateAssistantRequest()
+ assert args[0] == request_msg
+
+
+# This 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_assistant_empty_call_rest():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_assistant), "__call__") as call:
+ client.get_assistant(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.GetAssistantRequest()
+ assert args[0] == request_msg
+
+
+# This 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_assistants_empty_call_rest():
+ client = AssistantServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_assistants), "__call__") as call:
+ client.list_assistants(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = assistant_service.ListAssistantsRequest()
+ assert args[0] == request_msg
+
+
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
client = AssistantServiceClient(
@@ -2011,6 +5944,11 @@ def test_assistant_service_base_transport():
# raise NotImplementedError.
methods = (
"stream_assist",
+ "create_assistant",
+ "delete_assistant",
+ "update_assistant",
+ "get_assistant",
+ "list_assistants",
"get_operation",
"cancel_operation",
"list_operations",
@@ -2050,7 +5988,12 @@ def test_assistant_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2076,7 +6019,12 @@ def test_assistant_service_auth_adc():
AssistantServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -2096,7 +6044,12 @@ def test_assistant_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2149,7 +6102,12 @@ def test_assistant_service_transport_create_channel(transport_class, grpc_helper
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -2282,6 +6240,21 @@ def test_assistant_service_client_transport_session_collision(transport_name):
session1 = client1.transport.stream_assist._session
session2 = client2.transport.stream_assist._session
assert session1 != session2
+ session1 = client1.transport.create_assistant._session
+ session2 = client2.transport.create_assistant._session
+ assert session1 != session2
+ session1 = client1.transport.delete_assistant._session
+ session2 = client2.transport.delete_assistant._session
+ assert session1 != session2
+ session1 = client1.transport.update_assistant._session
+ session2 = client2.transport.update_assistant._session
+ assert session1 != session2
+ session1 = client1.transport.get_assistant._session
+ session2 = client2.transport.get_assistant._session
+ assert session1 != session2
+ session1 = client1.transport.list_assistants._session
+ session2 = client2.transport.list_assistants._session
+ assert session1 != session2
def test_assistant_service_grpc_transport_channel():
@@ -2482,10 +6455,38 @@ def test_parse_assistant_path():
assert expected == actual
-def test_data_store_path():
- project = "scallop"
+def test_content_policy_path():
+ organization = "scallop"
location = "abalone"
- data_store = "squid"
+ content_policy = "squid"
+ expected = "organizations/{organization}/locations/{location}/contentPolicies/{content_policy}".format(
+ organization=organization,
+ location=location,
+ content_policy=content_policy,
+ )
+ actual = AssistantServiceClient.content_policy_path(
+ organization, location, content_policy
+ )
+ assert expected == actual
+
+
+def test_parse_content_policy_path():
+ expected = {
+ "organization": "clam",
+ "location": "whelk",
+ "content_policy": "octopus",
+ }
+ path = AssistantServiceClient.content_policy_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AssistantServiceClient.parse_content_policy_path(path)
+ assert expected == actual
+
+
+def test_data_store_path():
+ project = "oyster"
+ location = "nudibranch"
+ data_store = "cuttlefish"
expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(
project=project,
location=location,
@@ -2497,9 +6498,9 @@ def test_data_store_path():
def test_parse_data_store_path():
expected = {
- "project": "clam",
- "location": "whelk",
- "data_store": "octopus",
+ "project": "mussel",
+ "location": "winkle",
+ "data_store": "nautilus",
}
path = AssistantServiceClient.data_store_path(**expected)
@@ -2509,11 +6510,11 @@ def test_parse_data_store_path():
def test_document_path():
- project = "oyster"
- location = "nudibranch"
- data_store = "cuttlefish"
- branch = "mussel"
- document = "winkle"
+ project = "scallop"
+ location = "abalone"
+ data_store = "squid"
+ branch = "clam"
+ document = "whelk"
expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(
project=project,
location=location,
@@ -2529,11 +6530,11 @@ def test_document_path():
def test_parse_document_path():
expected = {
- "project": "nautilus",
- "location": "scallop",
- "data_store": "abalone",
- "branch": "squid",
- "document": "clam",
+ "project": "octopus",
+ "location": "oyster",
+ "data_store": "nudibranch",
+ "branch": "cuttlefish",
+ "document": "mussel",
}
path = AssistantServiceClient.document_path(**expected)
@@ -2542,11 +6543,40 @@ def test_parse_document_path():
assert expected == actual
+def test_engine_path():
+ project = "winkle"
+ location = "nautilus"
+ collection = "scallop"
+ engine = "abalone"
+ expected = "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format(
+ project=project,
+ location=location,
+ collection=collection,
+ engine=engine,
+ )
+ actual = AssistantServiceClient.engine_path(project, location, collection, engine)
+ assert expected == actual
+
+
+def test_parse_engine_path():
+ expected = {
+ "project": "squid",
+ "location": "clam",
+ "collection": "whelk",
+ "engine": "octopus",
+ }
+ path = AssistantServiceClient.engine_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AssistantServiceClient.parse_engine_path(path)
+ assert expected == actual
+
+
def test_session_path():
- project = "whelk"
- location = "octopus"
- data_store = "oyster"
- session = "nudibranch"
+ project = "oyster"
+ location = "nudibranch"
+ data_store = "cuttlefish"
+ session = "mussel"
expected = "projects/{project}/locations/{location}/dataStores/{data_store}/sessions/{session}".format(
project=project,
location=location,
@@ -2559,10 +6589,10 @@ def test_session_path():
def test_parse_session_path():
expected = {
- "project": "cuttlefish",
- "location": "mussel",
- "data_store": "winkle",
- "session": "nautilus",
+ "project": "winkle",
+ "location": "nautilus",
+ "data_store": "scallop",
+ "session": "abalone",
}
path = AssistantServiceClient.session_path(**expected)
@@ -2571,8 +6601,34 @@ def test_parse_session_path():
assert expected == actual
+def test_template_path():
+ project = "squid"
+ location = "clam"
+ template = "whelk"
+ expected = "projects/{project}/locations/{location}/templates/{template}".format(
+ project=project,
+ location=location,
+ template=template,
+ )
+ actual = AssistantServiceClient.template_path(project, location, template)
+ assert expected == actual
+
+
+def test_parse_template_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "template": "nudibranch",
+ }
+ path = AssistantServiceClient.template_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = AssistantServiceClient.parse_template_path(path)
+ assert expected == actual
+
+
def test_common_billing_account_path():
- billing_account = "scallop"
+ billing_account = "cuttlefish"
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -2582,7 +6638,7 @@ def test_common_billing_account_path():
def test_parse_common_billing_account_path():
expected = {
- "billing_account": "abalone",
+ "billing_account": "mussel",
}
path = AssistantServiceClient.common_billing_account_path(**expected)
@@ -2592,7 +6648,7 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
- folder = "squid"
+ folder = "winkle"
expected = "folders/{folder}".format(
folder=folder,
)
@@ -2602,7 +6658,7 @@ def test_common_folder_path():
def test_parse_common_folder_path():
expected = {
- "folder": "clam",
+ "folder": "nautilus",
}
path = AssistantServiceClient.common_folder_path(**expected)
@@ -2612,7 +6668,7 @@ def test_parse_common_folder_path():
def test_common_organization_path():
- organization = "whelk"
+ organization = "scallop"
expected = "organizations/{organization}".format(
organization=organization,
)
@@ -2622,7 +6678,7 @@ def test_common_organization_path():
def test_parse_common_organization_path():
expected = {
- "organization": "octopus",
+ "organization": "abalone",
}
path = AssistantServiceClient.common_organization_path(**expected)
@@ -2632,7 +6688,7 @@ def test_parse_common_organization_path():
def test_common_project_path():
- project = "oyster"
+ project = "squid"
expected = "projects/{project}".format(
project=project,
)
@@ -2642,7 +6698,7 @@ def test_common_project_path():
def test_parse_common_project_path():
expected = {
- "project": "nudibranch",
+ "project": "clam",
}
path = AssistantServiceClient.common_project_path(**expected)
@@ -2652,8 +6708,8 @@ def test_parse_common_project_path():
def test_common_location_path():
- project = "cuttlefish"
- location = "mussel"
+ project = "whelk"
+ location = "octopus"
expected = "projects/{project}/locations/{location}".format(
project=project,
location=location,
@@ -2664,8 +6720,8 @@ def test_common_location_path():
def test_parse_common_location_path():
expected = {
- "project": "winkle",
- "location": "nautilus",
+ "project": "oyster",
+ "location": "nudibranch",
}
path = AssistantServiceClient.common_location_path(**expected)
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_cmek_config_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_cmek_config_service.py
index 431f5263b784..4942a201aa2f 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_cmek_config_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_cmek_config_service.py
@@ -1082,7 +1082,11 @@ def test_cmek_config_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -4462,7 +4466,11 @@ def test_cmek_config_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -4488,7 +4496,11 @@ def test_cmek_config_service_auth_adc():
CmekConfigServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -4508,7 +4520,11 @@ def test_cmek_config_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -4561,7 +4577,11 @@ def test_cmek_config_service_transport_create_channel(transport_class, grpc_help
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_collection_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_collection_service.py
new file mode 100644
index 000000000000..ba9a52987b30
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_collection_service.py
@@ -0,0 +1,4838 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import asyncio
+import json
+import math
+import os
+from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
+from unittest import mock
+from unittest.mock import AsyncMock
+
+import grpc
+import pytest
+from google.api_core import api_core_version
+from google.protobuf import json_format
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
+
+try:
+ from google.auth.aio import credentials as ga_credentials_async
+
+ HAS_GOOGLE_AUTH_AIO = True
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_AUTH_AIO = False
+
+import google.api_core.operation_async as operation_async # type: ignore
+import google.auth
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.options_pb2 as options_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
+import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.type.expr_pb2 as expr_pb2 # type: ignore
+from google.api_core import (
+ client_options,
+ future,
+ gapic_v1,
+ grpc_helpers,
+ grpc_helpers_async,
+ operation,
+ operations_v1,
+ path_template,
+)
+from google.api_core import exceptions as core_exceptions
+from google.api_core import retry as retries
+from google.auth import credentials as ga_credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.location import locations_pb2
+from google.longrunning import operations_pb2 # type: ignore
+from google.oauth2 import service_account
+
+from google.cloud.discoveryengine_v1.services.collection_service import (
+ CollectionServiceAsyncClient,
+ CollectionServiceClient,
+ transports,
+)
+from google.cloud.discoveryengine_v1.types import collection_service
+
+CRED_INFO_JSON = {
+ "credential_source": "/path/to/file",
+ "credential_type": "service account credentials",
+ "principal": "service-account@example.com",
+}
+CRED_INFO_STRING = json.dumps(CRED_INFO_JSON)
+
+
+@pytest.fixture(autouse=True)
+def disable_mtls_env():
+ with mock.patch.dict(
+ os.environ,
+ {
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false",
+ "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false",
+ },
+ ):
+ yield
+
+
+async def mock_async_gen(data, chunk_size=1):
+ for i in range(0, len(data)): # pragma: NO COVER
+ chunk = data[i : i + chunk_size]
+ yield chunk.encode("utf-8")
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
+# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
+def async_anonymous_credentials():
+ if HAS_GOOGLE_AUTH_AIO:
+ return ga_credentials_async.AnonymousCredentials()
+ return ga_credentials.AnonymousCredentials()
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+# If default endpoint template is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint template so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint_template(client):
+ return (
+ "test.{UNIVERSE_DOMAIN}"
+ if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE)
+ else client._DEFAULT_ENDPOINT_TEMPLATE
+ )
+
+
+@pytest.fixture(autouse=True)
+def set_event_loop():
+ try:
+ asyncio.get_running_loop()
+ yield
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ yield
+ finally:
+ loop.close()
+ asyncio.set_event_loop(None)
+
+
+def test__get_client_cert_source():
+ mock_provided_cert_source = mock.Mock()
+ mock_default_cert_source = mock.Mock()
+
+ assert CollectionServiceClient._get_client_cert_source(None, False) is None
+ assert (
+ CollectionServiceClient._get_client_cert_source(
+ mock_provided_cert_source, False
+ )
+ is None
+ )
+ assert (
+ CollectionServiceClient._get_client_cert_source(mock_provided_cert_source, True)
+ == mock_provided_cert_source
+ )
+
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source", return_value=True
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_default_cert_source,
+ ):
+ assert (
+ CollectionServiceClient._get_client_cert_source(None, True)
+ is mock_default_cert_source
+ )
+ assert (
+ CollectionServiceClient._get_client_cert_source(
+ mock_provided_cert_source, "true"
+ )
+ is mock_provided_cert_source
+ )
+
+
+@pytest.mark.parametrize(
+ "error_code,cred_info_json,show_cred_info",
+ [
+ (401, CRED_INFO_JSON, True),
+ (403, CRED_INFO_JSON, True),
+ (404, CRED_INFO_JSON, True),
+ (500, CRED_INFO_JSON, False),
+ (401, None, False),
+ (403, None, False),
+ (404, None, False),
+ (500, None, False),
+ ],
+)
+def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info):
+ cred = mock.Mock(["get_cred_info"])
+ cred.get_cred_info = mock.Mock(return_value=cred_info_json)
+ client = CollectionServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=["foo"])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ if show_cred_info:
+ assert error.details == ["foo", CRED_INFO_STRING]
+ else:
+ assert error.details == ["foo"]
+
+
+@pytest.mark.parametrize("error_code", [401, 403, 404, 500])
+def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code):
+ cred = mock.Mock([])
+ assert not hasattr(cred, "get_cred_info")
+ client = CollectionServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=[])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ assert error.details == []
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (CollectionServiceClient, "grpc"),
+ (CollectionServiceAsyncClient, "grpc_asyncio"),
+ (CollectionServiceClient, "rest"),
+ ],
+)
+def test_collection_service_client_from_service_account_info(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info, transport=transport_name)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.CollectionServiceGrpcTransport, "grpc"),
+ (transports.CollectionServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ (transports.CollectionServiceRestTransport, "rest"),
+ ],
+)
+def test_collection_service_client_service_account_always_use_jwt(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=False)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (CollectionServiceClient, "grpc"),
+ (CollectionServiceAsyncClient, "grpc_asyncio"),
+ (CollectionServiceClient, "rest"),
+ ],
+)
+def test_collection_service_client_from_service_account_file(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+def test_collection_service_client_get_transport_class():
+ transport = CollectionServiceClient.get_transport_class()
+ available_transports = [
+ transports.CollectionServiceGrpcTransport,
+ transports.CollectionServiceRestTransport,
+ ]
+ assert transport in available_transports
+
+ transport = CollectionServiceClient.get_transport_class("grpc")
+ assert transport == transports.CollectionServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (CollectionServiceClient, transports.CollectionServiceGrpcTransport, "grpc"),
+ (
+ CollectionServiceAsyncClient,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (CollectionServiceClient, transports.CollectionServiceRestTransport, "rest"),
+ ],
+)
+@mock.patch.object(
+ CollectionServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(CollectionServiceClient),
+)
+@mock.patch.object(
+ CollectionServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(CollectionServiceAsyncClient),
+)
+def test_collection_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(CollectionServiceClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(CollectionServiceClient, "get_transport_class") as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name, client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ # Check the case quota_project_id is provided
+ options = client_options.ClientOptions(quota_project_id="octopus")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id="octopus",
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+ # Check the case api_endpoint is provided
+ options = client_options.ClientOptions(
+ api_audience="https://language.googleapis.com"
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience="https://language.googleapis.com",
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (
+ CollectionServiceClient,
+ transports.CollectionServiceGrpcTransport,
+ "grpc",
+ "true",
+ ),
+ (
+ CollectionServiceAsyncClient,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (
+ CollectionServiceClient,
+ transports.CollectionServiceGrpcTransport,
+ "grpc",
+ "false",
+ ),
+ (
+ CollectionServiceAsyncClient,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ (
+ CollectionServiceClient,
+ transports.CollectionServiceRestTransport,
+ "rest",
+ "true",
+ ),
+ (
+ CollectionServiceClient,
+ transports.CollectionServiceRestTransport,
+ "rest",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ CollectionServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(CollectionServiceClient),
+)
+@mock.patch.object(
+ CollectionServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(CollectionServiceAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_collection_service_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [CollectionServiceClient, CollectionServiceAsyncClient]
+)
+@mock.patch.object(
+ CollectionServiceClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(CollectionServiceClient),
+)
+@mock.patch.object(
+ CollectionServiceAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(CollectionServiceAsyncClient),
+)
+def test_collection_service_client_get_mtls_endpoint_and_cert_source(client_class):
+ mock_client_cert_source = mock.Mock()
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source == mock_client_cert_source
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported".
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset.
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None)
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None)
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty).
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "")
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "")
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_client_cert_source,
+ ):
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source()
+ )
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source == mock_client_cert_source
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [CollectionServiceClient, CollectionServiceAsyncClient]
+)
+@mock.patch.object(
+ CollectionServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(CollectionServiceClient),
+)
+@mock.patch.object(
+ CollectionServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(CollectionServiceAsyncClient),
+)
+def test_collection_service_client_client_api_endpoint(client_class):
+ mock_client_cert_source = client_cert_source_callback
+ api_override = "foo.com"
+ default_universe = CollectionServiceClient._DEFAULT_UNIVERSE
+ default_endpoint = CollectionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = CollectionServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true",
+ # use ClientOptions.api_endpoint as the api endpoint regardless.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=api_override
+ )
+ client = client_class(
+ client_options=options,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert client.api_endpoint == api_override
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == default_endpoint
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always",
+ # use the DEFAULT_MTLS_ENDPOINT as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+
+ # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default),
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist,
+ # and ClientOptions.universe_domain="bar.com",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint.
+ options = client_options.ClientOptions()
+ universe_exists = hasattr(options, "universe_domain")
+ if universe_exists:
+ options = client_options.ClientOptions(universe_domain=mock_universe)
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ else:
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == (
+ mock_endpoint if universe_exists else default_endpoint
+ )
+ assert client.universe_domain == (
+ mock_universe if universe_exists else default_universe
+ )
+
+ # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ options = client_options.ClientOptions()
+ if hasattr(options, "universe_domain"):
+ delattr(options, "universe_domain")
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == default_endpoint
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (CollectionServiceClient, transports.CollectionServiceGrpcTransport, "grpc"),
+ (
+ CollectionServiceAsyncClient,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (CollectionServiceClient, transports.CollectionServiceRestTransport, "rest"),
+ ],
+)
+def test_collection_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(
+ scopes=["1", "2"],
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ CollectionServiceClient,
+ transports.CollectionServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ CollectionServiceAsyncClient,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ (
+ CollectionServiceClient,
+ transports.CollectionServiceRestTransport,
+ "rest",
+ None,
+ ),
+ ],
+)
+def test_collection_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+def test_collection_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.collection_service.transports.CollectionServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = CollectionServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ CollectionServiceClient,
+ transports.CollectionServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ CollectionServiceAsyncClient,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ ],
+)
+def test_collection_service_client_create_channel_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # test that the credentials from file are saved and used as the credentials.
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(grpc_helpers, "create_channel") as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ file_creds = ga_credentials.AnonymousCredentials()
+ load_creds.return_value = (file_creds, None)
+ adc.return_value = (creds, None)
+ client = client_class(client_options=options, transport=transport_name)
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=file_creds,
+ credentials_file=None,
+ quota_project_id=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=None,
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ collection_service.DeleteCollectionRequest(),
+ {},
+ ],
+)
+def test_delete_collection(request_type, transport: str = "grpc"):
+ client = CollectionServiceClient(
+ 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_collection), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+ response = client.delete_collection(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = collection_service.DeleteCollectionRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_collection_non_empty_request_with_auto_populated_field():
+ # This test is a coverage failsafe to make sure that UUID4 fields are
+ # automatically populated, according to AIP-4235, with non-empty requests.
+ client = CollectionServiceClient(
+ 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 = collection_service.DeleteCollectionRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_collection), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_collection(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = collection_service.DeleteCollectionRequest(
+ name="name_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_delete_collection_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert client._transport.delete_collection in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_collection] = (
+ mock_rpc
+ )
+ request = {}
+ client.delete_collection(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_collection(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_delete_collection_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
+):
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn:
+ client = CollectionServiceAsyncClient(
+ 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_collection
+ in client._client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.delete_collection
+ ] = mock_rpc
+
+ request = {}
+ await client.delete_collection(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_collection(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ collection_service.DeleteCollectionRequest(),
+ {},
+ ],
+)
+async def test_delete_collection_async(request_type, transport: str = "grpc_asyncio"):
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Everything is optional in proto3 as far as the runtime is concerned,
+ # and we are mocking out the actual API, so just send an empty request.
+ request = request_type
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_collection), "__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_collection(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = collection_service.DeleteCollectionRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_delete_collection_field_headers():
+ client = CollectionServiceClient(
+ 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 = collection_service.DeleteCollectionRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_collection), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.delete_collection(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_delete_collection_field_headers_async():
+ client = CollectionServiceAsyncClient(
+ 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 = collection_service.DeleteCollectionRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_collection), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+ await client.delete_collection(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == request
+
+ # 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_collection_flattened():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_collection), "__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_collection(
+ 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_collection_flattened_error():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_collection(
+ collection_service.DeleteCollectionRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_delete_collection_flattened_async():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_collection), "__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_collection(
+ 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_collection_flattened_error_async():
+ client = CollectionServiceAsyncClient(
+ 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_collection(
+ collection_service.DeleteCollectionRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.GetIamPolicyRequest(),
+ {},
+ ],
+)
+def test_get_iam_policy(request_type, transport: str = "grpc"):
+ client = CollectionServiceClient(
+ 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_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ response = client.get_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+
+def test_get_iam_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 = CollectionServiceClient(
+ 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 = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_iam_policy(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_iam_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 = CollectionServiceClient(
+ 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_iam_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_iam_policy] = mock_rpc
+ request = {}
+ client.get_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_iam_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
+async def test_get_iam_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 = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_iam_policy
+ 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_iam_policy
+ ] = mock_rpc
+
+ request = {}
+ await client.get_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_iam_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",
+ [
+ iam_policy_pb2.GetIamPolicyRequest(),
+ {},
+ ],
+)
+async def test_get_iam_policy_async(request_type, transport: str = "grpc_asyncio"):
+ client = CollectionServiceAsyncClient(
+ 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_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ response = await client.get_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+
+def test_get_iam_policy_field_headers():
+ client = CollectionServiceClient(
+ 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 = iam_policy_pb2.GetIamPolicyRequest()
+
+ request.resource = "resource_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.get_iam_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",
+ "resource=resource_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_iam_policy_field_headers_async():
+ client = CollectionServiceAsyncClient(
+ 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 = iam_policy_pb2.GetIamPolicyRequest()
+
+ request.resource = "resource_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ await client.get_iam_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",
+ "resource=resource_value",
+ ) in kw["metadata"]
+
+
+def test_get_iam_policy_from_dict_foreign():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ response = client.get_iam_policy(
+ request={
+ "resource": "resource_value",
+ "options": options_pb2.GetPolicyOptions(requested_policy_version=2598),
+ }
+ )
+ call.assert_called()
+
+
+def test_get_iam_policy_flattened():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
+
+
+def test_get_iam_policy_flattened_error():
+ client = CollectionServiceClient(
+ 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_iam_policy(
+ iam_policy_pb2.GetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_iam_policy_flattened_async():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_get_iam_policy_flattened_error_async():
+ client = CollectionServiceAsyncClient(
+ 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_iam_policy(
+ iam_policy_pb2.GetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.SetIamPolicyRequest(),
+ {},
+ ],
+)
+def test_set_iam_policy(request_type, transport: str = "grpc"):
+ client = CollectionServiceClient(
+ 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.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ response = client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+
+def test_set_iam_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 = CollectionServiceClient(
+ 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 = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.set_iam_policy(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_set_iam_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 = CollectionServiceClient(
+ 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.set_iam_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.set_iam_policy] = mock_rpc
+ request = {}
+ client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.set_iam_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
+async def test_set_iam_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 = CollectionServiceAsyncClient(
+ 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.set_iam_policy
+ 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.set_iam_policy
+ ] = mock_rpc
+
+ request = {}
+ await client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.set_iam_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",
+ [
+ iam_policy_pb2.SetIamPolicyRequest(),
+ {},
+ ],
+)
+async def test_set_iam_policy_async(request_type, transport: str = "grpc_asyncio"):
+ client = CollectionServiceAsyncClient(
+ 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.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ response = await client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+
+def test_set_iam_policy_field_headers():
+ client = CollectionServiceClient(
+ 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 = iam_policy_pb2.SetIamPolicyRequest()
+
+ request.resource = "resource_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.set_iam_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",
+ "resource=resource_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_set_iam_policy_field_headers_async():
+ client = CollectionServiceAsyncClient(
+ 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 = iam_policy_pb2.SetIamPolicyRequest()
+
+ request.resource = "resource_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ await client.set_iam_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",
+ "resource=resource_value",
+ ) in kw["metadata"]
+
+
+def test_set_iam_policy_from_dict_foreign():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ response = client.set_iam_policy(
+ request={
+ "resource": "resource_value",
+ "policy": policy_pb2.Policy(version=774),
+ "update_mask": field_mask_pb2.FieldMask(paths=["paths_value"]),
+ }
+ )
+ call.assert_called()
+
+
+def test_set_iam_policy_flattened():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.set_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
+
+
+def test_set_iam_policy_flattened_error():
+ client = CollectionServiceClient(
+ 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.set_iam_policy(
+ iam_policy_pb2.SetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_set_iam_policy_flattened_async():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.set_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_set_iam_policy_flattened_error_async():
+ client = CollectionServiceAsyncClient(
+ 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.set_iam_policy(
+ iam_policy_pb2.SetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+def test_delete_collection_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = CollectionServiceClient(
+ 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_collection in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.delete_collection] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.delete_collection(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.delete_collection(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_delete_collection_rest_required_fields(
+ request_type=collection_service.DeleteCollectionRequest,
+):
+ transport_class = transports.CollectionServiceRestTransport
+
+ 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._BaseDeleteCollection,
+ "_BaseDeleteCollection__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 = CollectionServiceClient(
+ 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_collection(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_delete_collection_rest_flattened():
+ client = CollectionServiceClient(
+ 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/collections/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_collection(**mock_args)
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(req.mock_calls) == 1
+ _, args, _ = req.mock_calls[0]
+ assert path_template.validate(
+ "%s/v1/{name=projects/*/locations/*/collections/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_delete_collection_rest_flattened_error(transport: str = "rest"):
+ client = CollectionServiceClient(
+ 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_collection(
+ collection_service.DeleteCollectionRequest(),
+ name="name_value",
+ )
+
+
+def test_get_iam_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 = CollectionServiceClient(
+ 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_iam_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_iam_policy] = mock_rpc
+
+ request = {}
+ client.get_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_iam_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_iam_policy_rest_required_fields(
+ request_type=iam_policy_pb2.GetIamPolicyRequest,
+):
+ transport_class = transports.CollectionServiceRestTransport
+
+ request_init = {}
+ request_init["resource"] = ""
+ request = request_type(**request_init)
+ pb_request = request
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ default_values = getattr(
+ transport_class._BaseGetIamPolicy,
+ "_BaseGetIamPolicy__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["resource"] = "resource_value"
+
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("options",))
+
+ # verify required fields with non-default values are left alone
+ assert "resource" in jsonified_request
+ assert jsonified_request["resource"] == "resource_value"
+
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = policy_pb2.Policy()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.get_iam_policy(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_get_iam_policy_rest_flattened():
+ client = CollectionServiceClient(
+ 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 = policy_pb2.Policy()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ resource="resource_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.get_iam_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/{resource=projects/*/locations/*/collections/*}:getIamPolicy"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_iam_policy_rest_flattened_error(transport: str = "rest"):
+ client = CollectionServiceClient(
+ 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_iam_policy(
+ iam_policy_pb2.GetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+def test_set_iam_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 = CollectionServiceClient(
+ 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.set_iam_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.set_iam_policy] = mock_rpc
+
+ request = {}
+ client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.set_iam_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_set_iam_policy_rest_required_fields(
+ request_type=iam_policy_pb2.SetIamPolicyRequest,
+):
+ transport_class = transports.CollectionServiceRestTransport
+
+ request_init = {}
+ request_init["resource"] = ""
+ request = request_type(**request_init)
+ pb_request = request
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ default_values = getattr(
+ transport_class._BaseSetIamPolicy,
+ "_BaseSetIamPolicy__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["resource"] = "resource_value"
+
+ # verify required fields with non-default values are left alone
+ assert "resource" in jsonified_request
+ assert jsonified_request["resource"] == "resource_value"
+
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = policy_pb2.Policy()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "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.set_iam_policy(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_set_iam_policy_rest_flattened():
+ client = CollectionServiceClient(
+ 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 = policy_pb2.Policy()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ resource="resource_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.set_iam_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/{resource=projects/*/locations/*/collections/*}:setIamPolicy"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_set_iam_policy_rest_flattened_error(transport: str = "rest"):
+ client = CollectionServiceClient(
+ 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.set_iam_policy(
+ iam_policy_pb2.SetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.CollectionServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.CollectionServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = CollectionServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.CollectionServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = CollectionServiceClient(
+ 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 = CollectionServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.CollectionServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = CollectionServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.CollectionServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = CollectionServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.CollectionServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.CollectionServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CollectionServiceGrpcTransport,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ transports.CollectionServiceRestTransport,
+ ],
+)
+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 = CollectionServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = CollectionServiceClient(
+ 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_delete_collection_empty_call_grpc():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_collection), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.delete_collection(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = collection_service.DeleteCollectionRequest()
+ assert args[0] == request_msg
+
+
+# This 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_iam_policy_empty_call_grpc():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.get_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_set_iam_policy_empty_call_grpc():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.set_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = CollectionServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = CollectionServiceAsyncClient(
+ 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_delete_collection_empty_call_grpc_asyncio():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_collection), "__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_collection(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = collection_service.DeleteCollectionRequest()
+ assert args[0] == request_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_iam_policy_empty_call_grpc_asyncio():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ await client.get_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request_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_set_iam_policy_empty_call_grpc_asyncio():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ await client.set_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = CollectionServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_delete_collection_rest_bad_request(
+ request_type=collection_service.DeleteCollectionRequest,
+):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/collections/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_collection(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ collection_service.DeleteCollectionRequest,
+ dict,
+ ],
+)
+def test_delete_collection_rest_call_success(request_type):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/collections/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_collection(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_collection_rest_interceptors(null_interceptor):
+ transport = transports.CollectionServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.CollectionServiceRestInterceptor(),
+ )
+ client = CollectionServiceClient(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.CollectionServiceRestInterceptor, "post_delete_collection"
+ ) as post,
+ mock.patch.object(
+ transports.CollectionServiceRestInterceptor,
+ "post_delete_collection_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.CollectionServiceRestInterceptor, "pre_delete_collection"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = collection_service.DeleteCollectionRequest.pb(
+ collection_service.DeleteCollectionRequest()
+ )
+ 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 = collection_service.DeleteCollectionRequest()
+ 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_collection(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_get_iam_policy_rest_bad_request(
+ request_type=iam_policy_pb2.GetIamPolicyRequest,
+):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/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_iam_policy(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.GetIamPolicyRequest,
+ dict,
+ ],
+)
+def test_get_iam_policy_rest_call_success(request_type):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/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 = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ response = client.get_iam_policy(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_iam_policy_rest_interceptors(null_interceptor):
+ transport = transports.CollectionServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.CollectionServiceRestInterceptor(),
+ )
+ client = CollectionServiceClient(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.CollectionServiceRestInterceptor, "post_get_iam_policy"
+ ) as post,
+ mock.patch.object(
+ transports.CollectionServiceRestInterceptor,
+ "post_get_iam_policy_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.CollectionServiceRestInterceptor, "pre_get_iam_policy"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = iam_policy_pb2.GetIamPolicyRequest()
+ 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(policy_pb2.Policy())
+ req.return_value.content = return_value
+
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = policy_pb2.Policy()
+ post_with_metadata.return_value = policy_pb2.Policy(), metadata
+
+ client.get_iam_policy(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_set_iam_policy_rest_bad_request(
+ request_type=iam_policy_pb2.SetIamPolicyRequest,
+):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/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.set_iam_policy(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.SetIamPolicyRequest,
+ dict,
+ ],
+)
+def test_set_iam_policy_rest_call_success(request_type):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/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 = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ response = client.set_iam_policy(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_set_iam_policy_rest_interceptors(null_interceptor):
+ transport = transports.CollectionServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.CollectionServiceRestInterceptor(),
+ )
+ client = CollectionServiceClient(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.CollectionServiceRestInterceptor, "post_set_iam_policy"
+ ) as post,
+ mock.patch.object(
+ transports.CollectionServiceRestInterceptor,
+ "post_set_iam_policy_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.CollectionServiceRestInterceptor, "pre_set_iam_policy"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = iam_policy_pb2.SetIamPolicyRequest()
+ 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(policy_pb2.Policy())
+ req.return_value.content = return_value
+
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = policy_pb2.Policy()
+ post_with_metadata.return_value = policy_pb2.Policy(), metadata
+
+ client.set_iam_policy(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_cancel_operation_rest_bad_request(
+ request_type=operations_pb2.CancelOperationRequest,
+):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = "{}"
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.cancel_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_get_operation_rest_bad_request(
+ request_type=operations_pb2.GetOperationRequest,
+):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.get_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_list_operations_rest_bad_request(
+ request_type=operations_pb2.ListOperationsRequest,
+):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.list_operations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_initialize_client_w_rest():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_delete_collection_empty_call_rest():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_collection), "__call__"
+ ) as call:
+ client.delete_collection(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = collection_service.DeleteCollectionRequest()
+ assert args[0] == request_msg
+
+
+# This 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_iam_policy_empty_call_rest():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ client.get_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_set_iam_policy_empty_call_rest():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ client.set_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+def test_collection_service_rest_lro_client():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have an api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert isinstance(
+ client.transport,
+ transports.CollectionServiceGrpcTransport,
+ )
+
+
+def test_collection_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
+ transport = transports.CollectionServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_collection_service_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.collection_service.transports.CollectionServiceTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.CollectionServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "delete_collection",
+ "get_iam_policy",
+ "set_iam_policy",
+ "get_operation",
+ "cancel_operation",
+ "list_operations",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ with pytest.raises(NotImplementedError):
+ transport.close()
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+ # Catch all for all remaining methods and properties
+ remainder = [
+ "kind",
+ ]
+ for r in remainder:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, r)()
+
+
+def test_collection_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.collection_service.transports.CollectionServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.CollectionServiceTransport(
+ credentials_file="credentials.json",
+ quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_collection_service_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.collection_service.transports.CollectionServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.CollectionServiceTransport()
+ adc.assert_called_once()
+
+
+def test_collection_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ CollectionServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CollectionServiceGrpcTransport,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_collection_service_transport_auth_adc(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CollectionServiceGrpcTransport,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ transports.CollectionServiceRestTransport,
+ ],
+)
+def test_collection_service_transport_auth_gdch_credentials(transport_class):
+ host = "https://language.com"
+ api_audience_tests = [None, "https://language2.com"]
+ api_audience_expect = [host, "https://language2.com"]
+ for t, e in zip(api_audience_tests, api_audience_expect):
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ gdch_mock = mock.MagicMock()
+ type(gdch_mock).with_gdch_audience = mock.PropertyMock(
+ return_value=gdch_mock
+ )
+ adc.return_value = (gdch_mock, None)
+ transport_class(host=host, api_audience=t)
+ gdch_mock.with_gdch_audience.assert_called_once_with(e)
+
+
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.CollectionServiceGrpcTransport, grpc_helpers),
+ (transports.CollectionServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_collection_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=["1", "2"],
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CollectionServiceGrpcTransport,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_collection_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_collection_service_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.CollectionServiceRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_collection_service_host_no_port(transport_name):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_collection_service_host_with_port(transport_name):
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com:8000"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:8000"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com:8000"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "rest",
+ ],
+)
+def test_collection_service_client_transport_session_collision(transport_name):
+ creds1 = ga_credentials.AnonymousCredentials()
+ creds2 = ga_credentials.AnonymousCredentials()
+ client1 = CollectionServiceClient(
+ credentials=creds1,
+ transport=transport_name,
+ )
+ client2 = CollectionServiceClient(
+ credentials=creds2,
+ transport=transport_name,
+ )
+ session1 = client1.transport.delete_collection._session
+ session2 = client2.transport.delete_collection._session
+ assert session1 != session2
+ session1 = client1.transport.get_iam_policy._session
+ session2 = client2.transport.get_iam_policy._session
+ assert session1 != session2
+ session1 = client1.transport.set_iam_policy._session
+ session2 = client2.transport.set_iam_policy._session
+ assert session1 != session2
+
+
+def test_collection_service_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.CollectionServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_collection_service_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.CollectionServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.filterwarnings("ignore::FutureWarning")
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CollectionServiceGrpcTransport,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_collection_service_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = ga_credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.CollectionServiceGrpcTransport,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_collection_service_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_collection_service_grpc_lro_client():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.OperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_collection_service_grpc_lro_async_client():
+ client = CollectionServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.OperationsAsyncClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_collection_path():
+ project = "squid"
+ location = "clam"
+ collection = "whelk"
+ expected = (
+ "projects/{project}/locations/{location}/collections/{collection}".format(
+ project=project,
+ location=location,
+ collection=collection,
+ )
+ )
+ actual = CollectionServiceClient.collection_path(project, location, collection)
+ assert expected == actual
+
+
+def test_parse_collection_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "collection": "nudibranch",
+ }
+ path = CollectionServiceClient.collection_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = CollectionServiceClient.parse_collection_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "cuttlefish"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = CollectionServiceClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "mussel",
+ }
+ path = CollectionServiceClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = CollectionServiceClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "winkle"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = CollectionServiceClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "nautilus",
+ }
+ path = CollectionServiceClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = CollectionServiceClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "scallop"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = CollectionServiceClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "abalone",
+ }
+ path = CollectionServiceClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = CollectionServiceClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "squid"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = CollectionServiceClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "clam",
+ }
+ path = CollectionServiceClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = CollectionServiceClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "whelk"
+ location = "octopus"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = CollectionServiceClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "oyster",
+ "location": "nudibranch",
+ }
+ path = CollectionServiceClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = CollectionServiceClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.CollectionServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.CollectionServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = CollectionServiceClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+def test_cancel_operation(transport: str = "grpc"):
+ client = CollectionServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
+ client = CollectionServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+def test_cancel_operation_field_headers():
+ client = CollectionServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = None
+
+ client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_field_headers_async():
+ client = CollectionServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_cancel_operation_from_dict():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_from_dict_async():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_cancel_operation_flattened():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_flattened_async():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+def test_get_operation(transport: str = "grpc"):
+ client = CollectionServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+@pytest.mark.asyncio
+async def test_get_operation_async(transport: str = "grpc_asyncio"):
+ client = CollectionServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_get_operation_field_headers():
+ client = CollectionServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_operation_field_headers_async():
+ client = CollectionServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_get_operation_from_dict():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ response = client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_from_dict_async():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_get_operation_flattened():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_flattened_async():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+def test_list_operations(transport: str = "grpc"):
+ client = CollectionServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+ response = client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+@pytest.mark.asyncio
+async def test_list_operations_async(transport: str = "grpc_asyncio"):
+ client = CollectionServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_list_operations_field_headers():
+ client = CollectionServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_operations_field_headers_async():
+ client = CollectionServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+def test_list_operations_from_dict():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ response = client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_from_dict_async():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_list_operations_flattened():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_flattened_async():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+def test_transport_close_grpc():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+@pytest.mark.asyncio
+async def test_transport_close_grpc_asyncio():
+ client = CollectionServiceAsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_transport_close_rest():
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_session")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_client_ctx():
+ transports = [
+ "rest",
+ "grpc",
+ ]
+ for transport in transports:
+ client = CollectionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ # Test client calls underlying transport.
+ with mock.patch.object(type(client.transport), "close") as close:
+ close.assert_not_called()
+ with client:
+ pass
+ close.assert_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class",
+ [
+ (CollectionServiceClient, transports.CollectionServiceGrpcTransport),
+ (
+ CollectionServiceAsyncClient,
+ transports.CollectionServiceGrpcAsyncIOTransport,
+ ),
+ ],
+)
+def test_api_key_credentials(client_class, transport_class):
+ with mock.patch.object(
+ google.auth._default, "get_api_key_credentials", create=True
+ ) as get_api_key_credentials:
+ mock_cred = mock.Mock()
+ get_api_key_credentials.return_value = mock_cred
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=mock_cred,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_completion_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_completion_service.py
index fbc2e01d99c8..1696bd1a7a4b 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_completion_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_completion_service.py
@@ -41,6 +41,7 @@
import google.api_core.operation_async as operation_async # type: ignore
import google.auth
import google.type.date_pb2 as date_pb2 # type: ignore
+import google.type.latlng_pb2 as latlng_pb2 # type: ignore
from google.api_core import (
client_options,
future,
@@ -65,6 +66,7 @@
transports,
)
from google.cloud.discoveryengine_v1.types import (
+ common,
completion,
completion_service,
import_config,
@@ -1087,7 +1089,13 @@ def test_completion_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud_search.query",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -1346,6 +1354,271 @@ async def test_complete_query_field_headers_async():
) in kw["metadata"]
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ completion_service.AdvancedCompleteQueryRequest(),
+ {},
+ ],
+)
+def test_advanced_complete_query(request_type, transport: str = "grpc"):
+ client = CompletionServiceClient(
+ 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.advanced_complete_query), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = completion_service.AdvancedCompleteQueryResponse(
+ tail_match_triggered=True,
+ )
+ response = client.advanced_complete_query(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = completion_service.AdvancedCompleteQueryRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, completion_service.AdvancedCompleteQueryResponse)
+ assert response.tail_match_triggered is True
+
+
+def test_advanced_complete_query_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 = CompletionServiceClient(
+ 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 = completion_service.AdvancedCompleteQueryRequest(
+ completion_config="completion_config_value",
+ query="query_value",
+ query_model="query_model_value",
+ user_pseudo_id="user_pseudo_id_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.advanced_complete_query), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.advanced_complete_query(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = completion_service.AdvancedCompleteQueryRequest(
+ completion_config="completion_config_value",
+ query="query_value",
+ query_model="query_model_value",
+ user_pseudo_id="user_pseudo_id_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_advanced_complete_query_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = CompletionServiceClient(
+ 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.advanced_complete_query
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.advanced_complete_query
+ ] = mock_rpc
+ request = {}
+ client.advanced_complete_query(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.advanced_complete_query(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_advanced_complete_query_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 = CompletionServiceAsyncClient(
+ 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.advanced_complete_query
+ 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.advanced_complete_query
+ ] = mock_rpc
+
+ request = {}
+ await client.advanced_complete_query(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.advanced_complete_query(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",
+ [
+ completion_service.AdvancedCompleteQueryRequest(),
+ {},
+ ],
+)
+async def test_advanced_complete_query_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = CompletionServiceAsyncClient(
+ 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.advanced_complete_query), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ completion_service.AdvancedCompleteQueryResponse(
+ tail_match_triggered=True,
+ )
+ )
+ response = await client.advanced_complete_query(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = completion_service.AdvancedCompleteQueryRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, completion_service.AdvancedCompleteQueryResponse)
+ assert response.tail_match_triggered is True
+
+
+def test_advanced_complete_query_field_headers():
+ client = CompletionServiceClient(
+ 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 = completion_service.AdvancedCompleteQueryRequest()
+
+ request.completion_config = "completion_config_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.advanced_complete_query), "__call__"
+ ) as call:
+ call.return_value = completion_service.AdvancedCompleteQueryResponse()
+ client.advanced_complete_query(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",
+ "completion_config=completion_config_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_advanced_complete_query_field_headers_async():
+ client = CompletionServiceAsyncClient(
+ 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 = completion_service.AdvancedCompleteQueryRequest()
+
+ request.completion_config = "completion_config_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.advanced_complete_query), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ completion_service.AdvancedCompleteQueryResponse()
+ )
+ await client.advanced_complete_query(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",
+ "completion_config=completion_config_value",
+ ) in kw["metadata"]
+
+
@pytest.mark.parametrize(
"request_type",
[
@@ -2440,7 +2713,146 @@ def test_complete_query_rest_required_fields(
transport_class = transports.CompletionServiceRestTransport
request_init = {}
- request_init["data_store"] = ""
+ request_init["data_store"] = ""
+ request_init["query"] = ""
+ request = 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 "query" not in jsonified_request
+
+ default_values = getattr(
+ transport_class._BaseCompleteQuery,
+ "_BaseCompleteQuery__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 "query" in jsonified_request
+ assert jsonified_request["query"] == request_init["query"]
+
+ jsonified_request["dataStore"] = "data_store_value"
+ jsonified_request["query"] = "query_value"
+
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(
+ (
+ "includeTailSuggestions",
+ "query",
+ "queryModel",
+ "userPseudoId",
+ )
+ )
+
+ # verify required fields with non-default values are left alone
+ assert "dataStore" in jsonified_request
+ assert jsonified_request["dataStore"] == "data_store_value"
+ assert "query" in jsonified_request
+ assert jsonified_request["query"] == "query_value"
+
+ client = CompletionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = completion_service.CompleteQueryResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = completion_service.CompleteQueryResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.complete_query(request)
+
+ expected_params = [
+ (
+ "query",
+ "",
+ ),
+ ("$alt", "json;enum-encoding=int"),
+ ]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_advanced_complete_query_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = CompletionServiceClient(
+ 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.advanced_complete_query
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.advanced_complete_query
+ ] = mock_rpc
+
+ request = {}
+ client.advanced_complete_query(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.advanced_complete_query(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_advanced_complete_query_rest_required_fields(
+ request_type=completion_service.AdvancedCompleteQueryRequest,
+):
+ transport_class = transports.CompletionServiceRestTransport
+
+ request_init = {}
+ request_init["completion_config"] = ""
request_init["query"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
@@ -2449,11 +2861,10 @@ def test_complete_query_rest_required_fields(
)
# verify fields with default values are dropped
- assert "query" not in jsonified_request
default_values = getattr(
- transport_class._BaseCompleteQuery,
- "_BaseCompleteQuery__REQUIRED_FIELDS_DEFAULT_VALUES",
+ transport_class._BaseAdvancedCompleteQuery,
+ "_BaseAdvancedCompleteQuery__REQUIRED_FIELDS_DEFAULT_VALUES",
{},
)
unset_fields = {
@@ -2462,25 +2873,13 @@ def test_complete_query_rest_required_fields(
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
- assert "query" in jsonified_request
- assert jsonified_request["query"] == request_init["query"]
- jsonified_request["dataStore"] = "data_store_value"
+ jsonified_request["completionConfig"] = "completion_config_value"
jsonified_request["query"] = "query_value"
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(
- (
- "includeTailSuggestions",
- "query",
- "queryModel",
- "userPseudoId",
- )
- )
-
# verify required fields with non-default values are left alone
- assert "dataStore" in jsonified_request
- assert jsonified_request["dataStore"] == "data_store_value"
+ assert "completionConfig" in jsonified_request
+ assert jsonified_request["completionConfig"] == "completion_config_value"
assert "query" in jsonified_request
assert jsonified_request["query"] == "query_value"
@@ -2491,7 +2890,7 @@ def test_complete_query_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = completion_service.CompleteQueryResponse()
+ return_value = completion_service.AdvancedCompleteQueryResponse()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -2503,31 +2902,28 @@ def test_complete_query_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 = completion_service.CompleteQueryResponse.pb(return_value)
+ return_value = completion_service.AdvancedCompleteQueryResponse.pb(
+ return_value
+ )
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_return_value.encode("UTF-8")
req.return_value = response_value
req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
- response = client.complete_query(request)
+ response = client.advanced_complete_query(request)
- expected_params = [
- (
- "query",
- "",
- ),
- ("$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)
@@ -3130,6 +3526,28 @@ def test_complete_query_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_advanced_complete_query_empty_call_grpc():
+ client = CompletionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.advanced_complete_query), "__call__"
+ ) as call:
+ call.return_value = completion_service.AdvancedCompleteQueryResponse()
+ client.advanced_complete_query(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = completion_service.AdvancedCompleteQueryRequest()
+ assert args[0] == request_msg
+
+
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
def test_import_suggestion_deny_list_entries_empty_call_grpc():
@@ -3258,6 +3676,34 @@ async def test_complete_query_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_advanced_complete_query_empty_call_grpc_asyncio():
+ client = CompletionServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.advanced_complete_query), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ completion_service.AdvancedCompleteQueryResponse(
+ tail_match_triggered=True,
+ )
+ )
+ await client.advanced_complete_query(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = completion_service.AdvancedCompleteQueryRequest()
+ assert args[0] == request_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
@@ -3509,6 +3955,146 @@ def test_complete_query_rest_interceptors(null_interceptor):
post_with_metadata.assert_called_once()
+def test_advanced_complete_query_rest_bad_request(
+ request_type=completion_service.AdvancedCompleteQueryRequest,
+):
+ client = CompletionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "completion_config": "projects/sample1/locations/sample2/dataStores/sample3/completionConfig"
+ }
+ 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.advanced_complete_query(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ completion_service.AdvancedCompleteQueryRequest,
+ dict,
+ ],
+)
+def test_advanced_complete_query_rest_call_success(request_type):
+ client = CompletionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "completion_config": "projects/sample1/locations/sample2/dataStores/sample3/completionConfig"
+ }
+ 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 = completion_service.AdvancedCompleteQueryResponse(
+ tail_match_triggered=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 = completion_service.AdvancedCompleteQueryResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ response = client.advanced_complete_query(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, completion_service.AdvancedCompleteQueryResponse)
+ assert response.tail_match_triggered is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_advanced_complete_query_rest_interceptors(null_interceptor):
+ transport = transports.CompletionServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.CompletionServiceRestInterceptor(),
+ )
+ client = CompletionServiceClient(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.CompletionServiceRestInterceptor, "post_advanced_complete_query"
+ ) as post,
+ mock.patch.object(
+ transports.CompletionServiceRestInterceptor,
+ "post_advanced_complete_query_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.CompletionServiceRestInterceptor, "pre_advanced_complete_query"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = completion_service.AdvancedCompleteQueryRequest.pb(
+ completion_service.AdvancedCompleteQueryRequest()
+ )
+ 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 = completion_service.AdvancedCompleteQueryResponse.to_json(
+ completion_service.AdvancedCompleteQueryResponse()
+ )
+ req.return_value.content = return_value
+
+ request = completion_service.AdvancedCompleteQueryRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = completion_service.AdvancedCompleteQueryResponse()
+ post_with_metadata.return_value = (
+ completion_service.AdvancedCompleteQueryResponse(),
+ metadata,
+ )
+
+ client.advanced_complete_query(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
def test_import_suggestion_deny_list_entries_rest_bad_request(
request_type=import_config.ImportSuggestionDenyListEntriesRequest,
):
@@ -4250,6 +4836,27 @@ def test_complete_query_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_advanced_complete_query_empty_call_rest():
+ client = CompletionServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.advanced_complete_query), "__call__"
+ ) as call:
+ client.advanced_complete_query(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = completion_service.AdvancedCompleteQueryRequest()
+ assert args[0] == request_msg
+
+
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
def test_import_suggestion_deny_list_entries_empty_call_rest():
@@ -4385,6 +4992,7 @@ def test_completion_service_base_transport():
# raise NotImplementedError.
methods = (
"complete_query",
+ "advanced_complete_query",
"import_suggestion_deny_list_entries",
"purge_suggestion_deny_list_entries",
"import_completion_suggestions",
@@ -4433,7 +5041,13 @@ def test_completion_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud_search.query",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -4459,7 +5073,13 @@ def test_completion_service_auth_adc():
CompletionServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud_search.query",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -4479,7 +5099,13 @@ def test_completion_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud_search.query",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -4532,7 +5158,13 @@ def test_completion_service_transport_create_channel(transport_class, grpc_helpe
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/cloud_search.query",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -4665,6 +5297,9 @@ def test_completion_service_client_transport_session_collision(transport_name):
session1 = client1.transport.complete_query._session
session2 = client2.transport.complete_query._session
assert session1 != session2
+ session1 = client1.transport.advanced_complete_query._session
+ session2 = client2.transport.advanced_complete_query._session
+ assert session1 != session2
session1 = client1.transport.import_suggestion_deny_list_entries._session
session2 = client2.transport.import_suggestion_deny_list_entries._session
assert session1 != session2
@@ -4840,25 +5475,53 @@ def test_completion_service_grpc_lro_async_client():
assert transport.operations_client is transport.operations_client
-def test_data_store_path():
+def test_completion_config_path():
project = "squid"
location = "clam"
data_store = "whelk"
- expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(
+ expected = "projects/{project}/locations/{location}/dataStores/{data_store}/completionConfig".format(
project=project,
location=location,
data_store=data_store,
)
- actual = CompletionServiceClient.data_store_path(project, location, data_store)
+ actual = CompletionServiceClient.completion_config_path(
+ project, location, data_store
+ )
assert expected == actual
-def test_parse_data_store_path():
+def test_parse_completion_config_path():
expected = {
"project": "octopus",
"location": "oyster",
"data_store": "nudibranch",
}
+ path = CompletionServiceClient.completion_config_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = CompletionServiceClient.parse_completion_config_path(path)
+ assert expected == actual
+
+
+def test_data_store_path():
+ project = "cuttlefish"
+ location = "mussel"
+ data_store = "winkle"
+ expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ )
+ actual = CompletionServiceClient.data_store_path(project, location, data_store)
+ assert expected == actual
+
+
+def test_parse_data_store_path():
+ expected = {
+ "project": "nautilus",
+ "location": "scallop",
+ "data_store": "abalone",
+ }
path = CompletionServiceClient.data_store_path(**expected)
# Check that the path construction is reversible.
@@ -4866,8 +5529,42 @@ def test_parse_data_store_path():
assert expected == actual
+def test_document_path():
+ project = "squid"
+ location = "clam"
+ data_store = "whelk"
+ branch = "octopus"
+ document = "oyster"
+ expected = "projects/{project}/locations/{location}/dataStores/{data_store}/branches/{branch}/documents/{document}".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ branch=branch,
+ document=document,
+ )
+ actual = CompletionServiceClient.document_path(
+ project, location, data_store, branch, document
+ )
+ assert expected == actual
+
+
+def test_parse_document_path():
+ expected = {
+ "project": "nudibranch",
+ "location": "cuttlefish",
+ "data_store": "mussel",
+ "branch": "winkle",
+ "document": "nautilus",
+ }
+ path = CompletionServiceClient.document_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = CompletionServiceClient.parse_document_path(path)
+ assert expected == actual
+
+
def test_common_billing_account_path():
- billing_account = "cuttlefish"
+ billing_account = "scallop"
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -4877,7 +5574,7 @@ def test_common_billing_account_path():
def test_parse_common_billing_account_path():
expected = {
- "billing_account": "mussel",
+ "billing_account": "abalone",
}
path = CompletionServiceClient.common_billing_account_path(**expected)
@@ -4887,7 +5584,7 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
- folder = "winkle"
+ folder = "squid"
expected = "folders/{folder}".format(
folder=folder,
)
@@ -4897,7 +5594,7 @@ def test_common_folder_path():
def test_parse_common_folder_path():
expected = {
- "folder": "nautilus",
+ "folder": "clam",
}
path = CompletionServiceClient.common_folder_path(**expected)
@@ -4907,7 +5604,7 @@ def test_parse_common_folder_path():
def test_common_organization_path():
- organization = "scallop"
+ organization = "whelk"
expected = "organizations/{organization}".format(
organization=organization,
)
@@ -4917,7 +5614,7 @@ def test_common_organization_path():
def test_parse_common_organization_path():
expected = {
- "organization": "abalone",
+ "organization": "octopus",
}
path = CompletionServiceClient.common_organization_path(**expected)
@@ -4927,7 +5624,7 @@ def test_parse_common_organization_path():
def test_common_project_path():
- project = "squid"
+ project = "oyster"
expected = "projects/{project}".format(
project=project,
)
@@ -4937,7 +5634,7 @@ def test_common_project_path():
def test_parse_common_project_path():
expected = {
- "project": "clam",
+ "project": "nudibranch",
}
path = CompletionServiceClient.common_project_path(**expected)
@@ -4947,8 +5644,8 @@ def test_parse_common_project_path():
def test_common_location_path():
- project = "whelk"
- location = "octopus"
+ project = "cuttlefish"
+ location = "mussel"
expected = "projects/{project}/locations/{location}".format(
project=project,
location=location,
@@ -4959,8 +5656,8 @@ def test_common_location_path():
def test_parse_common_location_path():
expected = {
- "project": "oyster",
- "location": "nudibranch",
+ "project": "winkle",
+ "location": "nautilus",
}
path = CompletionServiceClient.common_location_path(**expected)
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_control_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_control_service.py
index 91ddf222f852..1a3c87ce7d69 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_control_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_control_service.py
@@ -1050,7 +1050,11 @@ def test_control_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -5567,7 +5571,11 @@ def test_control_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5593,7 +5601,11 @@ def test_control_service_auth_adc():
ControlServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -5613,7 +5625,11 @@ def test_control_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5666,7 +5682,11 @@ def test_control_service_transport_create_channel(transport_class, grpc_helpers)
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py
index 4f9fbd1a2832..2ab281e693ec 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_conversational_search_service.py
@@ -39,9 +39,12 @@
HAS_GOOGLE_AUTH_AIO = False
import google.auth
+import google.protobuf.any_pb2 as any_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.rpc.status_pb2 as status_pb2 # type: ignore
+import google.type.date_pb2 as date_pb2 # type: ignore
from google.api_core import (
client_options,
gapic_v1,
@@ -68,6 +71,7 @@
assist_answer,
conversation,
conversational_search_service,
+ grounded_generation_service,
safety,
search_service,
session,
@@ -1121,7 +1125,11 @@ def test_conversational_search_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -4297,6 +4305,7 @@ def test_create_session(request_type, transport: str = "grpc"):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
response = client.create_session(request)
@@ -4314,6 +4323,10 @@ def test_create_session(request_type, transport: str = "grpc"):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_create_session_non_empty_request_with_auto_populated_field():
@@ -4329,6 +4342,7 @@ def test_create_session_non_empty_request_with_auto_populated_field():
# if they meet the requirements of AIP 4235.
request = conversational_search_service.CreateSessionRequest(
parent="parent_value",
+ session_id="session_id_value",
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -4341,6 +4355,7 @@ def test_create_session_non_empty_request_with_auto_populated_field():
_, args, _ = call.mock_calls[0]
request_msg = conversational_search_service.CreateSessionRequest(
parent="parent_value",
+ session_id="session_id_value",
)
assert args[0] == request_msg
@@ -4451,6 +4466,7 @@ async def test_create_session_async(request_type, transport: str = "grpc_asyncio
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
response = await client.create_session(request)
@@ -4469,6 +4485,10 @@ async def test_create_session_async(request_type, transport: str = "grpc_asyncio
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_create_session_field_headers():
@@ -4959,6 +4979,7 @@ def test_update_session(request_type, transport: str = "grpc"):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
response = client.update_session(request)
@@ -4976,6 +4997,10 @@ def test_update_session(request_type, transport: str = "grpc"):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_update_session_non_empty_request_with_auto_populated_field():
@@ -5109,6 +5134,7 @@ async def test_update_session_async(request_type, transport: str = "grpc_asyncio
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
response = await client.update_session(request)
@@ -5127,6 +5153,10 @@ async def test_update_session_async(request_type, transport: str = "grpc_asyncio
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_update_session_field_headers():
@@ -5305,6 +5335,7 @@ def test_get_session(request_type, transport: str = "grpc"):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
response = client.get_session(request)
@@ -5322,6 +5353,10 @@ def test_get_session(request_type, transport: str = "grpc"):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_get_session_non_empty_request_with_auto_populated_field():
@@ -5459,6 +5494,7 @@ async def test_get_session_async(request_type, transport: str = "grpc_asyncio"):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
response = await client.get_session(request)
@@ -5477,6 +5513,10 @@ async def test_get_session_async(request_type, transport: str = "grpc_asyncio"):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_get_session_field_headers():
@@ -7756,6 +7796,9 @@ def test_create_session_rest_required_fields(
jsonified_request["parent"] = "parent_value"
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("sessionId",))
+
# verify required fields with non-default values are left alone
assert "parent" in jsonified_request
assert jsonified_request["parent"] == "parent_value"
@@ -9317,6 +9360,7 @@ async def test_create_session_empty_call_grpc_asyncio():
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
await client.create_session(request=None)
@@ -9370,6 +9414,7 @@ async def test_update_session_empty_call_grpc_asyncio():
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
await client.update_session(request=None)
@@ -9401,6 +9446,7 @@ async def test_get_session_empty_call_grpc_asyncio():
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
await client.get_session(request=None)
@@ -11127,6 +11173,7 @@ def test_create_session_rest_call_success(request_type):
"detailed_assist_answer": {
"name": "name_value",
"state": 1,
+ "connector_display_names": {},
"replies": [
{
"grounded_content": {
@@ -11140,16 +11187,26 @@ def test_create_session_rest_call_success(request_type):
"text": "text_value",
}
],
+ "visual_segments": [
+ {
+ "reference_indices": [1774, 1775],
+ "content_id": "content_id_value",
+ }
+ ],
"references": [
{
"content": "content_value",
+ "code_snippet": "code_snippet_value",
"document_metadata": {
+ "language": 1,
"document": "document_value",
"uri": "uri_value",
"title": "title_value",
"page_identifier": "page_identifier_value",
"domain": "domain_value",
+ "mime_type": "mime_type_value",
},
+ "chunk_metadata": {},
}
],
},
@@ -11171,18 +11228,64 @@ def test_create_session_rest_call_success(request_type):
"role": "role_value",
"thought": True,
},
- }
+ "citation_metadata": {
+ "citations": [
+ {
+ "start_index": 1189,
+ "end_index": 942,
+ "uri": "uri_value",
+ "title": "title_value",
+ "license_": "license__value",
+ "publication_date": {
+ "year": 433,
+ "month": 550,
+ "day": 318,
+ },
+ }
+ ]
+ },
+ },
+ "create_time": {},
}
],
"assist_skipped_reasons": [1],
+ "customer_policy_enforcement_result": {
+ "verdict": 1,
+ "policy_results": [
+ {
+ "banned_phrase_enforcement_result": {
+ "banned_phrases": [
+ "banned_phrases_value1",
+ "banned_phrases_value2",
+ ]
+ },
+ "model_armor_enforcement_result": {
+ "model_armor_violation": "model_armor_violation_value",
+ "error": {
+ "code": 411,
+ "message": "message_value",
+ "details": [
+ {
+ "type_url": "type.googleapis.com/google.protobuf.Duration",
+ "value": b"\x08\x0c\x10\xdb\x07",
+ }
+ ],
+ },
+ },
+ }
+ ],
+ "violation_source": 1,
+ },
},
"query_config": {},
+ "live": True,
}
],
"labels": ["labels_value1", "labels_value2"],
"start_time": {},
"end_time": {},
"is_pinned": True,
+ "pending_async_assist_operation_id": "pending_async_assist_operation_id_value",
}
# The version of a generated dependency at test runtime may differ from the version used during generation.
# Delete any fields which are not present in the current runtime dependency
@@ -11265,6 +11368,7 @@ def get_message_fields(field):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
# Wrap the value into a proper Response obj
@@ -11287,6 +11391,10 @@ def get_message_fields(field):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -11640,6 +11748,7 @@ def test_update_session_rest_call_success(request_type):
"detailed_assist_answer": {
"name": "name_value",
"state": 1,
+ "connector_display_names": {},
"replies": [
{
"grounded_content": {
@@ -11653,16 +11762,26 @@ def test_update_session_rest_call_success(request_type):
"text": "text_value",
}
],
+ "visual_segments": [
+ {
+ "reference_indices": [1774, 1775],
+ "content_id": "content_id_value",
+ }
+ ],
"references": [
{
"content": "content_value",
+ "code_snippet": "code_snippet_value",
"document_metadata": {
+ "language": 1,
"document": "document_value",
"uri": "uri_value",
"title": "title_value",
"page_identifier": "page_identifier_value",
"domain": "domain_value",
+ "mime_type": "mime_type_value",
},
+ "chunk_metadata": {},
}
],
},
@@ -11684,18 +11803,64 @@ def test_update_session_rest_call_success(request_type):
"role": "role_value",
"thought": True,
},
- }
+ "citation_metadata": {
+ "citations": [
+ {
+ "start_index": 1189,
+ "end_index": 942,
+ "uri": "uri_value",
+ "title": "title_value",
+ "license_": "license__value",
+ "publication_date": {
+ "year": 433,
+ "month": 550,
+ "day": 318,
+ },
+ }
+ ]
+ },
+ },
+ "create_time": {},
}
],
"assist_skipped_reasons": [1],
+ "customer_policy_enforcement_result": {
+ "verdict": 1,
+ "policy_results": [
+ {
+ "banned_phrase_enforcement_result": {
+ "banned_phrases": [
+ "banned_phrases_value1",
+ "banned_phrases_value2",
+ ]
+ },
+ "model_armor_enforcement_result": {
+ "model_armor_violation": "model_armor_violation_value",
+ "error": {
+ "code": 411,
+ "message": "message_value",
+ "details": [
+ {
+ "type_url": "type.googleapis.com/google.protobuf.Duration",
+ "value": b"\x08\x0c\x10\xdb\x07",
+ }
+ ],
+ },
+ },
+ }
+ ],
+ "violation_source": 1,
+ },
},
"query_config": {},
+ "live": True,
}
],
"labels": ["labels_value1", "labels_value2"],
"start_time": {},
"end_time": {},
"is_pinned": True,
+ "pending_async_assist_operation_id": "pending_async_assist_operation_id_value",
}
# The version of a generated dependency at test runtime may differ from the version used during generation.
# Delete any fields which are not present in the current runtime dependency
@@ -11778,6 +11943,7 @@ def get_message_fields(field):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
# Wrap the value into a proper Response obj
@@ -11800,6 +11966,10 @@ def get_message_fields(field):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -11923,6 +12093,7 @@ def test_get_session_rest_call_success(request_type):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
# Wrap the value into a proper Response obj
@@ -11945,6 +12116,10 @@ def test_get_session_rest_call_success(request_type):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -12708,7 +12883,11 @@ def test_conversational_search_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -12734,7 +12913,11 @@ def test_conversational_search_service_auth_adc():
ConversationalSearchServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -12754,7 +12937,11 @@ def test_conversational_search_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -12812,7 +12999,11 @@ def test_conversational_search_service_transport_create_channel(
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_data_connector_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_data_connector_service.py
new file mode 100644
index 000000000000..23e19f577f1a
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_data_connector_service.py
@@ -0,0 +1,5864 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import asyncio
+import json
+import math
+import os
+from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
+from unittest import mock
+from unittest.mock import AsyncMock
+
+import grpc
+import pytest
+from google.api_core import api_core_version
+from google.protobuf import json_format
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
+
+try:
+ from google.auth.aio import credentials as ga_credentials_async
+
+ HAS_GOOGLE_AUTH_AIO = True
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_AUTH_AIO = False
+
+import google.api_core.operation_async as operation_async # type: ignore
+import google.auth
+import google.protobuf.any_pb2 as any_pb2 # type: ignore
+import google.protobuf.duration_pb2 as duration_pb2 # type: ignore
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.protobuf.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 google.type.datetime_pb2 as datetime_pb2 # type: ignore
+from google.api_core import (
+ client_options,
+ future,
+ gapic_v1,
+ grpc_helpers,
+ grpc_helpers_async,
+ operation,
+ operations_v1,
+ path_template,
+)
+from google.api_core import exceptions as core_exceptions
+from google.api_core import retry as retries
+from google.auth import credentials as ga_credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.location import locations_pb2
+from google.longrunning import operations_pb2 # type: ignore
+from google.oauth2 import service_account
+
+from google.cloud.discoveryengine_v1.services.data_connector_service import (
+ DataConnectorServiceAsyncClient,
+ DataConnectorServiceClient,
+ transports,
+)
+from google.cloud.discoveryengine_v1.types import (
+ common,
+ data_connector,
+ data_connector_service,
+ schema,
+)
+from google.cloud.discoveryengine_v1.types import data_connector as gcd_data_connector
+
+CRED_INFO_JSON = {
+ "credential_source": "/path/to/file",
+ "credential_type": "service account credentials",
+ "principal": "service-account@example.com",
+}
+CRED_INFO_STRING = json.dumps(CRED_INFO_JSON)
+
+
+@pytest.fixture(autouse=True)
+def disable_mtls_env():
+ with mock.patch.dict(
+ os.environ,
+ {
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false",
+ "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false",
+ },
+ ):
+ yield
+
+
+async def mock_async_gen(data, chunk_size=1):
+ for i in range(0, len(data)): # pragma: NO COVER
+ chunk = data[i : i + chunk_size]
+ yield chunk.encode("utf-8")
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
+# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
+def async_anonymous_credentials():
+ if HAS_GOOGLE_AUTH_AIO:
+ return ga_credentials_async.AnonymousCredentials()
+ return ga_credentials.AnonymousCredentials()
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+# If default endpoint template is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint template so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint_template(client):
+ return (
+ "test.{UNIVERSE_DOMAIN}"
+ if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE)
+ else client._DEFAULT_ENDPOINT_TEMPLATE
+ )
+
+
+@pytest.fixture(autouse=True)
+def set_event_loop():
+ try:
+ asyncio.get_running_loop()
+ yield
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ yield
+ finally:
+ loop.close()
+ asyncio.set_event_loop(None)
+
+
+def test__get_client_cert_source():
+ mock_provided_cert_source = mock.Mock()
+ mock_default_cert_source = mock.Mock()
+
+ assert DataConnectorServiceClient._get_client_cert_source(None, False) is None
+ assert (
+ DataConnectorServiceClient._get_client_cert_source(
+ mock_provided_cert_source, False
+ )
+ is None
+ )
+ assert (
+ DataConnectorServiceClient._get_client_cert_source(
+ mock_provided_cert_source, True
+ )
+ == mock_provided_cert_source
+ )
+
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source", return_value=True
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_default_cert_source,
+ ):
+ assert (
+ DataConnectorServiceClient._get_client_cert_source(None, True)
+ is mock_default_cert_source
+ )
+ assert (
+ DataConnectorServiceClient._get_client_cert_source(
+ mock_provided_cert_source, "true"
+ )
+ is mock_provided_cert_source
+ )
+
+
+@pytest.mark.parametrize(
+ "error_code,cred_info_json,show_cred_info",
+ [
+ (401, CRED_INFO_JSON, True),
+ (403, CRED_INFO_JSON, True),
+ (404, CRED_INFO_JSON, True),
+ (500, CRED_INFO_JSON, False),
+ (401, None, False),
+ (403, None, False),
+ (404, None, False),
+ (500, None, False),
+ ],
+)
+def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info):
+ cred = mock.Mock(["get_cred_info"])
+ cred.get_cred_info = mock.Mock(return_value=cred_info_json)
+ client = DataConnectorServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=["foo"])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ if show_cred_info:
+ assert error.details == ["foo", CRED_INFO_STRING]
+ else:
+ assert error.details == ["foo"]
+
+
+@pytest.mark.parametrize("error_code", [401, 403, 404, 500])
+def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code):
+ cred = mock.Mock([])
+ assert not hasattr(cred, "get_cred_info")
+ client = DataConnectorServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=[])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ assert error.details == []
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (DataConnectorServiceClient, "grpc"),
+ (DataConnectorServiceAsyncClient, "grpc_asyncio"),
+ (DataConnectorServiceClient, "rest"),
+ ],
+)
+def test_data_connector_service_client_from_service_account_info(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info, transport=transport_name)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.DataConnectorServiceGrpcTransport, "grpc"),
+ (transports.DataConnectorServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ (transports.DataConnectorServiceRestTransport, "rest"),
+ ],
+)
+def test_data_connector_service_client_service_account_always_use_jwt(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=False)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (DataConnectorServiceClient, "grpc"),
+ (DataConnectorServiceAsyncClient, "grpc_asyncio"),
+ (DataConnectorServiceClient, "rest"),
+ ],
+)
+def test_data_connector_service_client_from_service_account_file(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+def test_data_connector_service_client_get_transport_class():
+ transport = DataConnectorServiceClient.get_transport_class()
+ available_transports = [
+ transports.DataConnectorServiceGrpcTransport,
+ transports.DataConnectorServiceRestTransport,
+ ]
+ assert transport in available_transports
+
+ transport = DataConnectorServiceClient.get_transport_class("grpc")
+ assert transport == transports.DataConnectorServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ DataConnectorServiceAsyncClient,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceRestTransport,
+ "rest",
+ ),
+ ],
+)
+@mock.patch.object(
+ DataConnectorServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(DataConnectorServiceClient),
+)
+@mock.patch.object(
+ DataConnectorServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(DataConnectorServiceAsyncClient),
+)
+def test_data_connector_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(DataConnectorServiceClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(DataConnectorServiceClient, "get_transport_class") as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name, client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ # Check the case quota_project_id is provided
+ options = client_options.ClientOptions(quota_project_id="octopus")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id="octopus",
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+ # Check the case api_endpoint is provided
+ options = client_options.ClientOptions(
+ api_audience="https://language.googleapis.com"
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience="https://language.googleapis.com",
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceGrpcTransport,
+ "grpc",
+ "true",
+ ),
+ (
+ DataConnectorServiceAsyncClient,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceGrpcTransport,
+ "grpc",
+ "false",
+ ),
+ (
+ DataConnectorServiceAsyncClient,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceRestTransport,
+ "rest",
+ "true",
+ ),
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceRestTransport,
+ "rest",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ DataConnectorServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(DataConnectorServiceClient),
+)
+@mock.patch.object(
+ DataConnectorServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(DataConnectorServiceAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_data_connector_service_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [DataConnectorServiceClient, DataConnectorServiceAsyncClient]
+)
+@mock.patch.object(
+ DataConnectorServiceClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(DataConnectorServiceClient),
+)
+@mock.patch.object(
+ DataConnectorServiceAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(DataConnectorServiceAsyncClient),
+)
+def test_data_connector_service_client_get_mtls_endpoint_and_cert_source(client_class):
+ mock_client_cert_source = mock.Mock()
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source == mock_client_cert_source
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported".
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset.
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None)
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None)
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty).
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "")
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "")
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_client_cert_source,
+ ):
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source()
+ )
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source == mock_client_cert_source
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [DataConnectorServiceClient, DataConnectorServiceAsyncClient]
+)
+@mock.patch.object(
+ DataConnectorServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(DataConnectorServiceClient),
+)
+@mock.patch.object(
+ DataConnectorServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(DataConnectorServiceAsyncClient),
+)
+def test_data_connector_service_client_client_api_endpoint(client_class):
+ mock_client_cert_source = client_cert_source_callback
+ api_override = "foo.com"
+ default_universe = DataConnectorServiceClient._DEFAULT_UNIVERSE
+ default_endpoint = DataConnectorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = DataConnectorServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true",
+ # use ClientOptions.api_endpoint as the api endpoint regardless.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=api_override
+ )
+ client = client_class(
+ client_options=options,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert client.api_endpoint == api_override
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == default_endpoint
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always",
+ # use the DEFAULT_MTLS_ENDPOINT as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+
+ # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default),
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist,
+ # and ClientOptions.universe_domain="bar.com",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint.
+ options = client_options.ClientOptions()
+ universe_exists = hasattr(options, "universe_domain")
+ if universe_exists:
+ options = client_options.ClientOptions(universe_domain=mock_universe)
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ else:
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == (
+ mock_endpoint if universe_exists else default_endpoint
+ )
+ assert client.universe_domain == (
+ mock_universe if universe_exists else default_universe
+ )
+
+ # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ options = client_options.ClientOptions()
+ if hasattr(options, "universe_domain"):
+ delattr(options, "universe_domain")
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == default_endpoint
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ DataConnectorServiceAsyncClient,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceRestTransport,
+ "rest",
+ ),
+ ],
+)
+def test_data_connector_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(
+ scopes=["1", "2"],
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ DataConnectorServiceAsyncClient,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceRestTransport,
+ "rest",
+ None,
+ ),
+ ],
+)
+def test_data_connector_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+def test_data_connector_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.data_connector_service.transports.DataConnectorServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = DataConnectorServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ DataConnectorServiceClient,
+ transports.DataConnectorServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ DataConnectorServiceAsyncClient,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ ],
+)
+def test_data_connector_service_client_create_channel_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # test that the credentials from file are saved and used as the credentials.
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(grpc_helpers, "create_channel") as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ file_creds = ga_credentials.AnonymousCredentials()
+ load_creds.return_value = (file_creds, None)
+ adc.return_value = (creds, None)
+ client = client_class(client_options=options, transport=transport_name)
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=file_creds,
+ credentials_file=None,
+ quota_project_id=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=None,
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ data_connector_service.SetUpDataConnectorRequest(),
+ {},
+ ],
+)
+def test_set_up_data_connector(request_type, transport: str = "grpc"):
+ client = DataConnectorServiceClient(
+ 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.set_up_data_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+ response = client.set_up_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = data_connector_service.SetUpDataConnectorRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_set_up_data_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 = DataConnectorServiceClient(
+ 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 = data_connector_service.SetUpDataConnectorRequest(
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.set_up_data_connector), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.set_up_data_connector(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.SetUpDataConnectorRequest(
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_set_up_data_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 = DataConnectorServiceClient(
+ 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.set_up_data_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.set_up_data_connector] = (
+ mock_rpc
+ )
+ request = {}
+ client.set_up_data_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()
+
+ client.set_up_data_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
+async def test_set_up_data_connector_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 = DataConnectorServiceAsyncClient(
+ 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.set_up_data_connector
+ 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.set_up_data_connector
+ ] = mock_rpc
+
+ request = {}
+ await client.set_up_data_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.set_up_data_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",
+ [
+ data_connector_service.SetUpDataConnectorRequest(),
+ {},
+ ],
+)
+async def test_set_up_data_connector_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = DataConnectorServiceAsyncClient(
+ 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.set_up_data_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.set_up_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = data_connector_service.SetUpDataConnectorRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_set_up_data_connector_field_headers():
+ client = DataConnectorServiceClient(
+ 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 = data_connector_service.SetUpDataConnectorRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.set_up_data_connector), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.set_up_data_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_set_up_data_connector_field_headers_async():
+ client = DataConnectorServiceAsyncClient(
+ 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 = data_connector_service.SetUpDataConnectorRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.set_up_data_connector), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+ await client.set_up_data_connector(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_set_up_data_connector_flattened():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.set_up_data_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.set_up_data_connector(
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_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].collection_id
+ mock_val = "collection_id_value"
+ assert arg == mock_val
+ arg = args[0].collection_display_name
+ mock_val = "collection_display_name_value"
+ assert arg == mock_val
+ arg = args[0].data_connector
+ mock_val = gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ )
+ assert arg == mock_val
+
+
+def test_set_up_data_connector_flattened_error():
+ client = DataConnectorServiceClient(
+ 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.set_up_data_connector(
+ data_connector_service.SetUpDataConnectorRequest(),
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ ),
+ )
+
+
+@pytest.mark.asyncio
+async def test_set_up_data_connector_flattened_async():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.set_up_data_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.set_up_data_connector(
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_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].collection_id
+ mock_val = "collection_id_value"
+ assert arg == mock_val
+ arg = args[0].collection_display_name
+ mock_val = "collection_display_name_value"
+ assert arg == mock_val
+ arg = args[0].data_connector
+ mock_val = gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ )
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_set_up_data_connector_flattened_error_async():
+ client = DataConnectorServiceAsyncClient(
+ 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.set_up_data_connector(
+ data_connector_service.SetUpDataConnectorRequest(),
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ ),
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ data_connector_service.GetDataConnectorRequest(),
+ {},
+ ],
+)
+def test_get_data_connector(request_type, transport: str = "grpc"):
+ client = DataConnectorServiceClient(
+ 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_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = data_connector.DataConnector(
+ name="name_value",
+ state=data_connector.DataConnector.State.CREATING,
+ data_source="data_source_value",
+ remove_param_keys=["remove_param_keys_value"],
+ sync_mode=data_connector.DataConnector.SyncMode.STREAMING,
+ kms_key_name="kms_key_name_value",
+ action_state=data_connector.DataConnector.State.CREATING,
+ connector_modes=[data_connector.DataConnector.ConnectorMode.DATA_INGESTION],
+ static_ip_enabled=True,
+ static_ip_addresses=["static_ip_addresses_value"],
+ oauth_static_ip_addresses=["oauth_static_ip_addresses_value"],
+ blocking_reasons=[
+ data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ],
+ private_connectivity_project_id="private_connectivity_project_id_value",
+ connector_type=data_connector.ConnectorType.THIRD_PARTY,
+ realtime_state=data_connector.DataConnector.State.CREATING,
+ acl_enabled=True,
+ create_eua_saas=True,
+ auto_run_disabled=True,
+ incremental_sync_disabled=True,
+ hybrid_ingestion_disabled=True,
+ egress_fqdns=["egress_fqdns_value"],
+ vpcsc_enabled=True,
+ connector_source_id="connector_source_id_value",
+ tag="tag_value",
+ json_params="json_params_value",
+ )
+ response = client.get_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = data_connector_service.GetDataConnectorRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, data_connector.DataConnector)
+ assert response.name == "name_value"
+ assert response.state == data_connector.DataConnector.State.CREATING
+ assert response.data_source == "data_source_value"
+ assert response.remove_param_keys == ["remove_param_keys_value"]
+ assert response.sync_mode == data_connector.DataConnector.SyncMode.STREAMING
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.action_state == data_connector.DataConnector.State.CREATING
+ assert response.connector_modes == [
+ data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ]
+ assert response.static_ip_enabled is True
+ assert response.static_ip_addresses == ["static_ip_addresses_value"]
+ assert response.oauth_static_ip_addresses == ["oauth_static_ip_addresses_value"]
+ assert response.blocking_reasons == [
+ data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ]
+ assert (
+ response.private_connectivity_project_id
+ == "private_connectivity_project_id_value"
+ )
+ assert response.connector_type == data_connector.ConnectorType.THIRD_PARTY
+ assert response.realtime_state == data_connector.DataConnector.State.CREATING
+ assert response.acl_enabled is True
+ assert response.create_eua_saas is True
+ assert response.auto_run_disabled is True
+ assert response.incremental_sync_disabled is True
+ assert response.hybrid_ingestion_disabled is True
+ assert response.egress_fqdns == ["egress_fqdns_value"]
+ assert response.vpcsc_enabled is True
+ assert response.connector_source_id == "connector_source_id_value"
+ assert response.tag == "tag_value"
+
+
+def test_get_data_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 = DataConnectorServiceClient(
+ 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 = data_connector_service.GetDataConnectorRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_data_connector), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_data_connector(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.GetDataConnectorRequest(
+ name="name_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_data_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 = DataConnectorServiceClient(
+ 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_data_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_data_connector] = (
+ mock_rpc
+ )
+ request = {}
+ client.get_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_data_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
+async def test_get_data_connector_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 = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_data_connector
+ 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_data_connector
+ ] = mock_rpc
+
+ request = {}
+ await client.get_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_data_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",
+ [
+ data_connector_service.GetDataConnectorRequest(),
+ {},
+ ],
+)
+async def test_get_data_connector_async(request_type, transport: str = "grpc_asyncio"):
+ client = DataConnectorServiceAsyncClient(
+ 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_data_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ data_connector.DataConnector(
+ name="name_value",
+ state=data_connector.DataConnector.State.CREATING,
+ data_source="data_source_value",
+ remove_param_keys=["remove_param_keys_value"],
+ sync_mode=data_connector.DataConnector.SyncMode.STREAMING,
+ kms_key_name="kms_key_name_value",
+ action_state=data_connector.DataConnector.State.CREATING,
+ connector_modes=[
+ data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ],
+ static_ip_enabled=True,
+ static_ip_addresses=["static_ip_addresses_value"],
+ oauth_static_ip_addresses=["oauth_static_ip_addresses_value"],
+ blocking_reasons=[
+ data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ],
+ private_connectivity_project_id="private_connectivity_project_id_value",
+ connector_type=data_connector.ConnectorType.THIRD_PARTY,
+ realtime_state=data_connector.DataConnector.State.CREATING,
+ acl_enabled=True,
+ create_eua_saas=True,
+ auto_run_disabled=True,
+ incremental_sync_disabled=True,
+ hybrid_ingestion_disabled=True,
+ egress_fqdns=["egress_fqdns_value"],
+ vpcsc_enabled=True,
+ connector_source_id="connector_source_id_value",
+ tag="tag_value",
+ )
+ )
+ response = await client.get_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = data_connector_service.GetDataConnectorRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, data_connector.DataConnector)
+ assert response.name == "name_value"
+ assert response.state == data_connector.DataConnector.State.CREATING
+ assert response.data_source == "data_source_value"
+ assert response.remove_param_keys == ["remove_param_keys_value"]
+ assert response.sync_mode == data_connector.DataConnector.SyncMode.STREAMING
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.action_state == data_connector.DataConnector.State.CREATING
+ assert response.connector_modes == [
+ data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ]
+ assert response.static_ip_enabled is True
+ assert response.static_ip_addresses == ["static_ip_addresses_value"]
+ assert response.oauth_static_ip_addresses == ["oauth_static_ip_addresses_value"]
+ assert response.blocking_reasons == [
+ data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ]
+ assert (
+ response.private_connectivity_project_id
+ == "private_connectivity_project_id_value"
+ )
+ assert response.connector_type == data_connector.ConnectorType.THIRD_PARTY
+ assert response.realtime_state == data_connector.DataConnector.State.CREATING
+ assert response.acl_enabled is True
+ assert response.create_eua_saas is True
+ assert response.auto_run_disabled is True
+ assert response.incremental_sync_disabled is True
+ assert response.hybrid_ingestion_disabled is True
+ assert response.egress_fqdns == ["egress_fqdns_value"]
+ assert response.vpcsc_enabled is True
+ assert response.connector_source_id == "connector_source_id_value"
+ assert response.tag == "tag_value"
+
+
+def test_get_data_connector_field_headers():
+ client = DataConnectorServiceClient(
+ 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 = data_connector_service.GetDataConnectorRequest()
+
+ 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_connector), "__call__"
+ ) as call:
+ call.return_value = data_connector.DataConnector()
+ client.get_data_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",
+ "name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_data_connector_field_headers_async():
+ client = DataConnectorServiceAsyncClient(
+ 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 = data_connector_service.GetDataConnectorRequest()
+
+ 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_connector), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ data_connector.DataConnector()
+ )
+ await client.get_data_connector(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_data_connector_flattened():
+ client = DataConnectorServiceClient(
+ 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_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = data_connector.DataConnector()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_data_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].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+def test_get_data_connector_flattened_error():
+ client = DataConnectorServiceClient(
+ 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_data_connector(
+ data_connector_service.GetDataConnectorRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_data_connector_flattened_async():
+ client = DataConnectorServiceAsyncClient(
+ 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_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = data_connector.DataConnector()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ data_connector.DataConnector()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_data_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].name
+ mock_val = "name_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_get_data_connector_flattened_error_async():
+ client = DataConnectorServiceAsyncClient(
+ 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_connector(
+ data_connector_service.GetDataConnectorRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ data_connector_service.UpdateDataConnectorRequest(),
+ {},
+ ],
+)
+def test_update_data_connector(request_type, transport: str = "grpc"):
+ client = DataConnectorServiceClient(
+ 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_data_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_data_connector.DataConnector(
+ name="name_value",
+ state=gcd_data_connector.DataConnector.State.CREATING,
+ data_source="data_source_value",
+ remove_param_keys=["remove_param_keys_value"],
+ sync_mode=gcd_data_connector.DataConnector.SyncMode.STREAMING,
+ kms_key_name="kms_key_name_value",
+ action_state=gcd_data_connector.DataConnector.State.CREATING,
+ connector_modes=[
+ gcd_data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ],
+ static_ip_enabled=True,
+ static_ip_addresses=["static_ip_addresses_value"],
+ oauth_static_ip_addresses=["oauth_static_ip_addresses_value"],
+ blocking_reasons=[
+ gcd_data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ],
+ private_connectivity_project_id="private_connectivity_project_id_value",
+ connector_type=gcd_data_connector.ConnectorType.THIRD_PARTY,
+ realtime_state=gcd_data_connector.DataConnector.State.CREATING,
+ acl_enabled=True,
+ create_eua_saas=True,
+ auto_run_disabled=True,
+ incremental_sync_disabled=True,
+ hybrid_ingestion_disabled=True,
+ egress_fqdns=["egress_fqdns_value"],
+ vpcsc_enabled=True,
+ connector_source_id="connector_source_id_value",
+ tag="tag_value",
+ json_params="json_params_value",
+ )
+ response = client.update_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = data_connector_service.UpdateDataConnectorRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_data_connector.DataConnector)
+ assert response.name == "name_value"
+ assert response.state == gcd_data_connector.DataConnector.State.CREATING
+ assert response.data_source == "data_source_value"
+ assert response.remove_param_keys == ["remove_param_keys_value"]
+ assert response.sync_mode == gcd_data_connector.DataConnector.SyncMode.STREAMING
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.action_state == gcd_data_connector.DataConnector.State.CREATING
+ assert response.connector_modes == [
+ gcd_data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ]
+ assert response.static_ip_enabled is True
+ assert response.static_ip_addresses == ["static_ip_addresses_value"]
+ assert response.oauth_static_ip_addresses == ["oauth_static_ip_addresses_value"]
+ assert response.blocking_reasons == [
+ gcd_data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ]
+ assert (
+ response.private_connectivity_project_id
+ == "private_connectivity_project_id_value"
+ )
+ assert response.connector_type == gcd_data_connector.ConnectorType.THIRD_PARTY
+ assert response.realtime_state == gcd_data_connector.DataConnector.State.CREATING
+ assert response.acl_enabled is True
+ assert response.create_eua_saas is True
+ assert response.auto_run_disabled is True
+ assert response.incremental_sync_disabled is True
+ assert response.hybrid_ingestion_disabled is True
+ assert response.egress_fqdns == ["egress_fqdns_value"]
+ assert response.vpcsc_enabled is True
+ assert response.connector_source_id == "connector_source_id_value"
+ assert response.tag == "tag_value"
+
+
+def test_update_data_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 = DataConnectorServiceClient(
+ 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 = data_connector_service.UpdateDataConnectorRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_data_connector), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_data_connector(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.UpdateDataConnectorRequest()
+ assert args[0] == request_msg
+
+
+def test_update_data_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 = DataConnectorServiceClient(
+ 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.update_data_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_data_connector] = (
+ mock_rpc
+ )
+ request = {}
+ client.update_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_data_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
+async def test_update_data_connector_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 = DataConnectorServiceAsyncClient(
+ 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.update_data_connector
+ 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.update_data_connector
+ ] = mock_rpc
+
+ request = {}
+ await client.update_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_data_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",
+ [
+ data_connector_service.UpdateDataConnectorRequest(),
+ {},
+ ],
+)
+async def test_update_data_connector_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = DataConnectorServiceAsyncClient(
+ 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.update_data_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_data_connector.DataConnector(
+ name="name_value",
+ state=gcd_data_connector.DataConnector.State.CREATING,
+ data_source="data_source_value",
+ remove_param_keys=["remove_param_keys_value"],
+ sync_mode=gcd_data_connector.DataConnector.SyncMode.STREAMING,
+ kms_key_name="kms_key_name_value",
+ action_state=gcd_data_connector.DataConnector.State.CREATING,
+ connector_modes=[
+ gcd_data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ],
+ static_ip_enabled=True,
+ static_ip_addresses=["static_ip_addresses_value"],
+ oauth_static_ip_addresses=["oauth_static_ip_addresses_value"],
+ blocking_reasons=[
+ gcd_data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ],
+ private_connectivity_project_id="private_connectivity_project_id_value",
+ connector_type=gcd_data_connector.ConnectorType.THIRD_PARTY,
+ realtime_state=gcd_data_connector.DataConnector.State.CREATING,
+ acl_enabled=True,
+ create_eua_saas=True,
+ auto_run_disabled=True,
+ incremental_sync_disabled=True,
+ hybrid_ingestion_disabled=True,
+ egress_fqdns=["egress_fqdns_value"],
+ vpcsc_enabled=True,
+ connector_source_id="connector_source_id_value",
+ tag="tag_value",
+ )
+ )
+ response = await client.update_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = data_connector_service.UpdateDataConnectorRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_data_connector.DataConnector)
+ assert response.name == "name_value"
+ assert response.state == gcd_data_connector.DataConnector.State.CREATING
+ assert response.data_source == "data_source_value"
+ assert response.remove_param_keys == ["remove_param_keys_value"]
+ assert response.sync_mode == gcd_data_connector.DataConnector.SyncMode.STREAMING
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.action_state == gcd_data_connector.DataConnector.State.CREATING
+ assert response.connector_modes == [
+ gcd_data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ]
+ assert response.static_ip_enabled is True
+ assert response.static_ip_addresses == ["static_ip_addresses_value"]
+ assert response.oauth_static_ip_addresses == ["oauth_static_ip_addresses_value"]
+ assert response.blocking_reasons == [
+ gcd_data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ]
+ assert (
+ response.private_connectivity_project_id
+ == "private_connectivity_project_id_value"
+ )
+ assert response.connector_type == gcd_data_connector.ConnectorType.THIRD_PARTY
+ assert response.realtime_state == gcd_data_connector.DataConnector.State.CREATING
+ assert response.acl_enabled is True
+ assert response.create_eua_saas is True
+ assert response.auto_run_disabled is True
+ assert response.incremental_sync_disabled is True
+ assert response.hybrid_ingestion_disabled is True
+ assert response.egress_fqdns == ["egress_fqdns_value"]
+ assert response.vpcsc_enabled is True
+ assert response.connector_source_id == "connector_source_id_value"
+ assert response.tag == "tag_value"
+
+
+def test_update_data_connector_field_headers():
+ client = DataConnectorServiceClient(
+ 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 = data_connector_service.UpdateDataConnectorRequest()
+
+ request.data_connector.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_data_connector), "__call__"
+ ) as call:
+ call.return_value = gcd_data_connector.DataConnector()
+ client.update_data_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",
+ "data_connector.name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_data_connector_field_headers_async():
+ client = DataConnectorServiceAsyncClient(
+ 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 = data_connector_service.UpdateDataConnectorRequest()
+
+ request.data_connector.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_data_connector), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_data_connector.DataConnector()
+ )
+ await client.update_data_connector(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",
+ "data_connector.name=name_value",
+ ) in kw["metadata"]
+
+
+def test_update_data_connector_flattened():
+ client = DataConnectorServiceClient(
+ 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_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_data_connector.DataConnector()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_data_connector(
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_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].data_connector
+ mock_val = gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ )
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+def test_update_data_connector_flattened_error():
+ client = DataConnectorServiceClient(
+ 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_data_connector(
+ data_connector_service.UpdateDataConnectorRequest(),
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_data_connector_flattened_async():
+ client = DataConnectorServiceAsyncClient(
+ 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_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_data_connector.DataConnector()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_data_connector.DataConnector()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_data_connector(
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_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].data_connector
+ mock_val = gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ )
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_update_data_connector_flattened_error_async():
+ client = DataConnectorServiceAsyncClient(
+ 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_data_connector(
+ data_connector_service.UpdateDataConnectorRequest(),
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_set_up_data_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 = DataConnectorServiceClient(
+ 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.set_up_data_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.set_up_data_connector] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.set_up_data_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.set_up_data_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_set_up_data_connector_rest_required_fields(
+ request_type=data_connector_service.SetUpDataConnectorRequest,
+):
+ transport_class = transports.DataConnectorServiceRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request_init["collection_id"] = ""
+ request_init["collection_display_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._BaseSetUpDataConnector,
+ "_BaseSetUpDataConnector__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"
+ jsonified_request["collectionId"] = "collection_id_value"
+ jsonified_request["collectionDisplayName"] = "collection_display_name_value"
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
+ assert "collectionId" in jsonified_request
+ assert jsonified_request["collectionId"] == "collection_id_value"
+ assert "collectionDisplayName" in jsonified_request
+ assert jsonified_request["collectionDisplayName"] == "collection_display_name_value"
+
+ client = DataConnectorServiceClient(
+ 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.set_up_data_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_set_up_data_connector_rest_flattened():
+ client = DataConnectorServiceClient(
+ 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",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_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.set_up_data_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/*}:setUpDataConnector"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_set_up_data_connector_rest_flattened_error(transport: str = "rest"):
+ client = DataConnectorServiceClient(
+ 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.set_up_data_connector(
+ data_connector_service.SetUpDataConnectorRequest(),
+ parent="parent_value",
+ collection_id="collection_id_value",
+ collection_display_name="collection_display_name_value",
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ ),
+ )
+
+
+def test_get_data_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 = DataConnectorServiceClient(
+ 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_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_data_connector] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.get_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_data_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_data_connector_rest_required_fields(
+ request_type=data_connector_service.GetDataConnectorRequest,
+):
+ transport_class = transports.DataConnectorServiceRestTransport
+
+ 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._BaseGetDataConnector,
+ "_BaseGetDataConnector__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 = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = data_connector.DataConnector()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = data_connector.DataConnector.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_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_data_connector_rest_flattened():
+ client = DataConnectorServiceClient(
+ 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 = data_connector.DataConnector()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector"
+ }
+
+ # 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 = data_connector.DataConnector.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_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/*/collections/*/dataConnector}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_data_connector_rest_flattened_error(transport: str = "rest"):
+ client = DataConnectorServiceClient(
+ 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_connector(
+ data_connector_service.GetDataConnectorRequest(),
+ name="name_value",
+ )
+
+
+def test_update_data_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 = DataConnectorServiceClient(
+ 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_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_data_connector] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.update_data_connector(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_data_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_data_connector_rest_required_fields(
+ request_type=data_connector_service.UpdateDataConnectorRequest,
+):
+ transport_class = transports.DataConnectorServiceRestTransport
+
+ 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._BaseUpdateDataConnector,
+ "_BaseUpdateDataConnector__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(("updateMask",))
+
+ # verify required fields with non-default values are left alone
+
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_data_connector.DataConnector()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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
+
+ # Convert return value to protobuf type
+ return_value = gcd_data_connector.DataConnector.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_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_data_connector_rest_flattened():
+ client = DataConnectorServiceClient(
+ 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 = gcd_data_connector.DataConnector()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "data_connector": {
+ "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_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
+ # Convert return value to protobuf type
+ return_value = gcd_data_connector.DataConnector.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_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/{data_connector.name=projects/*/locations/*/collections/*/dataConnector}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_update_data_connector_rest_flattened_error(transport: str = "rest"):
+ client = DataConnectorServiceClient(
+ 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_connector(
+ data_connector_service.UpdateDataConnectorRequest(),
+ data_connector=gcd_data_connector.DataConnector(
+ params=struct_pb2.Struct(
+ fields={
+ "key_value": struct_pb2.Value(
+ null_value=struct_pb2.NullValue.NULL_VALUE
+ )
+ }
+ )
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.DataConnectorServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.DataConnectorServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = DataConnectorServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.DataConnectorServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = DataConnectorServiceClient(
+ 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 = DataConnectorServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.DataConnectorServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = DataConnectorServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.DataConnectorServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = DataConnectorServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.DataConnectorServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.DataConnectorServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DataConnectorServiceGrpcTransport,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ transports.DataConnectorServiceRestTransport,
+ ],
+)
+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 = DataConnectorServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = DataConnectorServiceClient(
+ 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_set_up_data_connector_empty_call_grpc():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.set_up_data_connector), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.set_up_data_connector(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.SetUpDataConnectorRequest()
+ assert args[0] == request_msg
+
+
+# This 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_connector_empty_call_grpc():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_data_connector), "__call__"
+ ) as call:
+ call.return_value = data_connector.DataConnector()
+ client.get_data_connector(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.GetDataConnectorRequest()
+ assert args[0] == request_msg
+
+
+# This 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_connector_empty_call_grpc():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_data_connector), "__call__"
+ ) as call:
+ call.return_value = gcd_data_connector.DataConnector()
+ client.update_data_connector(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.UpdateDataConnectorRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = DataConnectorServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = DataConnectorServiceAsyncClient(
+ 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_set_up_data_connector_empty_call_grpc_asyncio():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.set_up_data_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.set_up_data_connector(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.SetUpDataConnectorRequest()
+ assert args[0] == request_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_connector_empty_call_grpc_asyncio():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_data_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ data_connector.DataConnector(
+ name="name_value",
+ state=data_connector.DataConnector.State.CREATING,
+ data_source="data_source_value",
+ remove_param_keys=["remove_param_keys_value"],
+ sync_mode=data_connector.DataConnector.SyncMode.STREAMING,
+ kms_key_name="kms_key_name_value",
+ action_state=data_connector.DataConnector.State.CREATING,
+ connector_modes=[
+ data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ],
+ static_ip_enabled=True,
+ static_ip_addresses=["static_ip_addresses_value"],
+ oauth_static_ip_addresses=["oauth_static_ip_addresses_value"],
+ blocking_reasons=[
+ data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ],
+ private_connectivity_project_id="private_connectivity_project_id_value",
+ connector_type=data_connector.ConnectorType.THIRD_PARTY,
+ realtime_state=data_connector.DataConnector.State.CREATING,
+ acl_enabled=True,
+ create_eua_saas=True,
+ auto_run_disabled=True,
+ incremental_sync_disabled=True,
+ hybrid_ingestion_disabled=True,
+ egress_fqdns=["egress_fqdns_value"],
+ vpcsc_enabled=True,
+ connector_source_id="connector_source_id_value",
+ tag="tag_value",
+ )
+ )
+ await client.get_data_connector(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.GetDataConnectorRequest()
+ assert args[0] == request_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_connector_empty_call_grpc_asyncio():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_data_connector), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_data_connector.DataConnector(
+ name="name_value",
+ state=gcd_data_connector.DataConnector.State.CREATING,
+ data_source="data_source_value",
+ remove_param_keys=["remove_param_keys_value"],
+ sync_mode=gcd_data_connector.DataConnector.SyncMode.STREAMING,
+ kms_key_name="kms_key_name_value",
+ action_state=gcd_data_connector.DataConnector.State.CREATING,
+ connector_modes=[
+ gcd_data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ],
+ static_ip_enabled=True,
+ static_ip_addresses=["static_ip_addresses_value"],
+ oauth_static_ip_addresses=["oauth_static_ip_addresses_value"],
+ blocking_reasons=[
+ gcd_data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ],
+ private_connectivity_project_id="private_connectivity_project_id_value",
+ connector_type=gcd_data_connector.ConnectorType.THIRD_PARTY,
+ realtime_state=gcd_data_connector.DataConnector.State.CREATING,
+ acl_enabled=True,
+ create_eua_saas=True,
+ auto_run_disabled=True,
+ incremental_sync_disabled=True,
+ hybrid_ingestion_disabled=True,
+ egress_fqdns=["egress_fqdns_value"],
+ vpcsc_enabled=True,
+ connector_source_id="connector_source_id_value",
+ tag="tag_value",
+ )
+ )
+ await client.update_data_connector(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.UpdateDataConnectorRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = DataConnectorServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_set_up_data_connector_rest_bad_request(
+ request_type=data_connector_service.SetUpDataConnectorRequest,
+):
+ client = DataConnectorServiceClient(
+ 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.set_up_data_connector(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ data_connector_service.SetUpDataConnectorRequest,
+ dict,
+ ],
+)
+def test_set_up_data_connector_rest_call_success(request_type):
+ client = DataConnectorServiceClient(
+ 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")
+
+ # 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.set_up_data_connector(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_set_up_data_connector_rest_interceptors(null_interceptor):
+ transport = transports.DataConnectorServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.DataConnectorServiceRestInterceptor(),
+ )
+ client = DataConnectorServiceClient(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.DataConnectorServiceRestInterceptor, "post_set_up_data_connector"
+ ) as post,
+ mock.patch.object(
+ transports.DataConnectorServiceRestInterceptor,
+ "post_set_up_data_connector_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.DataConnectorServiceRestInterceptor, "pre_set_up_data_connector"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = data_connector_service.SetUpDataConnectorRequest.pb(
+ data_connector_service.SetUpDataConnectorRequest()
+ )
+ 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 = data_connector_service.SetUpDataConnectorRequest()
+ 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.set_up_data_connector(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_get_data_connector_rest_bad_request(
+ request_type=data_connector_service.GetDataConnectorRequest,
+):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector"
+ }
+ 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_connector(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ data_connector_service.GetDataConnectorRequest,
+ dict,
+ ],
+)
+def test_get_data_connector_rest_call_success(request_type):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector"
+ }
+ 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 = data_connector.DataConnector(
+ name="name_value",
+ state=data_connector.DataConnector.State.CREATING,
+ data_source="data_source_value",
+ remove_param_keys=["remove_param_keys_value"],
+ sync_mode=data_connector.DataConnector.SyncMode.STREAMING,
+ kms_key_name="kms_key_name_value",
+ action_state=data_connector.DataConnector.State.CREATING,
+ connector_modes=[data_connector.DataConnector.ConnectorMode.DATA_INGESTION],
+ static_ip_enabled=True,
+ static_ip_addresses=["static_ip_addresses_value"],
+ oauth_static_ip_addresses=["oauth_static_ip_addresses_value"],
+ blocking_reasons=[
+ data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ],
+ private_connectivity_project_id="private_connectivity_project_id_value",
+ connector_type=data_connector.ConnectorType.THIRD_PARTY,
+ realtime_state=data_connector.DataConnector.State.CREATING,
+ acl_enabled=True,
+ create_eua_saas=True,
+ auto_run_disabled=True,
+ incremental_sync_disabled=True,
+ hybrid_ingestion_disabled=True,
+ egress_fqdns=["egress_fqdns_value"],
+ vpcsc_enabled=True,
+ connector_source_id="connector_source_id_value",
+ tag="tag_value",
+ json_params="json_params_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 = data_connector.DataConnector.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_connector(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, data_connector.DataConnector)
+ assert response.name == "name_value"
+ assert response.state == data_connector.DataConnector.State.CREATING
+ assert response.data_source == "data_source_value"
+ assert response.remove_param_keys == ["remove_param_keys_value"]
+ assert response.sync_mode == data_connector.DataConnector.SyncMode.STREAMING
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.action_state == data_connector.DataConnector.State.CREATING
+ assert response.connector_modes == [
+ data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ]
+ assert response.static_ip_enabled is True
+ assert response.static_ip_addresses == ["static_ip_addresses_value"]
+ assert response.oauth_static_ip_addresses == ["oauth_static_ip_addresses_value"]
+ assert response.blocking_reasons == [
+ data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ]
+ assert (
+ response.private_connectivity_project_id
+ == "private_connectivity_project_id_value"
+ )
+ assert response.connector_type == data_connector.ConnectorType.THIRD_PARTY
+ assert response.realtime_state == data_connector.DataConnector.State.CREATING
+ assert response.acl_enabled is True
+ assert response.create_eua_saas is True
+ assert response.auto_run_disabled is True
+ assert response.incremental_sync_disabled is True
+ assert response.hybrid_ingestion_disabled is True
+ assert response.egress_fqdns == ["egress_fqdns_value"]
+ assert response.vpcsc_enabled is True
+ assert response.connector_source_id == "connector_source_id_value"
+ assert response.tag == "tag_value"
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_data_connector_rest_interceptors(null_interceptor):
+ transport = transports.DataConnectorServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.DataConnectorServiceRestInterceptor(),
+ )
+ client = DataConnectorServiceClient(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.DataConnectorServiceRestInterceptor, "post_get_data_connector"
+ ) as post,
+ mock.patch.object(
+ transports.DataConnectorServiceRestInterceptor,
+ "post_get_data_connector_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.DataConnectorServiceRestInterceptor, "pre_get_data_connector"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = data_connector_service.GetDataConnectorRequest.pb(
+ data_connector_service.GetDataConnectorRequest()
+ )
+ 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 = data_connector.DataConnector.to_json(
+ data_connector.DataConnector()
+ )
+ req.return_value.content = return_value
+
+ request = data_connector_service.GetDataConnectorRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = data_connector.DataConnector()
+ post_with_metadata.return_value = data_connector.DataConnector(), metadata
+
+ client.get_data_connector(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_update_data_connector_rest_bad_request(
+ request_type=data_connector_service.UpdateDataConnectorRequest,
+):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "data_connector": {
+ "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector"
+ }
+ }
+ 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_connector(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ data_connector_service.UpdateDataConnectorRequest,
+ dict,
+ ],
+)
+def test_update_data_connector_rest_call_success(request_type):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "data_connector": {
+ "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector"
+ }
+ }
+ request_init["data_connector"] = {
+ "params": {"fields": {}},
+ "json_params": "json_params_value",
+ "name": "projects/sample1/locations/sample2/collections/sample3/dataConnector",
+ "state": 1,
+ "data_source": "data_source_value",
+ "remove_param_keys": ["remove_param_keys_value1", "remove_param_keys_value2"],
+ "refresh_interval": {"seconds": 751, "nanos": 543},
+ "next_sync_time": {
+ "year": 433,
+ "month": 550,
+ "day": 318,
+ "hours": 561,
+ "minutes": 773,
+ "seconds": 751,
+ "nanos": 543,
+ "utc_offset": {},
+ "time_zone": {"id": "id_value", "version": "version_value"},
+ },
+ "entities": [
+ {
+ "params": {},
+ "json_params": "json_params_value",
+ "entity_name": "entity_name_value",
+ "key_property_mappings": {},
+ "data_store": "data_store_value",
+ "starting_schema": {
+ "struct_schema": {},
+ "json_schema": "json_schema_value",
+ "name": "name_value",
+ },
+ "healthcare_fhir_config": {
+ "enable_configurable_schema": True,
+ "enable_static_indexing_for_batch_ingestion": True,
+ "initial_filter_groups": [
+ "initial_filter_groups_value1",
+ "initial_filter_groups_value2",
+ ],
+ },
+ }
+ ],
+ "create_time": {"seconds": 751, "nanos": 543},
+ "latest_pause_time": {},
+ "last_sync_time": {},
+ "update_time": {},
+ "errors": [
+ {
+ "code": 411,
+ "message": "message_value",
+ "details": [
+ {
+ "type_url": "type.googleapis.com/google.protobuf.Duration",
+ "value": b"\x08\x0c\x10\xdb\x07",
+ }
+ ],
+ }
+ ],
+ "sync_mode": 1,
+ "kms_key_name": "kms_key_name_value",
+ "destination_configs": [
+ {
+ "params": {},
+ "json_params": "json_params_value",
+ "key": "key_value",
+ "destinations": [{"host": "host_value", "port": 453}],
+ }
+ ],
+ "action_state": 1,
+ "action_config": {
+ "action_params": {},
+ "json_action_params": "json_action_params_value",
+ "is_action_configured": True,
+ "service_name": "service_name_value",
+ "use_static_secrets": True,
+ "create_bap_connection": True,
+ "user_defined_scopes_mapping": {},
+ },
+ "end_user_config": {
+ "auth_params": {},
+ "json_auth_params": "json_auth_params_value",
+ "additional_params": {},
+ "tenant": {
+ "id": "id_value",
+ "uri": "uri_value",
+ "display_name": "display_name_value",
+ },
+ },
+ "federated_config": {
+ "auth_params": {},
+ "json_auth_params": "json_auth_params_value",
+ "additional_params": {},
+ },
+ "connector_modes": [1],
+ "static_ip_enabled": True,
+ "static_ip_addresses": [
+ "static_ip_addresses_value1",
+ "static_ip_addresses_value2",
+ ],
+ "oauth_static_ip_addresses": [
+ "oauth_static_ip_addresses_value1",
+ "oauth_static_ip_addresses_value2",
+ ],
+ "blocking_reasons": [1],
+ "identity_schedule_config": {"refresh_interval": {}, "next_sync_time": {}},
+ "private_connectivity_project_id": "private_connectivity_project_id_value",
+ "bap_config": {
+ "supported_connector_modes": [1],
+ "enabled_actions": ["enabled_actions_value1", "enabled_actions_value2"],
+ "toolspec_override": {"tools": {}, "base_version": "base_version_value"},
+ },
+ "connector_type": 1,
+ "realtime_state": 1,
+ "alert_policy_configs": [
+ {
+ "alert_policy_name": "alert_policy_name_value",
+ "alert_enrollments": [
+ {"alert_id": "alert_id_value", "enroll_state": 1}
+ ],
+ }
+ ],
+ "realtime_sync_config": {
+ "webhook_uri": "webhook_uri_value",
+ "realtime_sync_secret": "realtime_sync_secret_value",
+ "streaming_error": {"streaming_error_reason": 1, "error": {}},
+ },
+ "acl_enabled": True,
+ "create_eua_saas": True,
+ "auto_run_disabled": True,
+ "incremental_sync_disabled": True,
+ "incremental_refresh_interval": {},
+ "hybrid_ingestion_disabled": True,
+ "data_protection_policy": {
+ "sensitive_data_protection_policy": {"policy": "policy_value"}
+ },
+ "egress_fqdns": ["egress_fqdns_value1", "egress_fqdns_value2"],
+ "vpcsc_enabled": True,
+ "dynamic_tools": [
+ {
+ "name": "name_value",
+ "description": "description_value",
+ "enabled": True,
+ "display_name": "display_name_value",
+ }
+ ],
+ "cli_config": {
+ "enabled_actions": ["enabled_actions_value1", "enabled_actions_value2"]
+ },
+ "connector_source_id": "connector_source_id_value",
+ "tag": "tag_value",
+ "metadata": {
+ "title": "title_value",
+ "description": "description_value",
+ "short_description": "short_description_value",
+ "author": "author_value",
+ "note": "note_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 = data_connector_service.UpdateDataConnectorRequest.meta.fields[
+ "data_connector"
+ ]
+
+ 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_connector"].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_connector"][field])):
+ del request_init["data_connector"][field][i][subfield]
+ else:
+ del request_init["data_connector"][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 = gcd_data_connector.DataConnector(
+ name="name_value",
+ state=gcd_data_connector.DataConnector.State.CREATING,
+ data_source="data_source_value",
+ remove_param_keys=["remove_param_keys_value"],
+ sync_mode=gcd_data_connector.DataConnector.SyncMode.STREAMING,
+ kms_key_name="kms_key_name_value",
+ action_state=gcd_data_connector.DataConnector.State.CREATING,
+ connector_modes=[
+ gcd_data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ],
+ static_ip_enabled=True,
+ static_ip_addresses=["static_ip_addresses_value"],
+ oauth_static_ip_addresses=["oauth_static_ip_addresses_value"],
+ blocking_reasons=[
+ gcd_data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ],
+ private_connectivity_project_id="private_connectivity_project_id_value",
+ connector_type=gcd_data_connector.ConnectorType.THIRD_PARTY,
+ realtime_state=gcd_data_connector.DataConnector.State.CREATING,
+ acl_enabled=True,
+ create_eua_saas=True,
+ auto_run_disabled=True,
+ incremental_sync_disabled=True,
+ hybrid_ingestion_disabled=True,
+ egress_fqdns=["egress_fqdns_value"],
+ vpcsc_enabled=True,
+ connector_source_id="connector_source_id_value",
+ tag="tag_value",
+ json_params="json_params_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 = gcd_data_connector.DataConnector.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_connector(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_data_connector.DataConnector)
+ assert response.name == "name_value"
+ assert response.state == gcd_data_connector.DataConnector.State.CREATING
+ assert response.data_source == "data_source_value"
+ assert response.remove_param_keys == ["remove_param_keys_value"]
+ assert response.sync_mode == gcd_data_connector.DataConnector.SyncMode.STREAMING
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.action_state == gcd_data_connector.DataConnector.State.CREATING
+ assert response.connector_modes == [
+ gcd_data_connector.DataConnector.ConnectorMode.DATA_INGESTION
+ ]
+ assert response.static_ip_enabled is True
+ assert response.static_ip_addresses == ["static_ip_addresses_value"]
+ assert response.oauth_static_ip_addresses == ["oauth_static_ip_addresses_value"]
+ assert response.blocking_reasons == [
+ gcd_data_connector.DataConnector.BlockingReason.ALLOWLIST_STATIC_IP
+ ]
+ assert (
+ response.private_connectivity_project_id
+ == "private_connectivity_project_id_value"
+ )
+ assert response.connector_type == gcd_data_connector.ConnectorType.THIRD_PARTY
+ assert response.realtime_state == gcd_data_connector.DataConnector.State.CREATING
+ assert response.acl_enabled is True
+ assert response.create_eua_saas is True
+ assert response.auto_run_disabled is True
+ assert response.incremental_sync_disabled is True
+ assert response.hybrid_ingestion_disabled is True
+ assert response.egress_fqdns == ["egress_fqdns_value"]
+ assert response.vpcsc_enabled is True
+ assert response.connector_source_id == "connector_source_id_value"
+ assert response.tag == "tag_value"
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_data_connector_rest_interceptors(null_interceptor):
+ transport = transports.DataConnectorServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.DataConnectorServiceRestInterceptor(),
+ )
+ client = DataConnectorServiceClient(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.DataConnectorServiceRestInterceptor, "post_update_data_connector"
+ ) as post,
+ mock.patch.object(
+ transports.DataConnectorServiceRestInterceptor,
+ "post_update_data_connector_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.DataConnectorServiceRestInterceptor, "pre_update_data_connector"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = data_connector_service.UpdateDataConnectorRequest.pb(
+ data_connector_service.UpdateDataConnectorRequest()
+ )
+ 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 = gcd_data_connector.DataConnector.to_json(
+ gcd_data_connector.DataConnector()
+ )
+ req.return_value.content = return_value
+
+ request = data_connector_service.UpdateDataConnectorRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcd_data_connector.DataConnector()
+ post_with_metadata.return_value = gcd_data_connector.DataConnector(), metadata
+
+ client.update_data_connector(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_cancel_operation_rest_bad_request(
+ request_type=operations_pb2.CancelOperationRequest,
+):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = "{}"
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.cancel_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_get_operation_rest_bad_request(
+ request_type=operations_pb2.GetOperationRequest,
+):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.get_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_list_operations_rest_bad_request(
+ request_type=operations_pb2.ListOperationsRequest,
+):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.list_operations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_initialize_client_w_rest():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_set_up_data_connector_empty_call_rest():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.set_up_data_connector), "__call__"
+ ) as call:
+ client.set_up_data_connector(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.SetUpDataConnectorRequest()
+ assert args[0] == request_msg
+
+
+# This 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_connector_empty_call_rest():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_data_connector), "__call__"
+ ) as call:
+ client.get_data_connector(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.GetDataConnectorRequest()
+ assert args[0] == request_msg
+
+
+# This 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_connector_empty_call_rest():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_data_connector), "__call__"
+ ) as call:
+ client.update_data_connector(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_connector_service.UpdateDataConnectorRequest()
+ assert args[0] == request_msg
+
+
+def test_data_connector_service_rest_lro_client():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ transport = client.transport
+
+ # Ensure that we have an api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.AbstractOperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert isinstance(
+ client.transport,
+ transports.DataConnectorServiceGrpcTransport,
+ )
+
+
+def test_data_connector_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
+ transport = transports.DataConnectorServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_data_connector_service_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.data_connector_service.transports.DataConnectorServiceTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.DataConnectorServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "set_up_data_connector",
+ "get_data_connector",
+ "update_data_connector",
+ "get_operation",
+ "cancel_operation",
+ "list_operations",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ with pytest.raises(NotImplementedError):
+ transport.close()
+
+ # Additionally, the LRO client (a property) should
+ # also raise NotImplementedError
+ with pytest.raises(NotImplementedError):
+ transport.operations_client
+
+ # Catch all for all remaining methods and properties
+ remainder = [
+ "kind",
+ ]
+ for r in remainder:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, r)()
+
+
+def test_data_connector_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.data_connector_service.transports.DataConnectorServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.DataConnectorServiceTransport(
+ credentials_file="credentials.json",
+ quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_data_connector_service_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.data_connector_service.transports.DataConnectorServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.DataConnectorServiceTransport()
+ adc.assert_called_once()
+
+
+def test_data_connector_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ DataConnectorServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DataConnectorServiceGrpcTransport,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_data_connector_service_transport_auth_adc(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DataConnectorServiceGrpcTransport,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ transports.DataConnectorServiceRestTransport,
+ ],
+)
+def test_data_connector_service_transport_auth_gdch_credentials(transport_class):
+ host = "https://language.com"
+ api_audience_tests = [None, "https://language2.com"]
+ api_audience_expect = [host, "https://language2.com"]
+ for t, e in zip(api_audience_tests, api_audience_expect):
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ gdch_mock = mock.MagicMock()
+ type(gdch_mock).with_gdch_audience = mock.PropertyMock(
+ return_value=gdch_mock
+ )
+ adc.return_value = (gdch_mock, None)
+ transport_class(host=host, api_audience=t)
+ gdch_mock.with_gdch_audience.assert_called_once_with(e)
+
+
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.DataConnectorServiceGrpcTransport, grpc_helpers),
+ (transports.DataConnectorServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_data_connector_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=["1", "2"],
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DataConnectorServiceGrpcTransport,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_data_connector_service_grpc_transport_client_cert_source_for_mtls(
+ transport_class,
+):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_data_connector_service_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.DataConnectorServiceRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_data_connector_service_host_no_port(transport_name):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_data_connector_service_host_with_port(transport_name):
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com:8000"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:8000"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com:8000"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "rest",
+ ],
+)
+def test_data_connector_service_client_transport_session_collision(transport_name):
+ creds1 = ga_credentials.AnonymousCredentials()
+ creds2 = ga_credentials.AnonymousCredentials()
+ client1 = DataConnectorServiceClient(
+ credentials=creds1,
+ transport=transport_name,
+ )
+ client2 = DataConnectorServiceClient(
+ credentials=creds2,
+ transport=transport_name,
+ )
+ session1 = client1.transport.set_up_data_connector._session
+ session2 = client2.transport.set_up_data_connector._session
+ assert session1 != session2
+ session1 = client1.transport.get_data_connector._session
+ session2 = client2.transport.get_data_connector._session
+ assert session1 != session2
+ session1 = client1.transport.update_data_connector._session
+ session2 = client2.transport.update_data_connector._session
+ assert session1 != session2
+
+
+def test_data_connector_service_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.DataConnectorServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_data_connector_service_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.DataConnectorServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.filterwarnings("ignore::FutureWarning")
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DataConnectorServiceGrpcTransport,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_data_connector_service_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = ga_credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DataConnectorServiceGrpcTransport,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_data_connector_service_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_data_connector_service_grpc_lro_client():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.OperationsClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_data_connector_service_grpc_lro_async_client():
+ client = DataConnectorServiceAsyncClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc_asyncio",
+ )
+ transport = client.transport
+
+ # Ensure that we have a api-core operations client.
+ assert isinstance(
+ transport.operations_client,
+ operations_v1.OperationsAsyncClient,
+ )
+
+ # Ensure that subsequent calls to the property send the exact same object.
+ assert transport.operations_client is transport.operations_client
+
+
+def test_content_policy_path():
+ organization = "squid"
+ location = "clam"
+ content_policy = "whelk"
+ expected = "organizations/{organization}/locations/{location}/contentPolicies/{content_policy}".format(
+ organization=organization,
+ location=location,
+ content_policy=content_policy,
+ )
+ actual = DataConnectorServiceClient.content_policy_path(
+ organization, location, content_policy
+ )
+ assert expected == actual
+
+
+def test_parse_content_policy_path():
+ expected = {
+ "organization": "octopus",
+ "location": "oyster",
+ "content_policy": "nudibranch",
+ }
+ path = DataConnectorServiceClient.content_policy_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_content_policy_path(path)
+ assert expected == actual
+
+
+def test_data_connector_path():
+ project = "cuttlefish"
+ location = "mussel"
+ collection = "winkle"
+ expected = "projects/{project}/locations/{location}/collections/{collection}/dataConnector".format(
+ project=project,
+ location=location,
+ collection=collection,
+ )
+ actual = DataConnectorServiceClient.data_connector_path(
+ project, location, collection
+ )
+ assert expected == actual
+
+
+def test_parse_data_connector_path():
+ expected = {
+ "project": "nautilus",
+ "location": "scallop",
+ "collection": "abalone",
+ }
+ path = DataConnectorServiceClient.data_connector_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_data_connector_path(path)
+ assert expected == actual
+
+
+def test_data_store_path():
+ project = "squid"
+ location = "clam"
+ data_store = "whelk"
+ expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ )
+ actual = DataConnectorServiceClient.data_store_path(project, location, data_store)
+ assert expected == actual
+
+
+def test_parse_data_store_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "data_store": "nudibranch",
+ }
+ path = DataConnectorServiceClient.data_store_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_data_store_path(path)
+ assert expected == actual
+
+
+def test_location_path():
+ project = "cuttlefish"
+ location = "mussel"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = DataConnectorServiceClient.location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_location_path():
+ expected = {
+ "project": "winkle",
+ "location": "nautilus",
+ }
+ path = DataConnectorServiceClient.location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_location_path(path)
+ assert expected == actual
+
+
+def test_schema_path():
+ project = "scallop"
+ location = "abalone"
+ data_store = "squid"
+ schema = "clam"
+ expected = "projects/{project}/locations/{location}/dataStores/{data_store}/schemas/{schema}".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ schema=schema,
+ )
+ actual = DataConnectorServiceClient.schema_path(
+ project, location, data_store, schema
+ )
+ assert expected == actual
+
+
+def test_parse_schema_path():
+ expected = {
+ "project": "whelk",
+ "location": "octopus",
+ "data_store": "oyster",
+ "schema": "nudibranch",
+ }
+ path = DataConnectorServiceClient.schema_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_schema_path(path)
+ assert expected == actual
+
+
+def test_service_path():
+ project = "cuttlefish"
+ location = "mussel"
+ namespace = "winkle"
+ service = "nautilus"
+ expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format(
+ project=project,
+ location=location,
+ namespace=namespace,
+ service=service,
+ )
+ actual = DataConnectorServiceClient.service_path(
+ project, location, namespace, service
+ )
+ assert expected == actual
+
+
+def test_parse_service_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ "namespace": "squid",
+ "service": "clam",
+ }
+ path = DataConnectorServiceClient.service_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_service_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "whelk"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = DataConnectorServiceClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "octopus",
+ }
+ path = DataConnectorServiceClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "oyster"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = DataConnectorServiceClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "nudibranch",
+ }
+ path = DataConnectorServiceClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "cuttlefish"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = DataConnectorServiceClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "mussel",
+ }
+ path = DataConnectorServiceClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "winkle"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = DataConnectorServiceClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "nautilus",
+ }
+ path = DataConnectorServiceClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "scallop"
+ location = "abalone"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = DataConnectorServiceClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "squid",
+ "location": "clam",
+ }
+ path = DataConnectorServiceClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataConnectorServiceClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.DataConnectorServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.DataConnectorServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = DataConnectorServiceClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+def test_cancel_operation(transport: str = "grpc"):
+ client = DataConnectorServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
+ client = DataConnectorServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+def test_cancel_operation_field_headers():
+ client = DataConnectorServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = None
+
+ client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_field_headers_async():
+ client = DataConnectorServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_cancel_operation_from_dict():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_from_dict_async():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_cancel_operation_flattened():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_flattened_async():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+def test_get_operation(transport: str = "grpc"):
+ client = DataConnectorServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+@pytest.mark.asyncio
+async def test_get_operation_async(transport: str = "grpc_asyncio"):
+ client = DataConnectorServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_get_operation_field_headers():
+ client = DataConnectorServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_operation_field_headers_async():
+ client = DataConnectorServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_get_operation_from_dict():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ response = client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_from_dict_async():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_get_operation_flattened():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_flattened_async():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+def test_list_operations(transport: str = "grpc"):
+ client = DataConnectorServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+ response = client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+@pytest.mark.asyncio
+async def test_list_operations_async(transport: str = "grpc_asyncio"):
+ client = DataConnectorServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_list_operations_field_headers():
+ client = DataConnectorServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_operations_field_headers_async():
+ client = DataConnectorServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+def test_list_operations_from_dict():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ response = client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_from_dict_async():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_list_operations_flattened():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_flattened_async():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+def test_transport_close_grpc():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+@pytest.mark.asyncio
+async def test_transport_close_grpc_asyncio():
+ client = DataConnectorServiceAsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_transport_close_rest():
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_session")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_client_ctx():
+ transports = [
+ "rest",
+ "grpc",
+ ]
+ for transport in transports:
+ client = DataConnectorServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ # Test client calls underlying transport.
+ with mock.patch.object(type(client.transport), "close") as close:
+ close.assert_not_called()
+ with client:
+ pass
+ close.assert_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class",
+ [
+ (DataConnectorServiceClient, transports.DataConnectorServiceGrpcTransport),
+ (
+ DataConnectorServiceAsyncClient,
+ transports.DataConnectorServiceGrpcAsyncIOTransport,
+ ),
+ ],
+)
+def test_api_key_credentials(client_class, transport_class):
+ with mock.patch.object(
+ google.auth._default, "get_api_key_credentials", create=True
+ ) as get_api_key_credentials:
+ mock_cred = mock.Mock()
+ get_api_key_credentials.return_value = mock_cred
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=mock_cred,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_data_store_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_data_store_service.py
index 983068a32a39..24f615e4522c 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_data_store_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_data_store_service.py
@@ -40,10 +40,14 @@
import google.api_core.operation_async as operation_async # type: ignore
import google.auth
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.options_pb2 as options_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.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.type.expr_pb2 as expr_pb2 # type: ignore
from google.api_core import (
client_options,
future,
@@ -1092,7 +1096,11 @@ def test_data_store_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -1501,6 +1509,8 @@ def test_get_data_store(request_type, transport: str = "grpc"):
kms_key_name="kms_key_name_value",
acl_enabled=True,
identity_mapping_store="identity_mapping_store_value",
+ is_infobot_faq_data_store=True,
+ configurable_billing_approach=data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE,
)
response = client.get_data_store(request)
@@ -1521,6 +1531,11 @@ def test_get_data_store(request_type, transport: str = "grpc"):
assert response.kms_key_name == "kms_key_name_value"
assert response.acl_enabled is True
assert response.identity_mapping_store == "identity_mapping_store_value"
+ assert response.is_infobot_faq_data_store is True
+ assert (
+ response.configurable_billing_approach
+ == data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE
+ )
def test_get_data_store_non_empty_request_with_auto_populated_field():
@@ -1661,6 +1676,8 @@ async def test_get_data_store_async(request_type, transport: str = "grpc_asyncio
kms_key_name="kms_key_name_value",
acl_enabled=True,
identity_mapping_store="identity_mapping_store_value",
+ is_infobot_faq_data_store=True,
+ configurable_billing_approach=data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE,
)
)
response = await client.get_data_store(request)
@@ -1682,6 +1699,11 @@ async def test_get_data_store_async(request_type, transport: str = "grpc_asyncio
assert response.kms_key_name == "kms_key_name_value"
assert response.acl_enabled is True
assert response.identity_mapping_store == "identity_mapping_store_value"
+ assert response.is_infobot_faq_data_store is True
+ assert (
+ response.configurable_billing_approach
+ == data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE
+ )
def test_get_data_store_field_headers():
@@ -2728,6 +2750,8 @@ def test_update_data_store(request_type, transport: str = "grpc"):
kms_key_name="kms_key_name_value",
acl_enabled=True,
identity_mapping_store="identity_mapping_store_value",
+ is_infobot_faq_data_store=True,
+ configurable_billing_approach=gcd_data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE,
)
response = client.update_data_store(request)
@@ -2748,6 +2772,11 @@ def test_update_data_store(request_type, transport: str = "grpc"):
assert response.kms_key_name == "kms_key_name_value"
assert response.acl_enabled is True
assert response.identity_mapping_store == "identity_mapping_store_value"
+ assert response.is_infobot_faq_data_store is True
+ assert (
+ response.configurable_billing_approach
+ == gcd_data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE
+ )
def test_update_data_store_non_empty_request_with_auto_populated_field():
@@ -2890,6 +2919,8 @@ async def test_update_data_store_async(request_type, transport: str = "grpc_asyn
kms_key_name="kms_key_name_value",
acl_enabled=True,
identity_mapping_store="identity_mapping_store_value",
+ is_infobot_faq_data_store=True,
+ configurable_billing_approach=gcd_data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE,
)
)
response = await client.update_data_store(request)
@@ -2911,6 +2942,11 @@ async def test_update_data_store_async(request_type, transport: str = "grpc_asyn
assert response.kms_key_name == "kms_key_name_value"
assert response.acl_enabled is True
assert response.identity_mapping_store == "identity_mapping_store_value"
+ assert response.is_infobot_faq_data_store is True
+ assert (
+ response.configurable_billing_approach
+ == gcd_data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE
+ )
def test_update_data_store_field_headers():
@@ -3074,13 +3110,80 @@ async def test_update_data_store_flattened_error_async():
)
-def test_create_data_store_rest_use_cached_wrapped_rpc():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.GetIamPolicyRequest(),
+ {},
+ ],
+)
+def test_get_iam_policy(request_type, transport: str = "grpc"):
+ client = DataStoreServiceClient(
+ 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_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ response = client.get_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+
+def test_get_iam_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 = DataStoreServiceClient(
+ 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 = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_iam_policy(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_iam_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 = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport="grpc",
)
# Should wrap all calls on client creation
@@ -3088,367 +3191,340 @@ def test_create_data_store_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.create_data_store in client._transport._wrapped_methods
+ assert client._transport.get_iam_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_data_store] = (
- mock_rpc
- )
-
+ client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc
request = {}
- client.create_data_store(request)
+ client.get_iam_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_data_store(request)
+ client.get_iam_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_data_store_rest_required_fields(
- request_type=data_store_service.CreateDataStoreRequest,
+@pytest.mark.asyncio
+async def test_get_iam_policy_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
):
- transport_class = transports.DataStoreServiceRestTransport
+ # Clients should use _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 = DataStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
- request_init = {}
- request_init["parent"] = ""
- request_init["data_store_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 "dataStoreId" not in jsonified_request
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_iam_policy
+ in client._client._transport._wrapped_methods
+ )
- default_values = getattr(
- transport_class._BaseCreateDataStore,
- "_BaseCreateDataStore__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_iam_policy
+ ] = mock_rpc
- # verify required fields with default values are now present
- assert "dataStoreId" in jsonified_request
- assert jsonified_request["dataStoreId"] == request_init["data_store_id"]
+ request = {}
+ await client.get_iam_policy(request)
- jsonified_request["parent"] = "parent_value"
- jsonified_request["dataStoreId"] = "data_store_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(
- (
- "cmekConfigName",
- "createAdvancedSiteSearch",
- "dataStoreId",
- "disableCmek",
- "skipDefaultSchemaCreation",
- )
- )
+ await client.get_iam_policy(request)
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
- assert "dataStoreId" in jsonified_request
- assert jsonified_request["dataStoreId"] == "data_store_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 = DataStoreServiceClient(
- 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
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.GetIamPolicyRequest(),
+ {},
+ ],
+)
+async def test_get_iam_policy_async(request_type, transport: str = "grpc_asyncio"):
+ client = DataStoreServiceAsyncClient(
+ 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.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ response = await client.get_iam_policy(request)
- response = client.create_data_store(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request
- expected_params = [
- (
- "dataStoreId",
- "",
- ),
- ("$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, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
-def test_create_data_store_rest_flattened():
+def test_get_iam_policy_field_headers():
client = DataStoreServiceClient(
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"}
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = iam_policy_pb2.GetIamPolicyRequest()
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- data_store=gcd_data_store.DataStore(name="name_value"),
- data_store_id="data_store_id_value",
- )
- mock_args.update(sample_request)
+ request.resource = "resource_value"
- # 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.get_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.get_iam_policy(request)
- client.create_data_store(**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/*}/dataStores" % client.transport._host,
- args[1],
- )
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "resource=resource_value",
+ ) in kw["metadata"]
-def test_create_data_store_rest_flattened_error(transport: str = "rest"):
- client = DataStoreServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+@pytest.mark.asyncio
+async def test_get_iam_policy_field_headers_async():
+ client = DataStoreServiceAsyncClient(
+ 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.create_data_store(
- data_store_service.CreateDataStoreRequest(),
- parent="parent_value",
- data_store=gcd_data_store.DataStore(name="name_value"),
- data_store_id="data_store_id_value",
- )
-
-
-def test_get_data_store_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = DataStoreServiceClient(
- 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_store 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 = iam_policy_pb2.GetIamPolicyRequest()
- # Replace cached wrapped function with mock
- mock_rpc = 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_store] = mock_rpc
+ request.resource = "resource_value"
- request = {}
- client.get_data_store(request)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ await client.get_iam_policy(request)
# Establish that the underlying gRPC stub method was called.
- assert mock_rpc.call_count == 1
-
- client.get_data_store(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)
+ _, 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",
+ "resource=resource_value",
+ ) in kw["metadata"]
-def test_get_data_store_rest_required_fields(
- request_type=data_store_service.GetDataStoreRequest,
-):
- transport_class = transports.DataStoreServiceRestTransport
- 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_get_iam_policy_from_dict_foreign():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ response = client.get_iam_policy(
+ request={
+ "resource": "resource_value",
+ "options": options_pb2.GetPolicyOptions(requested_policy_version=2598),
+ }
+ )
+ call.assert_called()
- # verify fields with default values are dropped
- default_values = getattr(
- transport_class._BaseGetDataStore,
- "_BaseGetDataStore__REQUIRED_FIELDS_DEFAULT_VALUES",
- {},
+def test_get_iam_policy_flattened():
+ client = DataStoreServiceClient(
+ 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.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_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_get_iam_policy_flattened_error():
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
- request = request_type(**request_init)
- # Designate an appropriate value for the returned response.
- return_value = data_store.DataStore()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force 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.get_iam_policy(
+ iam_policy_pb2.GetIamPolicyRequest(),
+ resource="resource_value",
+ )
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = data_store.DataStore.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
+@pytest.mark.asyncio
+async def test_get_iam_policy_flattened_async():
+ client = DataStoreServiceAsyncClient(
+ 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.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
- response = client.get_data_store(request)
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
-def test_get_data_store_rest_flattened():
+@pytest.mark.asyncio
+async def test_get_iam_policy_flattened_error_async():
+ client = DataStoreServiceAsyncClient(
+ 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_iam_policy(
+ iam_policy_pb2.GetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.SetIamPolicyRequest(),
+ {},
+ ],
+)
+def test_set_iam_policy(request_type, transport: str = "grpc"):
client = DataStoreServiceClient(
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 = data_store.DataStore()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "name": "projects/sample1/locations/sample2/dataStores/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.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
)
- 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 = data_store.DataStore.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = json_return_value.encode("UTF-8")
- req.return_value = response_value
- req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ response = client.set_iam_policy(request)
- client.get_data_store(**mock_args)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ 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/*/dataStores/*}" % client.transport._host,
- args[1],
- )
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
-def test_get_data_store_rest_flattened_error(transport: str = "rest"):
+def test_set_iam_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 = DataStoreServiceClient(
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_data_store(
- data_store_service.GetDataStoreRequest(),
- 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 = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.set_iam_policy(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
)
+ assert args[0] == request_msg
-def test_list_data_stores_rest_use_cached_wrapped_rpc():
+def test_set_iam_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 = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport="grpc",
)
# Should wrap all calls on client creation
@@ -3456,48 +3532,329 @@ def test_list_data_stores_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.list_data_stores in client._transport._wrapped_methods
+ assert client._transport.set_iam_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.list_data_stores] = (
- mock_rpc
- )
-
+ client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc
request = {}
- client.list_data_stores(request)
+ client.set_iam_policy(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.list_data_stores(request)
+ client.set_iam_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_data_stores_rest_required_fields(
- request_type=data_store_service.ListDataStoresRequest,
+@pytest.mark.asyncio
+async def test_set_iam_policy_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
):
- transport_class = transports.DataStoreServiceRestTransport
+ # Clients should use _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 = DataStoreServiceAsyncClient(
+ 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(
+ # 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.set_iam_policy
+ 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.set_iam_policy
+ ] = mock_rpc
+
+ request = {}
+ await client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.set_iam_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",
+ [
+ iam_policy_pb2.SetIamPolicyRequest(),
+ {},
+ ],
+)
+async def test_set_iam_policy_async(request_type, transport: str = "grpc_asyncio"):
+ client = DataStoreServiceAsyncClient(
+ 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.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ response = await client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+
+def test_set_iam_policy_field_headers():
+ client = DataStoreServiceClient(
+ 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 = iam_policy_pb2.SetIamPolicyRequest()
+
+ request.resource = "resource_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.set_iam_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",
+ "resource=resource_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_set_iam_policy_field_headers_async():
+ client = DataStoreServiceAsyncClient(
+ 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 = iam_policy_pb2.SetIamPolicyRequest()
+
+ request.resource = "resource_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ await client.set_iam_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",
+ "resource=resource_value",
+ ) in kw["metadata"]
+
+
+def test_set_iam_policy_from_dict_foreign():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ response = client.set_iam_policy(
+ request={
+ "resource": "resource_value",
+ "policy": policy_pb2.Policy(version=774),
+ "update_mask": field_mask_pb2.FieldMask(paths=["paths_value"]),
+ }
+ )
+ call.assert_called()
+
+
+def test_set_iam_policy_flattened():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.set_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
+
+
+def test_set_iam_policy_flattened_error():
+ client = DataStoreServiceClient(
+ 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.set_iam_policy(
+ iam_policy_pb2.SetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_set_iam_policy_flattened_async():
+ client = DataStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.set_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_set_iam_policy_flattened_error_async():
+ client = DataStoreServiceAsyncClient(
+ 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.set_iam_policy(
+ iam_policy_pb2.SetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+def test_create_data_store_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = DataStoreServiceClient(
+ 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_data_store in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_data_store] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.create_data_store(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_data_store(request)
+
+ # Establish 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_data_store_rest_required_fields(
+ request_type=data_store_service.CreateDataStoreRequest,
+):
+ transport_class = transports.DataStoreServiceRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request_init["data_store_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 "dataStoreId" not in jsonified_request
default_values = getattr(
- transport_class._BaseListDataStores,
- "_BaseListDataStores__REQUIRED_FIELDS_DEFAULT_VALUES",
+ transport_class._BaseCreateDataStore,
+ "_BaseCreateDataStore__REQUIRED_FIELDS_DEFAULT_VALUES",
{},
)
unset_fields = {
@@ -3506,21 +3863,28 @@ def test_list_data_stores_rest_required_fields(
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
+ assert "dataStoreId" in jsonified_request
+ assert jsonified_request["dataStoreId"] == request_init["data_store_id"]
jsonified_request["parent"] = "parent_value"
+ jsonified_request["dataStoreId"] = "data_store_id_value"
# Check that path parameters and body parameters are not mixing in.
assert not set(unset_fields) - set(
(
- "filter",
- "pageSize",
- "pageToken",
+ "cmekConfigName",
+ "createAdvancedSiteSearch",
+ "dataStoreId",
+ "disableCmek",
+ "skipDefaultSchemaCreation",
)
)
# verify required fields with non-default values are left alone
assert "parent" in jsonified_request
assert jsonified_request["parent"] == "parent_value"
+ assert "dataStoreId" in jsonified_request
+ assert jsonified_request["dataStoreId"] == "data_store_id_value"
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3529,7 +3893,7 @@ def test_list_data_stores_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = data_store_service.ListDataStoresResponse()
+ 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
@@ -3541,30 +3905,34 @@ def test_list_data_stores_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 = data_store_service.ListDataStoresResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_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_stores(request)
-
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert sorted(expected_params) == sorted(actual_params)
-
+ response = client.create_data_store(request)
-def test_list_data_stores_rest_flattened():
+ expected_params = [
+ (
+ "dataStoreId",
+ "",
+ ),
+ ("$alt", "json;enum-encoding=int"),
+ ]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_create_data_store_rest_flattened():
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -3573,7 +3941,7 @@ def test_list_data_stores_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 = data_store_service.ListDataStoresResponse()
+ 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"}
@@ -3581,20 +3949,20 @@ def test_list_data_stores_rest_flattened():
# get truthy value for each flattened field
mock_args = dict(
parent="parent_value",
+ data_store=gcd_data_store.DataStore(name="name_value"),
+ data_store_id="data_store_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 = data_store_service.ListDataStoresResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = 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_stores(**mock_args)
+ client.create_data_store(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
@@ -3606,7 +3974,7 @@ def test_list_data_stores_rest_flattened():
)
-def test_list_data_stores_rest_flattened_error(transport: str = "rest"):
+def test_create_data_store_rest_flattened_error(transport: str = "rest"):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -3615,79 +3983,15 @@ def test_list_data_stores_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_stores(
- data_store_service.ListDataStoresRequest(),
+ client.create_data_store(
+ data_store_service.CreateDataStoreRequest(),
parent="parent_value",
+ data_store=gcd_data_store.DataStore(name="name_value"),
+ data_store_id="data_store_id_value",
)
-def test_list_data_stores_rest_pager(transport: str = "rest"):
- client = DataStoreServiceClient(
- 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 = (
- data_store_service.ListDataStoresResponse(
- data_stores=[
- data_store.DataStore(),
- data_store.DataStore(),
- data_store.DataStore(),
- ],
- next_page_token="abc",
- ),
- data_store_service.ListDataStoresResponse(
- data_stores=[],
- next_page_token="def",
- ),
- data_store_service.ListDataStoresResponse(
- data_stores=[
- data_store.DataStore(),
- ],
- next_page_token="ghi",
- ),
- data_store_service.ListDataStoresResponse(
- data_stores=[
- data_store.DataStore(),
- data_store.DataStore(),
- ],
- ),
- )
- # Two responses for two calls
- response = response + response
-
- # Wrap the values into proper Response objs
- response = tuple(
- data_store_service.ListDataStoresResponse.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_stores(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, data_store.DataStore) for i in results)
-
- pages = list(client.list_data_stores(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
-
-
-def test_delete_data_store_rest_use_cached_wrapped_rpc():
+def test_get_data_store_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -3701,36 +4005,30 @@ def test_delete_data_store_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.delete_data_store in client._transport._wrapped_methods
+ assert client._transport.get_data_store in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = 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_data_store] = (
- mock_rpc
- )
+ client._transport._wrapped_methods[client._transport.get_data_store] = mock_rpc
request = {}
- client.delete_data_store(request)
+ client.get_data_store(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_data_store(request)
+ client.get_data_store(request)
# Establish 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_data_store_rest_required_fields(
- request_type=data_store_service.DeleteDataStoreRequest,
+def test_get_data_store_rest_required_fields(
+ request_type=data_store_service.GetDataStoreRequest,
):
transport_class = transports.DataStoreServiceRestTransport
@@ -3745,8 +4043,8 @@ def test_delete_data_store_rest_required_fields(
# verify fields with default values are dropped
default_values = getattr(
- transport_class._BaseDeleteDataStore,
- "_BaseDeleteDataStore__REQUIRED_FIELDS_DEFAULT_VALUES",
+ transport_class._BaseGetDataStore,
+ "_BaseGetDataStore__REQUIRED_FIELDS_DEFAULT_VALUES",
{},
)
unset_fields = {
@@ -3769,7 +4067,7 @@ def test_delete_data_store_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 = data_store.DataStore()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -3781,27 +4079,30 @@ def test_delete_data_store_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 = data_store.DataStore.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_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_data_store(request)
+ response = client.get_data_store(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_data_store_rest_flattened():
+def test_get_data_store_rest_flattened():
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -3810,7 +4111,7 @@ def test_delete_data_store_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 = data_store.DataStore()
# get arguments that satisfy an http rule for this method
sample_request = {
@@ -3826,12 +4127,14 @@ def test_delete_data_store_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 = data_store.DataStore.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = 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_data_store(**mock_args)
+ client.get_data_store(**mock_args)
# Establish that the underlying call was made with the expected
# request object values.
@@ -3843,7 +4146,7 @@ def test_delete_data_store_rest_flattened():
)
-def test_delete_data_store_rest_flattened_error(transport: str = "rest"):
+def test_get_data_store_rest_flattened_error(transport: str = "rest"):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -3852,13 +4155,13 @@ def test_delete_data_store_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_data_store(
- data_store_service.DeleteDataStoreRequest(),
+ client.get_data_store(
+ data_store_service.GetDataStoreRequest(),
name="name_value",
)
-def test_update_data_store_rest_use_cached_wrapped_rpc():
+def test_list_data_stores_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -3872,36 +4175,37 @@ def test_update_data_store_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.update_data_store in client._transport._wrapped_methods
+ assert client._transport.list_data_stores in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = 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_store] = (
+ client._transport._wrapped_methods[client._transport.list_data_stores] = (
mock_rpc
)
request = {}
- client.update_data_store(request)
+ client.list_data_stores(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.update_data_store(request)
+ client.list_data_stores(request)
# Establish 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_store_rest_required_fields(
- request_type=data_store_service.UpdateDataStoreRequest,
+def test_list_data_stores_rest_required_fields(
+ request_type=data_store_service.ListDataStoresRequest,
):
transport_class = transports.DataStoreServiceRestTransport
request_init = {}
+ request_init["parent"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -3911,8 +4215,8 @@ def test_update_data_store_rest_required_fields(
# verify fields with default values are dropped
default_values = getattr(
- transport_class._BaseUpdateDataStore,
- "_BaseUpdateDataStore__REQUIRED_FIELDS_DEFAULT_VALUES",
+ transport_class._BaseListDataStores,
+ "_BaseListDataStores__REQUIRED_FIELDS_DEFAULT_VALUES",
{},
)
unset_fields = {
@@ -3922,10 +4226,20 @@ def test_update_data_store_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",
+ "pageSize",
+ "pageToken",
+ )
+ )
# verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3934,7 +4248,7 @@ def test_update_data_store_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = gcd_data_store.DataStore()
+ return_value = data_store_service.ListDataStoresResponse()
# Mock the http request call within the method and fake a response.
with mock.patch.object(Session, "request") as req:
# We need to mock transcode() because providing default values
@@ -3946,31 +4260,30 @@ def test_update_data_store_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 = gcd_data_store.DataStore.pb(return_value)
+ return_value = data_store_service.ListDataStoresResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_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_store(request)
+ response = client.list_data_stores(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_store_rest_flattened():
+def test_list_data_stores_rest_flattened():
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -3979,19 +4292,14 @@ def test_update_data_store_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 = gcd_data_store.DataStore()
+ return_value = data_store_service.ListDataStoresResponse()
# get arguments that satisfy an http rule for this method
- sample_request = {
- "data_store": {
- "name": "projects/sample1/locations/sample2/dataStores/sample3"
- }
- }
+ sample_request = {"parent": "projects/sample1/locations/sample2"}
# get truthy value for each flattened field
mock_args = dict(
- data_store=gcd_data_store.DataStore(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ parent="parent_value",
)
mock_args.update(sample_request)
@@ -3999,26 +4307,25 @@ def test_update_data_store_rest_flattened():
response_value = Response()
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = gcd_data_store.DataStore.pb(return_value)
+ return_value = data_store_service.ListDataStoresResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = 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_store(**mock_args)
+ client.list_data_stores(**mock_args)
# Establish that the underlying call 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_store.name=projects/*/locations/*/dataStores/*}"
- % client.transport._host,
+ "%s/v1/{parent=projects/*/locations/*}/dataStores" % client.transport._host,
args[1],
)
-def test_update_data_store_rest_flattened_error(transport: str = "rest"):
+def test_list_data_stores_rest_flattened_error(transport: str = "rest"):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -4027,396 +4334,1716 @@ def test_update_data_store_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_data_store(
- data_store_service.UpdateDataStoreRequest(),
- data_store=gcd_data_store.DataStore(name="name_value"),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ client.list_data_stores(
+ data_store_service.ListDataStoresRequest(),
+ parent="parent_value",
)
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.DataStoreServiceGrpcTransport(
+def test_list_data_stores_rest_pager(transport: str = "rest"):
+ client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
)
- with pytest.raises(ValueError):
- client = DataStoreServiceClient(
- 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 = (
+ data_store_service.ListDataStoresResponse(
+ data_stores=[
+ data_store.DataStore(),
+ data_store.DataStore(),
+ data_store.DataStore(),
+ ],
+ next_page_token="abc",
+ ),
+ data_store_service.ListDataStoresResponse(
+ data_stores=[],
+ next_page_token="def",
+ ),
+ data_store_service.ListDataStoresResponse(
+ data_stores=[
+ data_store.DataStore(),
+ ],
+ next_page_token="ghi",
+ ),
+ data_store_service.ListDataStoresResponse(
+ data_stores=[
+ data_store.DataStore(),
+ data_store.DataStore(),
+ ],
+ ),
)
+ # Two responses for two calls
+ response = response + response
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.DataStoreServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = DataStoreServiceClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
+ # Wrap the values into proper Response objs
+ response = tuple(
+ data_store_service.ListDataStoresResponse.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
- # It is an error to provide an api_key and a transport instance.
- transport = transports.DataStoreServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = DataStoreServiceClient(
- client_options=options,
- transport=transport,
- )
+ sample_request = {"parent": "projects/sample1/locations/sample2"}
- # 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 = DataStoreServiceClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
+ pager = client.list_data_stores(request=sample_request)
- # It is an error to provide scopes and a transport instance.
- transport = transports.DataStoreServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
+ 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, data_store.DataStore) for i in results)
+
+ pages = list(client.list_data_stores(request=sample_request).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_delete_data_store_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
client = DataStoreServiceClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.DataStoreServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = DataStoreServiceClient(transport=transport)
- assert client.transport is transport
+ # Ensure method has been cached
+ assert client._transport.delete_data_store in client._transport._wrapped_methods
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_data_store] = (
+ mock_rpc
+ )
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.DataStoreServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
+ request = {}
+ client.delete_data_store(request)
- transport = transports.DataStoreServiceGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
+ # 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.parametrize(
- "transport_class",
- [
- transports.DataStoreServiceGrpcTransport,
- transports.DataStoreServiceGrpcAsyncIOTransport,
- transports.DataStoreServiceRestTransport,
- ],
-)
-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()
+ client.delete_data_store(request)
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
-def test_transport_kind_grpc():
- transport = DataStoreServiceClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
+def test_delete_data_store_rest_required_fields(
+ request_type=data_store_service.DeleteDataStoreRequest,
+):
+ transport_class = transports.DataStoreServiceRestTransport
-def test_initialize_client_w_grpc():
- client = DataStoreServiceClient(
- 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)
)
- assert client is not None
+ # 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_create_data_store_empty_call_grpc():
- client = DataStoreServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ default_values = getattr(
+ transport_class._BaseDeleteDataStore,
+ "_BaseDeleteDataStore__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.create_data_store), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.create_data_store(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 = data_store_service.CreateDataStoreRequest()
- 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_get_data_store_empty_call_grpc():
client = DataStoreServiceClient(
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.get_data_store), "__call__") as call:
- call.return_value = data_store.DataStore()
- client.get_data_store(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = data_store_service.GetDataStoreRequest()
- 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_data_stores_empty_call_grpc():
- client = DataStoreServiceClient(
- 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_stores), "__call__") as call:
- call.return_value = data_store_service.ListDataStoresResponse()
- client.list_data_stores(request=None)
+ response = client.delete_data_store(request)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = data_store_service.ListDataStoresRequest()
- 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_delete_data_store_empty_call_grpc():
+def test_delete_data_store_rest_flattened():
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_data_store), "__call__"
- ) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.delete_data_store(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 = data_store_service.DeleteDataStoreRequest()
- assert args[0] == request_msg
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/dataStores/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_data_store_empty_call_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"}
+
+ client.delete_data_store(**mock_args)
+
+ # Establish that the underlying call 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/*/dataStores/*}" % client.transport._host,
+ args[1],
+ )
+
+
+def test_delete_data_store_rest_flattened_error(transport: str = "rest"):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_data_store), "__call__"
- ) as call:
- call.return_value = gcd_data_store.DataStore()
- client.update_data_store(request=None)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.delete_data_store(
+ data_store_service.DeleteDataStoreRequest(),
+ name="name_value",
+ )
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = data_store_service.UpdateDataStoreRequest()
- assert args[0] == request_msg
+def test_update_data_store_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
-def test_transport_kind_grpc_asyncio():
- transport = DataStoreServiceAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "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.update_data_store in client._transport._wrapped_methods
-def test_initialize_client_w_grpc_asyncio():
- client = DataStoreServiceAsyncClient(
- 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.update_data_store] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.update_data_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_data_store(request)
+
+ # Establish 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_store_rest_required_fields(
+ request_type=data_store_service.UpdateDataStoreRequest,
+):
+ transport_class = transports.DataStoreServiceRestTransport
+
+ 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)
)
- assert client is not None
+ # 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_create_data_store_empty_call_grpc_asyncio():
- client = DataStoreServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+ default_values = getattr(
+ transport_class._BaseUpdateDataStore,
+ "_BaseUpdateDataStore__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.create_data_store), "__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_data_store(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 = data_store_service.CreateDataStoreRequest()
- assert args[0] == request_msg
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("updateMask",))
+ # 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_get_data_store_empty_call_grpc_asyncio():
- client = DataStoreServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+ client = DataStoreServiceClient(
+ 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.get_data_store), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- data_store.DataStore(
- name="name_value",
- display_name="display_name_value",
- industry_vertical=common.IndustryVertical.GENERIC,
- solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION],
- default_schema_id="default_schema_id_value",
- content_config=data_store.DataStore.ContentConfig.NO_CONTENT,
- kms_key_name="kms_key_name_value",
- acl_enabled=True,
- identity_mapping_store="identity_mapping_store_value",
- )
- )
- await client.get_data_store(request=None)
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_data_store.DataStore()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = data_store_service.GetDataStoreRequest()
- assert args[0] == request_msg
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcd_data_store.DataStore.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_list_data_stores_empty_call_grpc_asyncio():
- client = DataStoreServiceAsyncClient(
- 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_data_stores), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- data_store_service.ListDataStoresResponse(
- next_page_token="next_page_token_value",
- )
- )
- await client.list_data_stores(request=None)
+ response = client.update_data_store(request)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = data_store_service.ListDataStoresRequest()
- 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_data_store_empty_call_grpc_asyncio():
- client = DataStoreServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+def test_update_data_store_rest_flattened():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.delete_data_store), "__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 = gcd_data_store.DataStore()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "data_store": {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ data_store=gcd_data_store.DataStore(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
- await client.delete_data_store(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 = data_store_service.DeleteDataStoreRequest()
- 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 = gcd_data_store.DataStore.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_store(**mock_args)
+
+ # Establish that the underlying call 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_store.name=projects/*/locations/*/dataStores/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_update_data_store_rest_flattened_error(transport: str = "rest"):
+ client = DataStoreServiceClient(
+ 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_store(
+ data_store_service.UpdateDataStoreRequest(),
+ data_store=gcd_data_store.DataStore(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_get_iam_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 = DataStoreServiceClient(
+ 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_iam_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_iam_policy] = mock_rpc
+
+ request = {}
+ client.get_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_iam_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_iam_policy_rest_required_fields(
+ request_type=iam_policy_pb2.GetIamPolicyRequest,
+):
+ transport_class = transports.DataStoreServiceRestTransport
+
+ request_init = {}
+ request_init["resource"] = ""
+ request = request_type(**request_init)
+ pb_request = request
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ default_values = getattr(
+ transport_class._BaseGetIamPolicy,
+ "_BaseGetIamPolicy__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["resource"] = "resource_value"
+
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("options",))
+
+ # verify required fields with non-default values are left alone
+ assert "resource" in jsonified_request
+ assert jsonified_request["resource"] == "resource_value"
+
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = policy_pb2.Policy()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.get_iam_policy(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_get_iam_policy_rest_flattened():
+ client = DataStoreServiceClient(
+ 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 = policy_pb2.Policy()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ resource="resource_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.get_iam_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/{resource=projects/*/locations/*/collections/*/dataStores/*}:getIamPolicy"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_iam_policy_rest_flattened_error(transport: str = "rest"):
+ client = DataStoreServiceClient(
+ 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_iam_policy(
+ iam_policy_pb2.GetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+def test_set_iam_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 = DataStoreServiceClient(
+ 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.set_iam_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.set_iam_policy] = mock_rpc
+
+ request = {}
+ client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.set_iam_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_set_iam_policy_rest_required_fields(
+ request_type=iam_policy_pb2.SetIamPolicyRequest,
+):
+ transport_class = transports.DataStoreServiceRestTransport
+
+ request_init = {}
+ request_init["resource"] = ""
+ request = request_type(**request_init)
+ pb_request = request
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ default_values = getattr(
+ transport_class._BaseSetIamPolicy,
+ "_BaseSetIamPolicy__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["resource"] = "resource_value"
+
+ # verify required fields with non-default values are left alone
+ assert "resource" in jsonified_request
+ assert jsonified_request["resource"] == "resource_value"
+
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = policy_pb2.Policy()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "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.set_iam_policy(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_set_iam_policy_rest_flattened():
+ client = DataStoreServiceClient(
+ 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 = policy_pb2.Policy()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ resource="resource_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.set_iam_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/{resource=projects/*/locations/*/collections/*/dataStores/*}:setIamPolicy"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_set_iam_policy_rest_flattened_error(transport: str = "rest"):
+ client = DataStoreServiceClient(
+ 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.set_iam_policy(
+ iam_policy_pb2.SetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.DataStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.DataStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = DataStoreServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.DataStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = DataStoreServiceClient(
+ 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 = DataStoreServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.DataStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = DataStoreServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.DataStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = DataStoreServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.DataStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.DataStoreServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.DataStoreServiceGrpcTransport,
+ transports.DataStoreServiceGrpcAsyncIOTransport,
+ transports.DataStoreServiceRestTransport,
+ ],
+)
+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 = DataStoreServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = DataStoreServiceClient(
+ 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_create_data_store_empty_call_grpc():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_data_store), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.create_data_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.CreateDataStoreRequest()
+ assert args[0] == request_msg
+
+
+# This 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_store_empty_call_grpc():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_data_store), "__call__") as call:
+ call.return_value = data_store.DataStore()
+ client.get_data_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.GetDataStoreRequest()
+ assert args[0] == request_msg
+
+
+# This 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_stores_empty_call_grpc():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call:
+ call.return_value = data_store_service.ListDataStoresResponse()
+ client.list_data_stores(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.ListDataStoresRequest()
+ assert args[0] == request_msg
+
+
+# This 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_data_store_empty_call_grpc():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_data_store), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.delete_data_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.DeleteDataStoreRequest()
+ assert args[0] == request_msg
+
+
+# This 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_store_empty_call_grpc():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_data_store), "__call__"
+ ) as call:
+ call.return_value = gcd_data_store.DataStore()
+ client.update_data_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.UpdateDataStoreRequest()
+ assert args[0] == request_msg
+
+
+# This 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_iam_policy_empty_call_grpc():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.get_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_set_iam_policy_empty_call_grpc():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.set_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = DataStoreServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = DataStoreServiceAsyncClient(
+ 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_create_data_store_empty_call_grpc_asyncio():
+ client = DataStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_data_store), "__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_data_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.CreateDataStoreRequest()
+ assert args[0] == request_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_store_empty_call_grpc_asyncio():
+ client = DataStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_data_store), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ data_store.DataStore(
+ name="name_value",
+ display_name="display_name_value",
+ industry_vertical=common.IndustryVertical.GENERIC,
+ solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION],
+ default_schema_id="default_schema_id_value",
+ content_config=data_store.DataStore.ContentConfig.NO_CONTENT,
+ kms_key_name="kms_key_name_value",
+ acl_enabled=True,
+ identity_mapping_store="identity_mapping_store_value",
+ is_infobot_faq_data_store=True,
+ configurable_billing_approach=data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE,
+ )
+ )
+ await client.get_data_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.GetDataStoreRequest()
+ assert args[0] == request_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_stores_empty_call_grpc_asyncio():
+ client = DataStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_data_stores), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ data_store_service.ListDataStoresResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ await client.list_data_stores(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.ListDataStoresRequest()
+ assert args[0] == request_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_data_store_empty_call_grpc_asyncio():
+ client = DataStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_data_store), "__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_data_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.DeleteDataStoreRequest()
+ assert args[0] == request_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_store_empty_call_grpc_asyncio():
+ client = DataStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_data_store), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_data_store.DataStore(
+ name="name_value",
+ display_name="display_name_value",
+ industry_vertical=common.IndustryVertical.GENERIC,
+ solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION],
+ default_schema_id="default_schema_id_value",
+ content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT,
+ kms_key_name="kms_key_name_value",
+ acl_enabled=True,
+ identity_mapping_store="identity_mapping_store_value",
+ is_infobot_faq_data_store=True,
+ configurable_billing_approach=gcd_data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE,
+ )
+ )
+ await client.update_data_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = data_store_service.UpdateDataStoreRequest()
+ assert args[0] == request_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_iam_policy_empty_call_grpc_asyncio():
+ client = DataStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ await client.get_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request_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_set_iam_policy_empty_call_grpc_asyncio():
+ client = DataStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ await client.set_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = DataStoreServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_create_data_store_rest_bad_request(
+ request_type=data_store_service.CreateDataStoreRequest,
+):
+ client = DataStoreServiceClient(
+ 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_data_store(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ data_store_service.CreateDataStoreRequest,
+ dict,
+ ],
+)
+def test_create_data_store_rest_call_success(request_type):
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request_init["data_store"] = {
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "industry_vertical": 1,
+ "solution_types": [1],
+ "default_schema_id": "default_schema_id_value",
+ "content_config": 1,
+ "create_time": {"seconds": 751, "nanos": 543},
+ "advanced_site_search_config": {
+ "disable_initial_index": True,
+ "disable_automatic_refresh": True,
+ },
+ "natural_language_query_understanding_config": {"mode": 1},
+ "kms_key_name": "kms_key_name_value",
+ "cmek_config": {
+ "name": "name_value",
+ "kms_key": "kms_key_value",
+ "kms_key_version": "kms_key_version_value",
+ "state": 1,
+ "is_default": True,
+ "last_rotation_timestamp_micros": 3234,
+ "single_region_keys": [{"kms_key": "kms_key_value"}],
+ "notebooklm_state": 1,
+ },
+ "billing_estimation": {
+ "structured_data_size": 2152,
+ "unstructured_data_size": 2379,
+ "website_data_size": 1798,
+ "structured_data_update_time": {},
+ "unstructured_data_update_time": {},
+ "website_data_update_time": {},
+ },
+ "acl_enabled": True,
+ "workspace_config": {
+ "type_": 1,
+ "dasher_customer_id": "dasher_customer_id_value",
+ "super_admin_service_account": "super_admin_service_account_value",
+ "super_admin_email_address": "super_admin_email_address_value",
+ },
+ "document_processing_config": {
+ "name": "name_value",
+ "chunking_config": {
+ "layout_based_chunking_config": {
+ "chunk_size": 1075,
+ "include_ancestor_headings": True,
+ }
+ },
+ "default_parsing_config": {
+ "digital_parsing_config": {},
+ "ocr_parsing_config": {
+ "enhanced_document_elements": [
+ "enhanced_document_elements_value1",
+ "enhanced_document_elements_value2",
+ ],
+ "use_native_text": True,
+ },
+ "layout_parsing_config": {
+ "enable_table_annotation": True,
+ "enable_image_annotation": True,
+ "enable_llm_layout_parsing": True,
+ "structured_content_types": [
+ "structured_content_types_value1",
+ "structured_content_types_value2",
+ ],
+ "exclude_html_elements": [
+ "exclude_html_elements_value1",
+ "exclude_html_elements_value2",
+ ],
+ "exclude_html_classes": [
+ "exclude_html_classes_value1",
+ "exclude_html_classes_value2",
+ ],
+ "exclude_html_ids": [
+ "exclude_html_ids_value1",
+ "exclude_html_ids_value2",
+ ],
+ "enable_get_processed_document": True,
+ },
+ },
+ "parsing_config_overrides": {},
+ },
+ "starting_schema": {
+ "struct_schema": {"fields": {}},
+ "json_schema": "json_schema_value",
+ "name": "name_value",
+ },
+ "healthcare_fhir_config": {
+ "enable_configurable_schema": True,
+ "enable_static_indexing_for_batch_ingestion": True,
+ "initial_filter_groups": [
+ "initial_filter_groups_value1",
+ "initial_filter_groups_value2",
+ ],
+ },
+ "serving_config_data_store": {"disabled_for_serving": True},
+ "identity_mapping_store": "identity_mapping_store_value",
+ "is_infobot_faq_data_store": True,
+ "federated_search_config": {
+ "alloy_db_config": {
+ "alloydb_connection_config": {
+ "instance": "instance_value",
+ "database": "database_value",
+ "user": "user_value",
+ "password": "password_value",
+ "auth_mode": 1,
+ "enable_psvs": True,
+ },
+ "alloydb_ai_nl_config": {"nl_config_id": "nl_config_id_value"},
+ "returned_fields": ["returned_fields_value1", "returned_fields_value2"],
+ },
+ "third_party_oauth_config": {
+ "app_name": "app_name_value",
+ "instance_name": "instance_name_value",
+ },
+ "notebooklm_config": {
+ "search_config": "search_config_value",
+ "notebooks": ["notebooks_value1", "notebooks_value2"],
+ },
+ },
+ "configurable_billing_approach": 1,
+ "configurable_billing_approach_update_time": {},
+ "data_protection_policy": {
+ "sensitive_data_protection_policy": {"policy": "policy_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 = data_store_service.CreateDataStoreRequest.meta.fields["data_store"]
+
+ 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_store"].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_store"][field])):
+ del request_init["data_store"][field][i][subfield]
+ else:
+ del request_init["data_store"][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_data_store(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_data_store_rest_interceptors(null_interceptor):
+ transport = transports.DataStoreServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.DataStoreServiceRestInterceptor(),
+ )
+ client = DataStoreServiceClient(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.DataStoreServiceRestInterceptor, "post_create_data_store"
+ ) as post,
+ mock.patch.object(
+ transports.DataStoreServiceRestInterceptor,
+ "post_create_data_store_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.DataStoreServiceRestInterceptor, "pre_create_data_store"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = data_store_service.CreateDataStoreRequest.pb(
+ data_store_service.CreateDataStoreRequest()
+ )
+ 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 = data_store_service.CreateDataStoreRequest()
+ 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_data_store(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_get_data_store_rest_bad_request(
+ request_type=data_store_service.GetDataStoreRequest,
+):
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/dataStores/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_data_store(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ data_store_service.GetDataStoreRequest,
+ dict,
+ ],
+)
+def test_get_data_store_rest_call_success(request_type):
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/dataStores/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 = data_store.DataStore(
+ name="name_value",
+ display_name="display_name_value",
+ industry_vertical=common.IndustryVertical.GENERIC,
+ solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION],
+ default_schema_id="default_schema_id_value",
+ content_config=data_store.DataStore.ContentConfig.NO_CONTENT,
+ kms_key_name="kms_key_name_value",
+ acl_enabled=True,
+ identity_mapping_store="identity_mapping_store_value",
+ is_infobot_faq_data_store=True,
+ configurable_billing_approach=data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE,
+ )
+
+ # 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 = data_store.DataStore.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_store(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, data_store.DataStore)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION]
+ assert response.default_schema_id == "default_schema_id_value"
+ assert response.content_config == data_store.DataStore.ContentConfig.NO_CONTENT
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.acl_enabled is True
+ assert response.identity_mapping_store == "identity_mapping_store_value"
+ assert response.is_infobot_faq_data_store is True
+ assert (
+ response.configurable_billing_approach
+ == data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE
+ )
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_data_store_rest_interceptors(null_interceptor):
+ transport = transports.DataStoreServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.DataStoreServiceRestInterceptor(),
+ )
+ client = DataStoreServiceClient(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.DataStoreServiceRestInterceptor, "post_get_data_store"
+ ) as post,
+ mock.patch.object(
+ transports.DataStoreServiceRestInterceptor,
+ "post_get_data_store_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.DataStoreServiceRestInterceptor, "pre_get_data_store"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = data_store_service.GetDataStoreRequest.pb(
+ data_store_service.GetDataStoreRequest()
+ )
+ 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 = data_store.DataStore.to_json(data_store.DataStore())
+ req.return_value.content = 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_data_store_empty_call_grpc_asyncio():
- client = DataStoreServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
+ request = data_store_service.GetDataStoreRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = data_store.DataStore()
+ post_with_metadata.return_value = data_store.DataStore(), metadata
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_data_store), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcd_data_store.DataStore(
- name="name_value",
- display_name="display_name_value",
- industry_vertical=common.IndustryVertical.GENERIC,
- solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION],
- default_schema_id="default_schema_id_value",
- content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT,
- kms_key_name="kms_key_name_value",
- acl_enabled=True,
- identity_mapping_store="identity_mapping_store_value",
- )
+ client.get_data_store(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
)
- await client.update_data_store(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = data_store_service.UpdateDataStoreRequest()
- assert args[0] == request_msg
-
-def test_transport_kind_rest():
- transport = DataStoreServiceClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
-def test_create_data_store_rest_bad_request(
- request_type=data_store_service.CreateDataStoreRequest,
+def test_list_data_stores_rest_bad_request(
+ request_type=data_store_service.ListDataStoresRequest,
):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
@@ -4438,202 +6065,51 @@ def test_create_data_store_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_data_store(request)
+ client.list_data_stores(request)
@pytest.mark.parametrize(
"request_type",
[
- data_store_service.CreateDataStoreRequest,
+ data_store_service.ListDataStoresRequest,
dict,
],
)
-def test_create_data_store_rest_call_success(request_type):
+def test_list_data_stores_rest_call_success(request_type):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
request_init = {"parent": "projects/sample1/locations/sample2"}
- request_init["data_store"] = {
- "name": "name_value",
- "display_name": "display_name_value",
- "industry_vertical": 1,
- "solution_types": [1],
- "default_schema_id": "default_schema_id_value",
- "content_config": 1,
- "create_time": {"seconds": 751, "nanos": 543},
- "advanced_site_search_config": {
- "disable_initial_index": True,
- "disable_automatic_refresh": True,
- },
- "natural_language_query_understanding_config": {"mode": 1},
- "kms_key_name": "kms_key_name_value",
- "cmek_config": {
- "name": "name_value",
- "kms_key": "kms_key_value",
- "kms_key_version": "kms_key_version_value",
- "state": 1,
- "is_default": True,
- "last_rotation_timestamp_micros": 3234,
- "single_region_keys": [{"kms_key": "kms_key_value"}],
- "notebooklm_state": 1,
- },
- "billing_estimation": {
- "structured_data_size": 2152,
- "unstructured_data_size": 2379,
- "website_data_size": 1798,
- "structured_data_update_time": {},
- "unstructured_data_update_time": {},
- "website_data_update_time": {},
- },
- "acl_enabled": True,
- "workspace_config": {
- "type_": 1,
- "dasher_customer_id": "dasher_customer_id_value",
- "super_admin_service_account": "super_admin_service_account_value",
- "super_admin_email_address": "super_admin_email_address_value",
- },
- "document_processing_config": {
- "name": "name_value",
- "chunking_config": {
- "layout_based_chunking_config": {
- "chunk_size": 1075,
- "include_ancestor_headings": True,
- }
- },
- "default_parsing_config": {
- "digital_parsing_config": {},
- "ocr_parsing_config": {
- "enhanced_document_elements": [
- "enhanced_document_elements_value1",
- "enhanced_document_elements_value2",
- ],
- "use_native_text": True,
- },
- "layout_parsing_config": {
- "enable_table_annotation": True,
- "enable_image_annotation": True,
- "structured_content_types": [
- "structured_content_types_value1",
- "structured_content_types_value2",
- ],
- "exclude_html_elements": [
- "exclude_html_elements_value1",
- "exclude_html_elements_value2",
- ],
- "exclude_html_classes": [
- "exclude_html_classes_value1",
- "exclude_html_classes_value2",
- ],
- "exclude_html_ids": [
- "exclude_html_ids_value1",
- "exclude_html_ids_value2",
- ],
- },
- },
- "parsing_config_overrides": {},
- },
- "starting_schema": {
- "struct_schema": {"fields": {}},
- "json_schema": "json_schema_value",
- "name": "name_value",
- },
- "healthcare_fhir_config": {
- "enable_configurable_schema": True,
- "enable_static_indexing_for_batch_ingestion": True,
- },
- "identity_mapping_store": "identity_mapping_store_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 = data_store_service.CreateDataStoreRequest.meta.fields["data_store"]
-
- 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_store"].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_store"][field])):
- del request_init["data_store"][field][i][subfield]
- else:
- del request_init["data_store"][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 = data_store_service.ListDataStoresResponse(
+ 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 = data_store_service.ListDataStoresResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_data_store(request)
+ response = client.list_data_stores(request)
# Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ assert isinstance(response, pagers.ListDataStoresPager)
+ assert response.next_page_token == "next_page_token_value"
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_data_store_rest_interceptors(null_interceptor):
+def test_list_data_stores_rest_interceptors(null_interceptor):
transport = transports.DataStoreServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -4645,23 +6121,22 @@ def test_create_data_store_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.DataStoreServiceRestInterceptor, "post_create_data_store"
+ transports.DataStoreServiceRestInterceptor, "post_list_data_stores"
) as post,
mock.patch.object(
transports.DataStoreServiceRestInterceptor,
- "post_create_data_store_with_metadata",
+ "post_list_data_stores_with_metadata",
) as post_with_metadata,
mock.patch.object(
- transports.DataStoreServiceRestInterceptor, "pre_create_data_store"
+ transports.DataStoreServiceRestInterceptor, "pre_list_data_stores"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = data_store_service.CreateDataStoreRequest.pb(
- data_store_service.CreateDataStoreRequest()
+ pb_message = data_store_service.ListDataStoresRequest.pb(
+ data_store_service.ListDataStoresRequest()
)
transcode.return_value = {
"method": "post",
@@ -4673,19 +6148,24 @@ def test_create_data_store_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 = data_store_service.ListDataStoresResponse.to_json(
+ data_store_service.ListDataStoresResponse()
+ )
req.return_value.content = return_value
- request = data_store_service.CreateDataStoreRequest()
+ request = data_store_service.ListDataStoresRequest()
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 = data_store_service.ListDataStoresResponse()
+ post_with_metadata.return_value = (
+ data_store_service.ListDataStoresResponse(),
+ metadata,
+ )
- client.create_data_store(
+ client.list_data_stores(
request,
metadata=[
("key", "val"),
@@ -4698,8 +6178,8 @@ def test_create_data_store_rest_interceptors(null_interceptor):
post_with_metadata.assert_called_once()
-def test_get_data_store_rest_bad_request(
- request_type=data_store_service.GetDataStoreRequest,
+def test_delete_data_store_rest_bad_request(
+ request_type=data_store_service.DeleteDataStoreRequest,
):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
@@ -4721,17 +6201,17 @@ def test_get_data_store_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_store(request)
+ client.delete_data_store(request)
@pytest.mark.parametrize(
"request_type",
[
- data_store_service.GetDataStoreRequest,
+ data_store_service.DeleteDataStoreRequest,
dict,
],
)
-def test_get_data_store_rest_call_success(request_type):
+def test_delete_data_store_rest_call_success(request_type):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
@@ -4743,45 +6223,23 @@ def test_get_data_store_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 = data_store.DataStore(
- name="name_value",
- display_name="display_name_value",
- industry_vertical=common.IndustryVertical.GENERIC,
- solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION],
- default_schema_id="default_schema_id_value",
- content_config=data_store.DataStore.ContentConfig.NO_CONTENT,
- kms_key_name="kms_key_name_value",
- acl_enabled=True,
- identity_mapping_store="identity_mapping_store_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 = data_store.DataStore.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_store(request)
+ response = client.delete_data_store(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, data_store.DataStore)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.industry_vertical == common.IndustryVertical.GENERIC
- assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION]
- assert response.default_schema_id == "default_schema_id_value"
- assert response.content_config == data_store.DataStore.ContentConfig.NO_CONTENT
- assert response.kms_key_name == "kms_key_name_value"
- assert response.acl_enabled is True
- assert response.identity_mapping_store == "identity_mapping_store_value"
+ json_return_value = json_format.MessageToJson(return_value)
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_data_store_rest_interceptors(null_interceptor):
+def test_delete_data_store_rest_interceptors(null_interceptor):
transport = transports.DataStoreServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -4793,22 +6251,23 @@ def test_get_data_store_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.DataStoreServiceRestInterceptor, "post_get_data_store"
+ transports.DataStoreServiceRestInterceptor, "post_delete_data_store"
) as post,
mock.patch.object(
transports.DataStoreServiceRestInterceptor,
- "post_get_data_store_with_metadata",
+ "post_delete_data_store_with_metadata",
) as post_with_metadata,
mock.patch.object(
- transports.DataStoreServiceRestInterceptor, "pre_get_data_store"
+ transports.DataStoreServiceRestInterceptor, "pre_delete_data_store"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = data_store_service.GetDataStoreRequest.pb(
- data_store_service.GetDataStoreRequest()
+ pb_message = data_store_service.DeleteDataStoreRequest.pb(
+ data_store_service.DeleteDataStoreRequest()
)
transcode.return_value = {
"method": "post",
@@ -4820,19 +6279,19 @@ def test_get_data_store_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 = data_store.DataStore.to_json(data_store.DataStore())
+ return_value = json_format.MessageToJson(operations_pb2.Operation())
req.return_value.content = return_value
- request = data_store_service.GetDataStoreRequest()
+ request = data_store_service.DeleteDataStoreRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = data_store.DataStore()
- post_with_metadata.return_value = data_store.DataStore(), metadata
+ post.return_value = operations_pb2.Operation()
+ post_with_metadata.return_value = operations_pb2.Operation(), metadata
- client.get_data_store(
+ client.delete_data_store(
request,
metadata=[
("key", "val"),
@@ -4845,14 +6304,16 @@ def test_get_data_store_rest_interceptors(null_interceptor):
post_with_metadata.assert_called_once()
-def test_list_data_stores_rest_bad_request(
- request_type=data_store_service.ListDataStoresRequest,
+def test_update_data_store_rest_bad_request(
+ request_type=data_store_service.UpdateDataStoreRequest,
):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
+ request_init = {
+ "data_store": {"name": "projects/sample1/locations/sample2/dataStores/sample3"}
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -4868,30 +6329,234 @@ def test_list_data_stores_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_stores(request)
+ client.update_data_store(request)
@pytest.mark.parametrize(
"request_type",
[
- data_store_service.ListDataStoresRequest,
+ data_store_service.UpdateDataStoreRequest,
dict,
],
)
-def test_list_data_stores_rest_call_success(request_type):
+def test_update_data_store_rest_call_success(request_type):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2"}
+ request_init = {
+ "data_store": {"name": "projects/sample1/locations/sample2/dataStores/sample3"}
+ }
+ request_init["data_store"] = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3",
+ "display_name": "display_name_value",
+ "industry_vertical": 1,
+ "solution_types": [1],
+ "default_schema_id": "default_schema_id_value",
+ "content_config": 1,
+ "create_time": {"seconds": 751, "nanos": 543},
+ "advanced_site_search_config": {
+ "disable_initial_index": True,
+ "disable_automatic_refresh": True,
+ },
+ "natural_language_query_understanding_config": {"mode": 1},
+ "kms_key_name": "kms_key_name_value",
+ "cmek_config": {
+ "name": "name_value",
+ "kms_key": "kms_key_value",
+ "kms_key_version": "kms_key_version_value",
+ "state": 1,
+ "is_default": True,
+ "last_rotation_timestamp_micros": 3234,
+ "single_region_keys": [{"kms_key": "kms_key_value"}],
+ "notebooklm_state": 1,
+ },
+ "billing_estimation": {
+ "structured_data_size": 2152,
+ "unstructured_data_size": 2379,
+ "website_data_size": 1798,
+ "structured_data_update_time": {},
+ "unstructured_data_update_time": {},
+ "website_data_update_time": {},
+ },
+ "acl_enabled": True,
+ "workspace_config": {
+ "type_": 1,
+ "dasher_customer_id": "dasher_customer_id_value",
+ "super_admin_service_account": "super_admin_service_account_value",
+ "super_admin_email_address": "super_admin_email_address_value",
+ },
+ "document_processing_config": {
+ "name": "name_value",
+ "chunking_config": {
+ "layout_based_chunking_config": {
+ "chunk_size": 1075,
+ "include_ancestor_headings": True,
+ }
+ },
+ "default_parsing_config": {
+ "digital_parsing_config": {},
+ "ocr_parsing_config": {
+ "enhanced_document_elements": [
+ "enhanced_document_elements_value1",
+ "enhanced_document_elements_value2",
+ ],
+ "use_native_text": True,
+ },
+ "layout_parsing_config": {
+ "enable_table_annotation": True,
+ "enable_image_annotation": True,
+ "enable_llm_layout_parsing": True,
+ "structured_content_types": [
+ "structured_content_types_value1",
+ "structured_content_types_value2",
+ ],
+ "exclude_html_elements": [
+ "exclude_html_elements_value1",
+ "exclude_html_elements_value2",
+ ],
+ "exclude_html_classes": [
+ "exclude_html_classes_value1",
+ "exclude_html_classes_value2",
+ ],
+ "exclude_html_ids": [
+ "exclude_html_ids_value1",
+ "exclude_html_ids_value2",
+ ],
+ "enable_get_processed_document": True,
+ },
+ },
+ "parsing_config_overrides": {},
+ },
+ "starting_schema": {
+ "struct_schema": {"fields": {}},
+ "json_schema": "json_schema_value",
+ "name": "name_value",
+ },
+ "healthcare_fhir_config": {
+ "enable_configurable_schema": True,
+ "enable_static_indexing_for_batch_ingestion": True,
+ "initial_filter_groups": [
+ "initial_filter_groups_value1",
+ "initial_filter_groups_value2",
+ ],
+ },
+ "serving_config_data_store": {"disabled_for_serving": True},
+ "identity_mapping_store": "identity_mapping_store_value",
+ "is_infobot_faq_data_store": True,
+ "federated_search_config": {
+ "alloy_db_config": {
+ "alloydb_connection_config": {
+ "instance": "instance_value",
+ "database": "database_value",
+ "user": "user_value",
+ "password": "password_value",
+ "auth_mode": 1,
+ "enable_psvs": True,
+ },
+ "alloydb_ai_nl_config": {"nl_config_id": "nl_config_id_value"},
+ "returned_fields": ["returned_fields_value1", "returned_fields_value2"],
+ },
+ "third_party_oauth_config": {
+ "app_name": "app_name_value",
+ "instance_name": "instance_name_value",
+ },
+ "notebooklm_config": {
+ "search_config": "search_config_value",
+ "notebooks": ["notebooks_value1", "notebooks_value2"],
+ },
+ },
+ "configurable_billing_approach": 1,
+ "configurable_billing_approach_update_time": {},
+ "data_protection_policy": {
+ "sensitive_data_protection_policy": {"policy": "policy_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 = data_store_service.UpdateDataStoreRequest.meta.fields["data_store"]
+
+ 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_store"].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_store"][field])):
+ del request_init["data_store"][field][i][subfield]
+ else:
+ del request_init["data_store"][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 = data_store_service.ListDataStoresResponse(
- next_page_token="next_page_token_value",
+ return_value = gcd_data_store.DataStore(
+ name="name_value",
+ display_name="display_name_value",
+ industry_vertical=common.IndustryVertical.GENERIC,
+ solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION],
+ default_schema_id="default_schema_id_value",
+ content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT,
+ kms_key_name="kms_key_name_value",
+ acl_enabled=True,
+ identity_mapping_store="identity_mapping_store_value",
+ is_infobot_faq_data_store=True,
+ configurable_billing_approach=gcd_data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE,
)
# Wrap the value into a proper Response obj
@@ -4899,20 +6564,33 @@ def test_list_data_stores_rest_call_success(request_type):
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = data_store_service.ListDataStoresResponse.pb(return_value)
+ return_value = gcd_data_store.DataStore.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_stores(request)
+ response = client.update_data_store(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListDataStoresPager)
- assert response.next_page_token == "next_page_token_value"
+ assert isinstance(response, gcd_data_store.DataStore)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION]
+ assert response.default_schema_id == "default_schema_id_value"
+ assert response.content_config == gcd_data_store.DataStore.ContentConfig.NO_CONTENT
+ assert response.kms_key_name == "kms_key_name_value"
+ assert response.acl_enabled is True
+ assert response.identity_mapping_store == "identity_mapping_store_value"
+ assert response.is_infobot_faq_data_store is True
+ assert (
+ response.configurable_billing_approach
+ == gcd_data_store.DataStore.ConfigurableBillingApproach.CONFIGURABLE_SUBSCRIPTION_INDEXING_CORE
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_data_stores_rest_interceptors(null_interceptor):
+def test_update_data_store_rest_interceptors(null_interceptor):
transport = transports.DataStoreServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -4925,21 +6603,21 @@ def test_list_data_stores_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.DataStoreServiceRestInterceptor, "post_list_data_stores"
+ transports.DataStoreServiceRestInterceptor, "post_update_data_store"
) as post,
mock.patch.object(
transports.DataStoreServiceRestInterceptor,
- "post_list_data_stores_with_metadata",
+ "post_update_data_store_with_metadata",
) as post_with_metadata,
mock.patch.object(
- transports.DataStoreServiceRestInterceptor, "pre_list_data_stores"
+ transports.DataStoreServiceRestInterceptor, "pre_update_data_store"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = data_store_service.ListDataStoresRequest.pb(
- data_store_service.ListDataStoresRequest()
+ pb_message = data_store_service.UpdateDataStoreRequest.pb(
+ data_store_service.UpdateDataStoreRequest()
)
transcode.return_value = {
"method": "post",
@@ -4951,24 +6629,19 @@ def test_list_data_stores_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 = data_store_service.ListDataStoresResponse.to_json(
- data_store_service.ListDataStoresResponse()
- )
+ return_value = gcd_data_store.DataStore.to_json(gcd_data_store.DataStore())
req.return_value.content = return_value
- request = data_store_service.ListDataStoresRequest()
+ request = data_store_service.UpdateDataStoreRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = data_store_service.ListDataStoresResponse()
- post_with_metadata.return_value = (
- data_store_service.ListDataStoresResponse(),
- metadata,
- )
+ post.return_value = gcd_data_store.DataStore()
+ post_with_metadata.return_value = gcd_data_store.DataStore(), metadata
- client.list_data_stores(
+ client.update_data_store(
request,
metadata=[
("key", "val"),
@@ -4981,14 +6654,16 @@ def test_list_data_stores_rest_interceptors(null_interceptor):
post_with_metadata.assert_called_once()
-def test_delete_data_store_rest_bad_request(
- request_type=data_store_service.DeleteDataStoreRequest,
+def test_get_iam_policy_rest_bad_request(
+ request_type=iam_policy_pb2.GetIamPolicyRequest,
):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/dataStores/sample3"}
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4"
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -5004,29 +6679,34 @@ def test_delete_data_store_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_data_store(request)
+ client.get_iam_policy(request)
@pytest.mark.parametrize(
"request_type",
[
- data_store_service.DeleteDataStoreRequest,
+ iam_policy_pb2.GetIamPolicyRequest,
dict,
],
)
-def test_delete_data_store_rest_call_success(request_type):
+def test_get_iam_policy_rest_call_success(request_type):
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
- request_init = {"name": "projects/sample1/locations/sample2/dataStores/sample3"}
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/dataStores/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 = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
# Wrap the value into a proper Response obj
response_value = mock.Mock()
@@ -5035,14 +6715,16 @@ def test_delete_data_store_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_data_store(request)
+ response = client.get_iam_policy(request)
# Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_data_store_rest_interceptors(null_interceptor):
+def test_get_iam_policy_rest_interceptors(null_interceptor):
transport = transports.DataStoreServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -5054,304 +6736,127 @@ def test_delete_data_store_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.DataStoreServiceRestInterceptor, "post_delete_data_store"
+ transports.DataStoreServiceRestInterceptor, "post_get_iam_policy"
) as post,
mock.patch.object(
transports.DataStoreServiceRestInterceptor,
- "post_delete_data_store_with_metadata",
+ "post_get_iam_policy_with_metadata",
) as post_with_metadata,
mock.patch.object(
- transports.DataStoreServiceRestInterceptor, "pre_delete_data_store"
+ transports.DataStoreServiceRestInterceptor, "pre_get_iam_policy"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = data_store_service.DeleteDataStoreRequest.pb(
- data_store_service.DeleteDataStoreRequest()
- )
+ pb_message = iam_policy_pb2.GetIamPolicyRequest()
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 = data_store_service.DeleteDataStoreRequest()
- 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_data_store(
- request,
- metadata=[
- ("key", "val"),
- ("cephalopod", "squid"),
- ],
- )
-
- pre.assert_called_once()
- post.assert_called_once()
- post_with_metadata.assert_called_once()
-
-
-def test_update_data_store_rest_bad_request(
- request_type=data_store_service.UpdateDataStoreRequest,
-):
- client = DataStoreServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
- # send a request that will satisfy transcoding
- request_init = {
- "data_store": {"name": "projects/sample1/locations/sample2/dataStores/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_data_store(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- data_store_service.UpdateDataStoreRequest,
- dict,
- ],
-)
-def test_update_data_store_rest_call_success(request_type):
- client = DataStoreServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "data_store": {"name": "projects/sample1/locations/sample2/dataStores/sample3"}
- }
- request_init["data_store"] = {
- "name": "projects/sample1/locations/sample2/dataStores/sample3",
- "display_name": "display_name_value",
- "industry_vertical": 1,
- "solution_types": [1],
- "default_schema_id": "default_schema_id_value",
- "content_config": 1,
- "create_time": {"seconds": 751, "nanos": 543},
- "advanced_site_search_config": {
- "disable_initial_index": True,
- "disable_automatic_refresh": True,
- },
- "natural_language_query_understanding_config": {"mode": 1},
- "kms_key_name": "kms_key_name_value",
- "cmek_config": {
- "name": "name_value",
- "kms_key": "kms_key_value",
- "kms_key_version": "kms_key_version_value",
- "state": 1,
- "is_default": True,
- "last_rotation_timestamp_micros": 3234,
- "single_region_keys": [{"kms_key": "kms_key_value"}],
- "notebooklm_state": 1,
- },
- "billing_estimation": {
- "structured_data_size": 2152,
- "unstructured_data_size": 2379,
- "website_data_size": 1798,
- "structured_data_update_time": {},
- "unstructured_data_update_time": {},
- "website_data_update_time": {},
- },
- "acl_enabled": True,
- "workspace_config": {
- "type_": 1,
- "dasher_customer_id": "dasher_customer_id_value",
- "super_admin_service_account": "super_admin_service_account_value",
- "super_admin_email_address": "super_admin_email_address_value",
- },
- "document_processing_config": {
- "name": "name_value",
- "chunking_config": {
- "layout_based_chunking_config": {
- "chunk_size": 1075,
- "include_ancestor_headings": True,
- }
- },
- "default_parsing_config": {
- "digital_parsing_config": {},
- "ocr_parsing_config": {
- "enhanced_document_elements": [
- "enhanced_document_elements_value1",
- "enhanced_document_elements_value2",
- ],
- "use_native_text": True,
- },
- "layout_parsing_config": {
- "enable_table_annotation": True,
- "enable_image_annotation": True,
- "structured_content_types": [
- "structured_content_types_value1",
- "structured_content_types_value2",
- ],
- "exclude_html_elements": [
- "exclude_html_elements_value1",
- "exclude_html_elements_value2",
- ],
- "exclude_html_classes": [
- "exclude_html_classes_value1",
- "exclude_html_classes_value2",
- ],
- "exclude_html_ids": [
- "exclude_html_ids_value1",
- "exclude_html_ids_value2",
- ],
- },
- },
- "parsing_config_overrides": {},
- },
- "starting_schema": {
- "struct_schema": {"fields": {}},
- "json_schema": "json_schema_value",
- "name": "name_value",
- },
- "healthcare_fhir_config": {
- "enable_configurable_schema": True,
- "enable_static_indexing_for_batch_ingestion": True,
- },
- "identity_mapping_store": "identity_mapping_store_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
+ "body": pb_message,
+ "query_params": pb_message,
+ }
- # Determine if the message type is proto-plus or protobuf
- test_field = data_store_service.UpdateDataStoreRequest.meta.fields["data_store"]
+ req.return_value = mock.Mock()
+ req.return_value.status_code = 200
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ return_value = json_format.MessageToJson(policy_pb2.Policy())
+ req.return_value.content = return_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 = []
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = policy_pb2.Policy()
+ post_with_metadata.return_value = policy_pb2.Policy(), metadata
- if hasattr(field, "message") and field.message:
- is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR")
+ client.get_iam_policy(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
- 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
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
- 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 = []
+def test_set_iam_policy_rest_bad_request(
+ request_type=iam_policy_pb2.SetIamPolicyRequest,
+):
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/dataStores/sample4"
+ }
+ request = request_type(**request_init)
- # 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_store"].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
+ # 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.set_iam_policy(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["data_store"][field])):
- del request_init["data_store"][field][i][subfield]
- else:
- del request_init["data_store"][field][subfield]
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.SetIamPolicyRequest,
+ dict,
+ ],
+)
+def test_set_iam_policy_rest_call_success(request_type):
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/dataStores/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 = gcd_data_store.DataStore(
- name="name_value",
- display_name="display_name_value",
- industry_vertical=common.IndustryVertical.GENERIC,
- solution_types=[common.SolutionType.SOLUTION_TYPE_RECOMMENDATION],
- default_schema_id="default_schema_id_value",
- content_config=gcd_data_store.DataStore.ContentConfig.NO_CONTENT,
- kms_key_name="kms_key_name_value",
- acl_enabled=True,
- identity_mapping_store="identity_mapping_store_value",
+ return_value = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
)
# Wrap the value into a proper Response obj
response_value = mock.Mock()
response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = gcd_data_store.DataStore.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_store(request)
+ response = client.set_iam_policy(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, gcd_data_store.DataStore)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.industry_vertical == common.IndustryVertical.GENERIC
- assert response.solution_types == [common.SolutionType.SOLUTION_TYPE_RECOMMENDATION]
- assert response.default_schema_id == "default_schema_id_value"
- assert response.content_config == gcd_data_store.DataStore.ContentConfig.NO_CONTENT
- assert response.kms_key_name == "kms_key_name_value"
- assert response.acl_enabled is True
- assert response.identity_mapping_store == "identity_mapping_store_value"
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_data_store_rest_interceptors(null_interceptor):
+def test_set_iam_policy_rest_interceptors(null_interceptor):
transport = transports.DataStoreServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -5364,22 +6869,20 @@ def test_update_data_store_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.DataStoreServiceRestInterceptor, "post_update_data_store"
+ transports.DataStoreServiceRestInterceptor, "post_set_iam_policy"
) as post,
mock.patch.object(
transports.DataStoreServiceRestInterceptor,
- "post_update_data_store_with_metadata",
+ "post_set_iam_policy_with_metadata",
) as post_with_metadata,
mock.patch.object(
- transports.DataStoreServiceRestInterceptor, "pre_update_data_store"
+ transports.DataStoreServiceRestInterceptor, "pre_set_iam_policy"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = data_store_service.UpdateDataStoreRequest.pb(
- data_store_service.UpdateDataStoreRequest()
- )
+ pb_message = iam_policy_pb2.SetIamPolicyRequest()
transcode.return_value = {
"method": "post",
"uri": "my_uri",
@@ -5390,19 +6893,19 @@ def test_update_data_store_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 = gcd_data_store.DataStore.to_json(gcd_data_store.DataStore())
+ return_value = json_format.MessageToJson(policy_pb2.Policy())
req.return_value.content = return_value
- request = data_store_service.UpdateDataStoreRequest()
+ request = iam_policy_pb2.SetIamPolicyRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = gcd_data_store.DataStore()
- post_with_metadata.return_value = gcd_data_store.DataStore(), metadata
+ post.return_value = policy_pb2.Policy()
+ post_with_metadata.return_value = policy_pb2.Policy(), metadata
- client.update_data_store(
+ client.set_iam_policy(
request,
metadata=[
("key", "val"),
@@ -5710,6 +7213,44 @@ def test_update_data_store_empty_call_rest():
assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_iam_policy_empty_call_rest():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ client.get_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_set_iam_policy_empty_call_rest():
+ client = DataStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ client.set_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
def test_data_store_service_rest_lro_client():
client = DataStoreServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5765,6 +7306,8 @@ def test_data_store_service_base_transport():
"list_data_stores",
"delete_data_store",
"update_data_store",
+ "get_iam_policy",
+ "set_iam_policy",
"get_operation",
"cancel_operation",
"list_operations",
@@ -5809,7 +7352,11 @@ def test_data_store_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5835,7 +7382,11 @@ def test_data_store_service_auth_adc():
DataStoreServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -5855,7 +7406,11 @@ def test_data_store_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5908,7 +7463,11 @@ def test_data_store_service_transport_create_channel(transport_class, grpc_helpe
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -6053,6 +7612,12 @@ def test_data_store_service_client_transport_session_collision(transport_name):
session1 = client1.transport.update_data_store._session
session2 = client2.transport.update_data_store._session
assert session1 != session2
+ session1 = client1.transport.get_iam_policy._session
+ session2 = client2.transport.get_iam_policy._session
+ assert session1 != session2
+ session1 = client1.transport.set_iam_policy._session
+ session2 = client2.transport.set_iam_policy._session
+ assert session1 != session2
def test_data_store_service_grpc_transport_channel():
@@ -6267,11 +7832,39 @@ def test_parse_collection_path():
assert expected == actual
-def test_crypto_keys_path():
- project = "scallop"
+def test_content_policy_path():
+ organization = "scallop"
location = "abalone"
- key_ring = "squid"
- crypto_key = "clam"
+ content_policy = "squid"
+ expected = "organizations/{organization}/locations/{location}/contentPolicies/{content_policy}".format(
+ organization=organization,
+ location=location,
+ content_policy=content_policy,
+ )
+ actual = DataStoreServiceClient.content_policy_path(
+ organization, location, content_policy
+ )
+ assert expected == actual
+
+
+def test_parse_content_policy_path():
+ expected = {
+ "organization": "clam",
+ "location": "whelk",
+ "content_policy": "octopus",
+ }
+ path = DataStoreServiceClient.content_policy_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataStoreServiceClient.parse_content_policy_path(path)
+ assert expected == actual
+
+
+def test_crypto_keys_path():
+ project = "oyster"
+ location = "nudibranch"
+ key_ring = "cuttlefish"
+ crypto_key = "mussel"
expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(
project=project,
location=location,
@@ -6286,10 +7879,10 @@ def test_crypto_keys_path():
def test_parse_crypto_keys_path():
expected = {
- "project": "whelk",
- "location": "octopus",
- "key_ring": "oyster",
- "crypto_key": "nudibranch",
+ "project": "winkle",
+ "location": "nautilus",
+ "key_ring": "scallop",
+ "crypto_key": "abalone",
}
path = DataStoreServiceClient.crypto_keys_path(**expected)
@@ -6299,11 +7892,11 @@ def test_parse_crypto_keys_path():
def test_crypto_key_versions_path():
- project = "cuttlefish"
- location = "mussel"
- key_ring = "winkle"
- crypto_key = "nautilus"
- crypto_key_version = "scallop"
+ project = "squid"
+ location = "clam"
+ key_ring = "whelk"
+ crypto_key = "octopus"
+ crypto_key_version = "oyster"
expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(
project=project,
location=location,
@@ -6319,11 +7912,11 @@ def test_crypto_key_versions_path():
def test_parse_crypto_key_versions_path():
expected = {
- "project": "abalone",
- "location": "squid",
- "key_ring": "clam",
- "crypto_key": "whelk",
- "crypto_key_version": "octopus",
+ "project": "nudibranch",
+ "location": "cuttlefish",
+ "key_ring": "mussel",
+ "crypto_key": "winkle",
+ "crypto_key_version": "nautilus",
}
path = DataStoreServiceClient.crypto_key_versions_path(**expected)
@@ -6333,9 +7926,9 @@ def test_parse_crypto_key_versions_path():
def test_data_store_path():
- project = "oyster"
- location = "nudibranch"
- data_store = "cuttlefish"
+ project = "scallop"
+ location = "abalone"
+ data_store = "squid"
expected = "projects/{project}/locations/{location}/dataStores/{data_store}".format(
project=project,
location=location,
@@ -6347,9 +7940,9 @@ def test_data_store_path():
def test_parse_data_store_path():
expected = {
- "project": "mussel",
- "location": "winkle",
- "data_store": "nautilus",
+ "project": "clam",
+ "location": "whelk",
+ "data_store": "octopus",
}
path = DataStoreServiceClient.data_store_path(**expected)
@@ -6359,9 +7952,9 @@ def test_parse_data_store_path():
def test_document_processing_config_path():
- project = "scallop"
- location = "abalone"
- data_store = "squid"
+ project = "oyster"
+ location = "nudibranch"
+ data_store = "cuttlefish"
expected = "projects/{project}/locations/{location}/dataStores/{data_store}/documentProcessingConfig".format(
project=project,
location=location,
@@ -6375,9 +7968,9 @@ def test_document_processing_config_path():
def test_parse_document_processing_config_path():
expected = {
- "project": "clam",
- "location": "whelk",
- "data_store": "octopus",
+ "project": "mussel",
+ "location": "winkle",
+ "data_store": "nautilus",
}
path = DataStoreServiceClient.document_processing_config_path(**expected)
@@ -6387,9 +7980,9 @@ def test_parse_document_processing_config_path():
def test_identity_mapping_store_path():
- project = "oyster"
- location = "nudibranch"
- identity_mapping_store = "cuttlefish"
+ project = "scallop"
+ location = "abalone"
+ identity_mapping_store = "squid"
expected = "projects/{project}/locations/{location}/identityMappingStores/{identity_mapping_store}".format(
project=project,
location=location,
@@ -6403,9 +7996,9 @@ def test_identity_mapping_store_path():
def test_parse_identity_mapping_store_path():
expected = {
- "project": "mussel",
- "location": "winkle",
- "identity_mapping_store": "nautilus",
+ "project": "clam",
+ "location": "whelk",
+ "identity_mapping_store": "octopus",
}
path = DataStoreServiceClient.identity_mapping_store_path(**expected)
@@ -6414,6 +8007,32 @@ def test_parse_identity_mapping_store_path():
assert expected == actual
+def test_notebook_path():
+ project = "oyster"
+ location = "nudibranch"
+ notebook = "cuttlefish"
+ expected = "projects/{project}/locations/{location}/notebooks/{notebook}".format(
+ project=project,
+ location=location,
+ notebook=notebook,
+ )
+ actual = DataStoreServiceClient.notebook_path(project, location, notebook)
+ assert expected == actual
+
+
+def test_parse_notebook_path():
+ expected = {
+ "project": "mussel",
+ "location": "winkle",
+ "notebook": "nautilus",
+ }
+ path = DataStoreServiceClient.notebook_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = DataStoreServiceClient.parse_notebook_path(path)
+ assert expected == actual
+
+
def test_schema_path():
project = "scallop"
location = "abalone"
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_document_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_document_service.py
index a58e7ddd3ae8..ce795aa13dba 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_document_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_document_service.py
@@ -1088,7 +1088,11 @@ def test_document_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -7558,7 +7562,11 @@ def test_document_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -7584,7 +7592,11 @@ def test_document_service_auth_adc():
DocumentServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -7604,7 +7616,11 @@ def test_document_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -7657,7 +7673,11 @@ def test_document_service_transport_create_channel(transport_class, grpc_helpers
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_engine_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_engine_service.py
index 7fa5f674df86..81eef344d3dc 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_engine_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_engine_service.py
@@ -40,9 +40,13 @@
import google.api_core.operation_async as operation_async # type: ignore
import google.auth
+import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore
+import google.iam.v1.options_pb2 as options_pb2 # type: ignore
+import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore
import google.protobuf.empty_pb2 as empty_pb2 # type: ignore
import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
+import google.type.expr_pb2 as expr_pb2 # type: ignore
from google.api_core import (
client_options,
future,
@@ -67,7 +71,14 @@
pagers,
transports,
)
-from google.cloud.discoveryengine_v1.types import common, engine, engine_service
+from google.cloud.discoveryengine_v1.types import (
+ agent_gateway_setting,
+ cmek_config_service,
+ common,
+ engine,
+ engine_service,
+ logging,
+)
from google.cloud.discoveryengine_v1.types import engine as gcd_engine
CRED_INFO_JSON = {
@@ -1055,7 +1066,11 @@ def test_engine_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -1806,7 +1821,12 @@ def test_update_engine(request_type, transport: str = "grpc"):
data_store_ids=["data_store_ids_value"],
solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
industry_vertical=common.IndustryVertical.GENERIC,
+ app_type=gcd_engine.Engine.AppType.APP_TYPE_INTRANET,
disable_analytics=True,
+ configurable_billing_approach=gcd_engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED,
+ marketplace_agent_visibility=gcd_engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY,
+ procurement_contact_emails=["procurement_contact_emails_value"],
+ associated_agent_registry="associated_agent_registry_value",
)
response = client.update_engine(request)
@@ -1823,7 +1843,18 @@ def test_update_engine(request_type, transport: str = "grpc"):
assert response.data_store_ids == ["data_store_ids_value"]
assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.app_type == gcd_engine.Engine.AppType.APP_TYPE_INTRANET
assert response.disable_analytics is True
+ assert (
+ response.configurable_billing_approach
+ == gcd_engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED
+ )
+ assert (
+ response.marketplace_agent_visibility
+ == gcd_engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY
+ )
+ assert response.procurement_contact_emails == ["procurement_contact_emails_value"]
+ assert response.associated_agent_registry == "associated_agent_registry_value"
def test_update_engine_non_empty_request_with_auto_populated_field():
@@ -1956,7 +1987,12 @@ async def test_update_engine_async(request_type, transport: str = "grpc_asyncio"
data_store_ids=["data_store_ids_value"],
solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
industry_vertical=common.IndustryVertical.GENERIC,
+ app_type=gcd_engine.Engine.AppType.APP_TYPE_INTRANET,
disable_analytics=True,
+ configurable_billing_approach=gcd_engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED,
+ marketplace_agent_visibility=gcd_engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY,
+ procurement_contact_emails=["procurement_contact_emails_value"],
+ associated_agent_registry="associated_agent_registry_value",
)
)
response = await client.update_engine(request)
@@ -1974,7 +2010,18 @@ async def test_update_engine_async(request_type, transport: str = "grpc_asyncio"
assert response.data_store_ids == ["data_store_ids_value"]
assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.app_type == gcd_engine.Engine.AppType.APP_TYPE_INTRANET
assert response.disable_analytics is True
+ assert (
+ response.configurable_billing_approach
+ == gcd_engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED
+ )
+ assert (
+ response.marketplace_agent_visibility
+ == gcd_engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY
+ )
+ assert response.procurement_contact_emails == ["procurement_contact_emails_value"]
+ assert response.associated_agent_registry == "associated_agent_registry_value"
def test_update_engine_field_headers():
@@ -2188,7 +2235,12 @@ def test_get_engine(request_type, transport: str = "grpc"):
data_store_ids=["data_store_ids_value"],
solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
industry_vertical=common.IndustryVertical.GENERIC,
+ app_type=engine.Engine.AppType.APP_TYPE_INTRANET,
disable_analytics=True,
+ configurable_billing_approach=engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED,
+ marketplace_agent_visibility=engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY,
+ procurement_contact_emails=["procurement_contact_emails_value"],
+ associated_agent_registry="associated_agent_registry_value",
)
response = client.get_engine(request)
@@ -2205,7 +2257,18 @@ def test_get_engine(request_type, transport: str = "grpc"):
assert response.data_store_ids == ["data_store_ids_value"]
assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.app_type == engine.Engine.AppType.APP_TYPE_INTRANET
assert response.disable_analytics is True
+ assert (
+ response.configurable_billing_approach
+ == engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED
+ )
+ assert (
+ response.marketplace_agent_visibility
+ == engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY
+ )
+ assert response.procurement_contact_emails == ["procurement_contact_emails_value"]
+ assert response.associated_agent_registry == "associated_agent_registry_value"
def test_get_engine_non_empty_request_with_auto_populated_field():
@@ -2340,7 +2403,12 @@ async def test_get_engine_async(request_type, transport: str = "grpc_asyncio"):
data_store_ids=["data_store_ids_value"],
solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
industry_vertical=common.IndustryVertical.GENERIC,
+ app_type=engine.Engine.AppType.APP_TYPE_INTRANET,
disable_analytics=True,
+ configurable_billing_approach=engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED,
+ marketplace_agent_visibility=engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY,
+ procurement_contact_emails=["procurement_contact_emails_value"],
+ associated_agent_registry="associated_agent_registry_value",
)
)
response = await client.get_engine(request)
@@ -2358,7 +2426,18 @@ async def test_get_engine_async(request_type, transport: str = "grpc_asyncio"):
assert response.data_store_ids == ["data_store_ids_value"]
assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.app_type == engine.Engine.AppType.APP_TYPE_INTRANET
assert response.disable_analytics is True
+ assert (
+ response.configurable_billing_approach
+ == engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED
+ )
+ assert (
+ response.marketplace_agent_visibility
+ == engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY
+ )
+ assert response.procurement_contact_emails == ["procurement_contact_emails_value"]
+ assert response.associated_agent_registry == "associated_agent_registry_value"
def test_get_engine_field_headers():
@@ -3023,13 +3102,80 @@ async def test_list_engines_async_pages():
assert page_.raw_page.next_page_token == token
-def test_create_engine_rest_use_cached_wrapped_rpc():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.GetIamPolicyRequest(),
+ {},
+ ],
+)
+def test_get_iam_policy(request_type, transport: str = "grpc"):
+ client = EngineServiceClient(
+ 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_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ response = client.get_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+
+def test_get_iam_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 = EngineServiceClient(
+ 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 = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_iam_policy(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest(
+ resource="resource_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_iam_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 = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport="grpc",
)
# Should wrap all calls on client creation
@@ -3037,372 +3183,340 @@ def test_create_engine_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.create_engine in client._transport._wrapped_methods
+ assert client._transport.get_iam_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_engine] = mock_rpc
-
+ client._transport._wrapped_methods[client._transport.get_iam_policy] = mock_rpc
request = {}
- client.create_engine(request)
+ client.get_iam_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_engine(request)
+ client.get_iam_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_engine_rest_required_fields(
- request_type=engine_service.CreateEngineRequest,
+@pytest.mark.asyncio
+async def test_get_iam_policy_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
):
- transport_class = transports.EngineServiceRestTransport
+ # Clients should use _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 = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
- request_init = {}
- request_init["parent"] = ""
- request_init["engine_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 "engineId" not in jsonified_request
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_iam_policy
+ in client._client._transport._wrapped_methods
+ )
- default_values = getattr(
- transport_class._BaseCreateEngine,
- "_BaseCreateEngine__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_iam_policy
+ ] = mock_rpc
- # verify required fields with default values are now present
- assert "engineId" in jsonified_request
- assert jsonified_request["engineId"] == request_init["engine_id"]
+ request = {}
+ await client.get_iam_policy(request)
- jsonified_request["parent"] = "parent_value"
- jsonified_request["engineId"] = "engine_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(("engineId",))
+ await client.get_iam_policy(request)
- # verify required fields with non-default values are left alone
- assert "parent" in jsonified_request
- assert jsonified_request["parent"] == "parent_value"
- assert "engineId" in jsonified_request
- assert jsonified_request["engineId"] == "engine_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 = EngineServiceClient(
- 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
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.GetIamPolicyRequest(),
+ {},
+ ],
+)
+async def test_get_iam_policy_async(request_type, transport: str = "grpc_asyncio"):
+ client = EngineServiceAsyncClient(
+ 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.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ response = await client.get_iam_policy(request)
- response = client.create_engine(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request
- expected_params = [
- (
- "engineId",
- "",
- ),
- ("$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, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
-def test_create_engine_rest_flattened():
+def test_get_iam_policy_field_headers():
client = EngineServiceClient(
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/collections/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 = iam_policy_pb2.GetIamPolicyRequest()
- # get truthy value for each flattened field
- mock_args = dict(
- parent="parent_value",
- engine=gcd_engine.Engine(
- chat_engine_config=gcd_engine.Engine.ChatEngineConfig(
- agent_creation_config=gcd_engine.Engine.ChatEngineConfig.AgentCreationConfig(
- business="business_value"
- )
- )
- ),
- engine_id="engine_id_value",
- )
- mock_args.update(sample_request)
+ request.resource = "resource_value"
- # 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.get_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.get_iam_policy(request)
- client.create_engine(**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/*/collections/*}/engines"
- % client.transport._host,
- args[1],
- )
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "resource=resource_value",
+ ) in kw["metadata"]
-def test_create_engine_rest_flattened_error(transport: str = "rest"):
- client = EngineServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
+@pytest.mark.asyncio
+async def test_get_iam_policy_field_headers_async():
+ client = EngineServiceAsyncClient(
+ 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.create_engine(
- engine_service.CreateEngineRequest(),
- parent="parent_value",
- engine=gcd_engine.Engine(
- chat_engine_config=gcd_engine.Engine.ChatEngineConfig(
- agent_creation_config=gcd_engine.Engine.ChatEngineConfig.AgentCreationConfig(
- business="business_value"
- )
- )
- ),
- engine_id="engine_id_value",
- )
-
-
-def test_delete_engine_rest_use_cached_wrapped_rpc():
- # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
- # instead of constructing them on each call
- with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
- client = EngineServiceClient(
- 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_engine 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 = iam_policy_pb2.GetIamPolicyRequest()
- # Replace cached wrapped function with mock
- mock_rpc = 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_engine] = mock_rpc
+ request.resource = "resource_value"
- request = {}
- client.delete_engine(request)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ await client.get_iam_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_engine(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)
+ _, 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",
+ "resource=resource_value",
+ ) in kw["metadata"]
-def test_delete_engine_rest_required_fields(
- request_type=engine_service.DeleteEngineRequest,
-):
- transport_class = transports.EngineServiceRestTransport
- 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_get_iam_policy_from_dict_foreign():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ response = client.get_iam_policy(
+ request={
+ "resource": "resource_value",
+ "options": options_pb2.GetPolicyOptions(requested_policy_version=2598),
+ }
+ )
+ call.assert_called()
- # verify fields with default values are dropped
- default_values = getattr(
- transport_class._BaseDeleteEngine,
- "_BaseDeleteEngine__REQUIRED_FIELDS_DEFAULT_VALUES",
- {},
+def test_get_iam_policy_flattened():
+ client = EngineServiceClient(
+ 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.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_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_get_iam_policy_flattened_error():
client = EngineServiceClient(
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
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.get_iam_policy(
+ iam_policy_pb2.GetIamPolicyRequest(),
+ resource="resource_value",
+ )
- 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_get_iam_policy_flattened_async():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
- response = client.delete_engine(request)
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
- expected_params = [("$alt", "json;enum-encoding=int")]
- actual_params = req.call_args.kwargs["params"]
- assert sorted(expected_params) == sorted(actual_params)
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
-def test_delete_engine_rest_flattened():
+@pytest.mark.asyncio
+async def test_get_iam_policy_flattened_error_async():
+ client = EngineServiceAsyncClient(
+ 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_iam_policy(
+ iam_policy_pb2.GetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ iam_policy_pb2.SetIamPolicyRequest(),
+ {},
+ ],
+)
+def test_set_iam_policy(request_type, transport: str = "grpc"):
client = EngineServiceClient(
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/collections/sample3/engines/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(
- name="name_value",
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
)
- 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.set_iam_policy(request)
- client.delete_engine(**mock_args)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ 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/*/collections/*/engines/*}"
- % client.transport._host,
- args[1],
- )
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
-def test_delete_engine_rest_flattened_error(transport: str = "rest"):
+def test_set_iam_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 = EngineServiceClient(
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_engine(
- engine_service.DeleteEngineRequest(),
- 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 = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.set_iam_policy(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest(
+ resource="resource_value",
)
+ assert args[0] == request_msg
-def test_update_engine_rest_use_cached_wrapped_rpc():
+def test_set_iam_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 = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport="grpc",
)
# Should wrap all calls on client creation
@@ -3410,179 +3524,268 @@ def test_update_engine_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.update_engine in client._transport._wrapped_methods
+ assert client._transport.set_iam_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_engine] = mock_rpc
-
+ client._transport._wrapped_methods[client._transport.set_iam_policy] = mock_rpc
request = {}
- client.update_engine(request)
+ client.set_iam_policy(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.update_engine(request)
+ client.set_iam_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_engine_rest_required_fields(
- request_type=engine_service.UpdateEngineRequest,
-):
- transport_class = transports.EngineServiceRestTransport
+@pytest.mark.asyncio
+async def test_set_iam_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 = EngineServiceAsyncClient(
+ 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.set_iam_policy
+ in client._client._transport._wrapped_methods
+ )
- default_values = getattr(
- transport_class._BaseUpdateEngine,
- "_BaseUpdateEngine__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.set_iam_policy
+ ] = mock_rpc
+
+ request = {}
+ await client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.set_iam_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",
+ [
+ iam_policy_pb2.SetIamPolicyRequest(),
{},
+ ],
+)
+async def test_set_iam_policy_async(request_type, transport: str = "grpc_asyncio"):
+ client = EngineServiceAsyncClient(
+ 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(("updateMask",))
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ response = await client.set_iam_policy(request)
- # verify required fields with non-default values are left alone
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
+
+def test_set_iam_policy_field_headers():
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
)
- request = request_type(**request_init)
- # Designate an appropriate value for the returned response.
- return_value = gcd_engine.Engine()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force 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 = iam_policy_pb2.SetIamPolicyRequest()
- response_value = Response()
- response_value.status_code = 200
+ request.resource = "resource_value"
- # Convert return value to protobuf type
- return_value = gcd_engine.Engine.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.set_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.set_iam_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.update_engine(request)
+ # Establish that the field header was sent.
+ _, _, kw = call.mock_calls[0]
+ assert (
+ "x-goog-request-params",
+ "resource=resource_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_set_iam_policy_field_headers_async():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
-def test_update_engine_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 = iam_policy_pb2.SetIamPolicyRequest()
+
+ request.resource = "resource_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ await client.set_iam_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",
+ "resource=resource_value",
+ ) in kw["metadata"]
+
+
+def test_set_iam_policy_from_dict_foreign():
client = EngineServiceClient(
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 = gcd_engine.Engine()
-
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "engine": {
- "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ response = client.set_iam_policy(
+ request={
+ "resource": "resource_value",
+ "policy": policy_pb2.Policy(version=774),
+ "update_mask": field_mask_pb2.FieldMask(paths=["paths_value"]),
}
- }
-
- # get truthy value for each flattened field
- mock_args = dict(
- engine=gcd_engine.Engine(
- chat_engine_config=gcd_engine.Engine.ChatEngineConfig(
- agent_creation_config=gcd_engine.Engine.ChatEngineConfig.AgentCreationConfig(
- business="business_value"
- )
- )
- ),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
)
- mock_args.update(sample_request)
+ call.assert_called()
- # Wrap the value into a proper Response obj
- response_value = Response()
- response_value.status_code = 200
- # Convert return value to protobuf type
- return_value = gcd_engine.Engine.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._content = 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_engine(**mock_args)
+def test_set_iam_policy_flattened():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.set_iam_policy(
+ resource="resource_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/{engine.name=projects/*/locations/*/collections/*/engines/*}"
- % client.transport._host,
- args[1],
- )
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ arg = args[0].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
-def test_update_engine_rest_flattened_error(transport: str = "rest"):
+def test_set_iam_policy_flattened_error():
client = EngineServiceClient(
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_engine(
- engine_service.UpdateEngineRequest(),
- engine=gcd_engine.Engine(
- chat_engine_config=gcd_engine.Engine.ChatEngineConfig(
- agent_creation_config=gcd_engine.Engine.ChatEngineConfig.AgentCreationConfig(
- business="business_value"
- )
- )
- ),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ client.set_iam_policy(
+ iam_policy_pb2.SetIamPolicyRequest(),
+ resource="resource_value",
)
-def test_get_engine_rest_use_cached_wrapped_rpc():
+@pytest.mark.asyncio
+async def test_set_iam_policy_flattened_async():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = policy_pb2.Policy()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy())
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.set_iam_policy(
+ resource="resource_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].resource
+ mock_val = "resource_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_set_iam_policy_flattened_error_async():
+ client = EngineServiceAsyncClient(
+ 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.set_iam_policy(
+ iam_policy_pb2.SetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+def test_create_engine_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -3596,33 +3799,40 @@ def test_get_engine_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.get_engine in client._transport._wrapped_methods
+ assert client._transport.create_engine in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = 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_engine] = mock_rpc
+ client._transport._wrapped_methods[client._transport.create_engine] = mock_rpc
request = {}
- client.get_engine(request)
+ client.create_engine(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.get_engine(request)
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
- # Establish that a new wrapper was not created for this call
+ client.create_engine(request)
+
+ # Establish 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_engine_rest_required_fields(request_type=engine_service.GetEngineRequest):
+def test_create_engine_rest_required_fields(
+ request_type=engine_service.CreateEngineRequest,
+):
transport_class = transports.EngineServiceRestTransport
request_init = {}
- request_init["name"] = ""
+ request_init["parent"] = ""
+ request_init["engine_id"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -3630,10 +3840,11 @@ def test_get_engine_rest_required_fields(request_type=engine_service.GetEngineRe
)
# verify fields with default values are dropped
+ assert "engineId" not in jsonified_request
default_values = getattr(
- transport_class._BaseGetEngine,
- "_BaseGetEngine__REQUIRED_FIELDS_DEFAULT_VALUES",
+ transport_class._BaseCreateEngine,
+ "_BaseCreateEngine__REQUIRED_FIELDS_DEFAULT_VALUES",
{},
)
unset_fields = {
@@ -3642,12 +3853,20 @@ def test_get_engine_rest_required_fields(request_type=engine_service.GetEngineRe
jsonified_request.update(unset_fields)
# verify required fields with default values are now present
+ assert "engineId" in jsonified_request
+ assert jsonified_request["engineId"] == request_init["engine_id"]
- jsonified_request["name"] = "name_value"
+ jsonified_request["parent"] = "parent_value"
+ jsonified_request["engineId"] = "engine_id_value"
+
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("engineId",))
# 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 "engineId" in jsonified_request
+ assert jsonified_request["engineId"] == "engine_id_value"
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3656,7 +3875,7 @@ def test_get_engine_rest_required_fields(request_type=engine_service.GetEngineRe
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = engine.Engine()
+ 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
@@ -3668,30 +3887,34 @@ def test_get_engine_rest_required_fields(request_type=engine_service.GetEngineRe
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 = engine.Engine.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_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_engine(request)
+ response = client.create_engine(request)
- expected_params = [("$alt", "json;enum-encoding=int")]
+ expected_params = [
+ (
+ "engineId",
+ "",
+ ),
+ ("$alt", "json;enum-encoding=int"),
+ ]
actual_params = req.call_args.kwargs["params"]
assert sorted(expected_params) == sorted(actual_params)
-def test_get_engine_rest_flattened():
+def test_create_engine_rest_flattened():
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -3700,43 +3923,49 @@ def test_get_engine_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 = engine.Engine()
+ 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/collections/sample3/engines/sample4"
+ "parent": "projects/sample1/locations/sample2/collections/sample3"
}
# get truthy value for each flattened field
mock_args = dict(
- name="name_value",
+ parent="parent_value",
+ engine=gcd_engine.Engine(
+ chat_engine_config=gcd_engine.Engine.ChatEngineConfig(
+ agent_creation_config=gcd_engine.Engine.ChatEngineConfig.AgentCreationConfig(
+ business="business_value"
+ )
+ )
+ ),
+ engine_id="engine_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 = engine.Engine.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = 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_engine(**mock_args)
+ client.create_engine(**mock_args)
# Establish that the underlying call 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/*/collections/*/engines/*}"
+ "%s/v1/{parent=projects/*/locations/*/collections/*}/engines"
% client.transport._host,
args[1],
)
-def test_get_engine_rest_flattened_error(transport: str = "rest"):
+def test_create_engine_rest_flattened_error(transport: str = "rest"):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -3745,13 +3974,21 @@ def test_get_engine_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_engine(
- engine_service.GetEngineRequest(),
- name="name_value",
+ client.create_engine(
+ engine_service.CreateEngineRequest(),
+ parent="parent_value",
+ engine=gcd_engine.Engine(
+ chat_engine_config=gcd_engine.Engine.ChatEngineConfig(
+ agent_creation_config=gcd_engine.Engine.ChatEngineConfig.AgentCreationConfig(
+ business="business_value"
+ )
+ )
+ ),
+ engine_id="engine_id_value",
)
-def test_list_engines_rest_use_cached_wrapped_rpc():
+def test_delete_engine_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -3765,35 +4002,39 @@ def test_list_engines_rest_use_cached_wrapped_rpc():
wrapper_fn.reset_mock()
# Ensure method has been cached
- assert client._transport.list_engines in client._transport._wrapped_methods
+ assert client._transport.delete_engine in client._transport._wrapped_methods
# Replace cached wrapped function with mock
mock_rpc = 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_engines] = mock_rpc
+ client._transport._wrapped_methods[client._transport.delete_engine] = mock_rpc
request = {}
- client.list_engines(request)
+ client.delete_engine(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.list_engines(request)
+ # Operation methods build a cached wrapper on first rpc call
+ # subsequent calls should use the cached wrapper
+ wrapper_fn.reset_mock()
+
+ client.delete_engine(request)
# Establish 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_engines_rest_required_fields(
- request_type=engine_service.ListEnginesRequest,
+def test_delete_engine_rest_required_fields(
+ request_type=engine_service.DeleteEngineRequest,
):
transport_class = transports.EngineServiceRestTransport
request_init = {}
- request_init["parent"] = ""
+ request_init["name"] = ""
request = request_type(**request_init)
pb_request = request_type.pb(request)
jsonified_request = json.loads(
@@ -3803,8 +4044,8 @@ def test_list_engines_rest_required_fields(
# verify fields with default values are dropped
default_values = getattr(
- transport_class._BaseListEngines,
- "_BaseListEngines__REQUIRED_FIELDS_DEFAULT_VALUES",
+ transport_class._BaseDeleteEngine,
+ "_BaseDeleteEngine__REQUIRED_FIELDS_DEFAULT_VALUES",
{},
)
unset_fields = {
@@ -3814,20 +4055,11 @@ def test_list_engines_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",
- "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 = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -3836,7 +4068,7 @@ def test_list_engines_rest_required_fields(
request = request_type(**request_init)
# Designate an appropriate value for the returned response.
- return_value = engine_service.ListEnginesResponse()
+ 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
@@ -3848,30 +4080,27 @@ def test_list_engines_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 = engine_service.ListEnginesResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = json_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_engines(request)
+ response = client.delete_engine(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_engines_rest_flattened():
+def test_delete_engine_rest_flattened():
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -3880,43 +4109,41 @@ def test_list_engines_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 = engine_service.ListEnginesResponse()
+ 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/collections/sample3"
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/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 = engine_service.ListEnginesResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value._content = 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_engines(**mock_args)
+ client.delete_engine(**mock_args)
# Establish that the underlying call 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/*/collections/*}/engines"
+ "%s/v1/{name=projects/*/locations/*/collections/*/engines/*}"
% client.transport._host,
args[1],
)
-def test_list_engines_rest_flattened_error(transport: str = "rest"):
+def test_delete_engine_rest_flattened_error(transport: str = "rest"):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -3925,451 +4152,1845 @@ def test_list_engines_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_engines(
- engine_service.ListEnginesRequest(),
- parent="parent_value",
+ client.delete_engine(
+ engine_service.DeleteEngineRequest(),
+ name="name_value",
)
-def test_list_engines_rest_pager(transport: str = "rest"):
- client = EngineServiceClient(
- 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 = (
- engine_service.ListEnginesResponse(
- engines=[
- engine.Engine(),
- engine.Engine(),
- engine.Engine(),
- ],
- next_page_token="abc",
- ),
- engine_service.ListEnginesResponse(
- engines=[],
- next_page_token="def",
- ),
- engine_service.ListEnginesResponse(
- engines=[
- engine.Engine(),
- ],
- next_page_token="ghi",
- ),
- engine_service.ListEnginesResponse(
- engines=[
- engine.Engine(),
- engine.Engine(),
- ],
- ),
+def test_update_engine_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # Two responses for two calls
- response = response + response
- # Wrap the values into proper Response objs
- response = tuple(
- engine_service.ListEnginesResponse.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.update_engine in client._transport._wrapped_methods
+
+ # Replace cached 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
+ client._transport._wrapped_methods[client._transport.update_engine] = mock_rpc
- sample_request = {
- "parent": "projects/sample1/locations/sample2/collections/sample3"
- }
+ request = {}
+ client.update_engine(request)
- pager = client.list_engines(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__}<")
+ client.update_engine(request)
- results = list(pager)
- assert len(results) == 6
- assert all(isinstance(i, engine.Engine) for i in results)
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
- pages = list(client.list_engines(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
+def test_update_engine_rest_required_fields(
+ request_type=engine_service.UpdateEngineRequest,
+):
+ transport_class = transports.EngineServiceRestTransport
-def test_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.EngineServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
+ 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)
)
- with pytest.raises(ValueError):
- client = EngineServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
-
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.EngineServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = EngineServiceClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
-
- # It is an error to provide an api_key and a transport instance.
- transport = transports.EngineServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = EngineServiceClient(
- 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 = EngineServiceClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
+ # verify fields with default values are dropped
- # It is an error to provide scopes and a transport instance.
- transport = transports.EngineServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
+ default_values = getattr(
+ transport_class._BaseUpdateEngine,
+ "_BaseUpdateEngine__REQUIRED_FIELDS_DEFAULT_VALUES",
+ {},
)
- with pytest.raises(ValueError):
- client = EngineServiceClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
-
+ unset_fields = {
+ k: v for k, v in default_values.items() if k not in jsonified_request
+ }
+ jsonified_request.update(unset_fields)
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.EngineServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = EngineServiceClient(transport=transport)
- assert client.transport is transport
+ # 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(("updateMask",))
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.EngineServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
+ # verify required fields with non-default values are left alone
- transport = transports.EngineServiceGrpcAsyncIOTransport(
+ client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- channel = transport.grpc_channel
- assert channel
+ request = request_type(**request_init)
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_engine.Engine()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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
-@pytest.mark.parametrize(
- "transport_class",
- [
- transports.EngineServiceGrpcTransport,
- transports.EngineServiceGrpcAsyncIOTransport,
- transports.EngineServiceRestTransport,
- ],
-)
-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()
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = gcd_engine.Engine.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
-def test_transport_kind_grpc():
- transport = EngineServiceClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "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"}
+ response = client.update_engine(request)
-def test_initialize_client_w_grpc():
- client = EngineServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
- )
- assert client is not None
+ 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_engine_empty_call_grpc():
+def test_update_engine_rest_flattened():
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.create_engine), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.create_engine(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 = gcd_engine.Engine()
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = engine_service.CreateEngineRequest()
- assert args[0] == request_msg
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "engine": {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ }
+ }
+ # get truthy value for each flattened field
+ mock_args = dict(
+ engine=gcd_engine.Engine(
+ chat_engine_config=gcd_engine.Engine.ChatEngineConfig(
+ agent_creation_config=gcd_engine.Engine.ChatEngineConfig.AgentCreationConfig(
+ business="business_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.
-def test_delete_engine_empty_call_grpc():
- client = EngineServiceClient(
- 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 = gcd_engine.Engine.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._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_engine), "__call__") as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.delete_engine(request=None)
+ client.update_engine(**mock_args)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = engine_service.DeleteEngineRequest()
- 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/{engine.name=projects/*/locations/*/collections/*/engines/*}"
+ % 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_update_engine_empty_call_grpc():
+def test_update_engine_rest_flattened_error(transport: str = "rest"):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
+ transport=transport,
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.update_engine), "__call__") as call:
- call.return_value = gcd_engine.Engine()
- client.update_engine(request=None)
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
+ with pytest.raises(ValueError):
+ client.update_engine(
+ engine_service.UpdateEngineRequest(),
+ engine=gcd_engine.Engine(
+ chat_engine_config=gcd_engine.Engine.ChatEngineConfig(
+ agent_creation_config=gcd_engine.Engine.ChatEngineConfig.AgentCreationConfig(
+ business="business_value"
+ )
+ )
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = engine_service.UpdateEngineRequest()
- assert args[0] == request_msg
+def test_get_engine_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EngineServiceClient(
+ 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_get_engine_empty_call_grpc():
- client = EngineServiceClient(
- 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.get_engine), "__call__") as call:
- call.return_value = engine.Engine()
- client.get_engine(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = engine_service.GetEngineRequest()
- assert args[0] == request_msg
+ # Ensure method has been cached
+ assert client._transport.get_engine in client._transport._wrapped_methods
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_engine] = 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_list_engines_empty_call_grpc():
- client = EngineServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport="grpc",
- )
+ request = {}
+ client.get_engine(request)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_engines), "__call__") as call:
- call.return_value = engine_service.ListEnginesResponse()
- client.list_engines(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 = engine_service.ListEnginesRequest()
- assert args[0] == request_msg
+ client.get_engine(request)
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
-def test_transport_kind_grpc_asyncio():
- transport = EngineServiceAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
+def test_get_engine_rest_required_fields(request_type=engine_service.GetEngineRequest):
+ transport_class = transports.EngineServiceRestTransport
-def test_initialize_client_w_grpc_asyncio():
- client = EngineServiceAsyncClient(
- 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)
)
- assert client is not None
+ # 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_create_engine_empty_call_grpc_asyncio():
- client = EngineServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+ default_values = getattr(
+ transport_class._BaseGetEngine,
+ "_BaseGetEngine__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.create_engine), "__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_engine(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 = engine_service.CreateEngineRequest()
- 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.
-@pytest.mark.asyncio
-async def test_delete_engine_empty_call_grpc_asyncio():
- client = EngineServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+ client = EngineServiceClient(
+ 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_engine), "__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_engine(request=None)
+ # Designate an appropriate value for the returned response.
+ return_value = engine.Engine()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = engine_service.DeleteEngineRequest()
- assert args[0] == request_msg
+ response_value = Response()
+ response_value.status_code = 200
+ # Convert return value to protobuf type
+ return_value = engine.Engine.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_engine_empty_call_grpc_asyncio():
- client = EngineServiceAsyncClient(
- 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_engine), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcd_engine.Engine(
- name="name_value",
- display_name="display_name_value",
- data_store_ids=["data_store_ids_value"],
- solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
- industry_vertical=common.IndustryVertical.GENERIC,
- disable_analytics=True,
- )
- )
- await client.update_engine(request=None)
+ response = client.get_engine(request)
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = engine_service.UpdateEngineRequest()
- 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_engine_empty_call_grpc_asyncio():
- client = EngineServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+def test_get_engine_rest_flattened():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
)
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.get_engine), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- engine.Engine(
- name="name_value",
- display_name="display_name_value",
- data_store_ids=["data_store_ids_value"],
- solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
- industry_vertical=common.IndustryVertical.GENERIC,
- disable_analytics=True,
- )
- )
- await client.get_engine(request=None)
-
- # Establish that the underlying stub method was called.
- call.assert_called()
- _, args, _ = call.mock_calls[0]
- request_msg = engine_service.GetEngineRequest()
- 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 = engine.Engine()
-# This test is a coverage 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_engines_empty_call_grpc_asyncio():
- client = EngineServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
- )
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ }
- # Mock the actual call, and fake the request.
- with mock.patch.object(type(client.transport.list_engines), "__call__") as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- engine_service.ListEnginesResponse(
- next_page_token="next_page_token_value",
- )
+ # get truthy value for each flattened field
+ mock_args = dict(
+ name="name_value",
)
- await client.list_engines(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 = engine_service.ListEnginesRequest()
- 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 = engine.Engine.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_engine(**mock_args)
-def test_transport_kind_rest():
- transport = EngineServiceClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
+ # Establish that the underlying call 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/*/collections/*/engines/*}"
+ % client.transport._host,
+ args[1],
+ )
-def test_create_engine_rest_bad_request(
- request_type=engine_service.CreateEngineRequest,
-):
+def test_get_engine_rest_flattened_error(transport: str = "rest"):
client = EngineServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
+ 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_engine(
+ engine_service.GetEngineRequest(),
+ name="name_value",
+ )
+
+
+def test_list_engines_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = EngineServiceClient(
+ 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_engines in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_engines] = mock_rpc
+
+ request = {}
+ client.list_engines(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_engines(request)
+
+ # Establish 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_engines_rest_required_fields(
+ request_type=engine_service.ListEnginesRequest,
+):
+ transport_class = transports.EngineServiceRestTransport
+
+ 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._BaseListEngines,
+ "_BaseListEngines__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 = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = engine_service.ListEnginesResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = engine_service.ListEnginesResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_engines(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_engines_rest_flattened():
+ client = EngineServiceClient(
+ 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 = engine_service.ListEnginesResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/collections/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 = engine_service.ListEnginesResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_engines(**mock_args)
+
+ # Establish that the underlying call 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/*/collections/*}/engines"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_list_engines_rest_flattened_error(transport: str = "rest"):
+ client = EngineServiceClient(
+ 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_engines(
+ engine_service.ListEnginesRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_engines_rest_pager(transport: str = "rest"):
+ client = EngineServiceClient(
+ 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 = (
+ engine_service.ListEnginesResponse(
+ engines=[
+ engine.Engine(),
+ engine.Engine(),
+ engine.Engine(),
+ ],
+ next_page_token="abc",
+ ),
+ engine_service.ListEnginesResponse(
+ engines=[],
+ next_page_token="def",
+ ),
+ engine_service.ListEnginesResponse(
+ engines=[
+ engine.Engine(),
+ ],
+ next_page_token="ghi",
+ ),
+ engine_service.ListEnginesResponse(
+ engines=[
+ engine.Engine(),
+ engine.Engine(),
+ ],
+ ),
+ )
+ # Two responses for two calls
+ response = response + response
+
+ # Wrap the values into proper Response objs
+ response = tuple(
+ engine_service.ListEnginesResponse.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/collections/sample3"
+ }
+
+ pager = client.list_engines(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, engine.Engine) for i in results)
+
+ pages = list(client.list_engines(request=sample_request).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_get_iam_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 = EngineServiceClient(
+ 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_iam_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_iam_policy] = mock_rpc
+
+ request = {}
+ client.get_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_iam_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_iam_policy_rest_required_fields(
+ request_type=iam_policy_pb2.GetIamPolicyRequest,
+):
+ transport_class = transports.EngineServiceRestTransport
+
+ request_init = {}
+ request_init["resource"] = ""
+ request = request_type(**request_init)
+ pb_request = request
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ default_values = getattr(
+ transport_class._BaseGetIamPolicy,
+ "_BaseGetIamPolicy__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["resource"] = "resource_value"
+
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("options",))
+
+ # verify required fields with non-default values are left alone
+ assert "resource" in jsonified_request
+ assert jsonified_request["resource"] == "resource_value"
+
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = policy_pb2.Policy()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "get",
+ "query_params": pb_request,
+ }
+ transcode.return_value = transcode_result
+
+ response_value = Response()
+ response_value.status_code = 200
+
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.get_iam_policy(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_get_iam_policy_rest_flattened():
+ client = EngineServiceClient(
+ 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 = policy_pb2.Policy()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ resource="resource_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.get_iam_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/{resource=projects/*/locations/*/collections/*/engines/*}:getIamPolicy"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_iam_policy_rest_flattened_error(transport: str = "rest"):
+ client = EngineServiceClient(
+ 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_iam_policy(
+ iam_policy_pb2.GetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+def test_set_iam_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 = EngineServiceClient(
+ 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.set_iam_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.set_iam_policy] = mock_rpc
+
+ request = {}
+ client.set_iam_policy(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.set_iam_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_set_iam_policy_rest_required_fields(
+ request_type=iam_policy_pb2.SetIamPolicyRequest,
+):
+ transport_class = transports.EngineServiceRestTransport
+
+ request_init = {}
+ request_init["resource"] = ""
+ request = request_type(**request_init)
+ pb_request = request
+ jsonified_request = json.loads(
+ json_format.MessageToJson(pb_request, use_integers_for_enums=False)
+ )
+
+ # verify fields with default values are dropped
+
+ default_values = getattr(
+ transport_class._BaseSetIamPolicy,
+ "_BaseSetIamPolicy__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["resource"] = "resource_value"
+
+ # verify required fields with non-default values are left alone
+ assert "resource" in jsonified_request
+ assert jsonified_request["resource"] == "resource_value"
+
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = policy_pb2.Policy()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force all the
+ # request fields to show up in the query_params.
+ pb_request = request
+ transcode_result = {
+ "uri": "v1/sample_method",
+ "method": "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.set_iam_policy(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_set_iam_policy_rest_flattened():
+ client = EngineServiceClient(
+ 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 = policy_pb2.Policy()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ resource="resource_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.set_iam_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/{resource=projects/*/locations/*/collections/*/engines/*}:setIamPolicy"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_set_iam_policy_rest_flattened_error(transport: str = "rest"):
+ client = EngineServiceClient(
+ 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.set_iam_policy(
+ iam_policy_pb2.SetIamPolicyRequest(),
+ resource="resource_value",
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.EngineServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.EngineServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = EngineServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.EngineServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = EngineServiceClient(
+ 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 = EngineServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.EngineServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = EngineServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.EngineServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = EngineServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.EngineServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.EngineServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.EngineServiceGrpcTransport,
+ transports.EngineServiceGrpcAsyncIOTransport,
+ transports.EngineServiceRestTransport,
+ ],
+)
+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 = EngineServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = EngineServiceClient(
+ 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_create_engine_empty_call_grpc():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.create_engine), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.create_engine(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.CreateEngineRequest()
+ assert args[0] == request_msg
+
+
+# This 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_engine_empty_call_grpc():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_engine), "__call__") as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.delete_engine(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.DeleteEngineRequest()
+ assert args[0] == request_msg
+
+
+# This 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_engine_empty_call_grpc():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.update_engine), "__call__") as call:
+ call.return_value = gcd_engine.Engine()
+ client.update_engine(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.UpdateEngineRequest()
+ assert args[0] == request_msg
+
+
+# This 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_engine_empty_call_grpc():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_engine), "__call__") as call:
+ call.return_value = engine.Engine()
+ client.get_engine(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.GetEngineRequest()
+ assert args[0] == request_msg
+
+
+# This 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_engines_empty_call_grpc():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_engines), "__call__") as call:
+ call.return_value = engine_service.ListEnginesResponse()
+ client.list_engines(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.ListEnginesRequest()
+ assert args[0] == request_msg
+
+
+# This 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_iam_policy_empty_call_grpc():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.get_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_set_iam_policy_empty_call_grpc():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ call.return_value = policy_pb2.Policy()
+ client.set_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = EngineServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = EngineServiceAsyncClient(
+ 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_create_engine_empty_call_grpc_asyncio():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.create_engine), "__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_engine(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.CreateEngineRequest()
+ assert args[0] == request_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_engine_empty_call_grpc_asyncio():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.delete_engine), "__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_engine(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.DeleteEngineRequest()
+ assert args[0] == request_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_engine_empty_call_grpc_asyncio():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.update_engine), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_engine.Engine(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_ids=["data_store_ids_value"],
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ app_type=gcd_engine.Engine.AppType.APP_TYPE_INTRANET,
+ disable_analytics=True,
+ configurable_billing_approach=gcd_engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED,
+ marketplace_agent_visibility=gcd_engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY,
+ procurement_contact_emails=["procurement_contact_emails_value"],
+ associated_agent_registry="associated_agent_registry_value",
+ )
+ )
+ await client.update_engine(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.UpdateEngineRequest()
+ assert args[0] == request_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_engine_empty_call_grpc_asyncio():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_engine), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ engine.Engine(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_ids=["data_store_ids_value"],
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ app_type=engine.Engine.AppType.APP_TYPE_INTRANET,
+ disable_analytics=True,
+ configurable_billing_approach=engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED,
+ marketplace_agent_visibility=engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY,
+ procurement_contact_emails=["procurement_contact_emails_value"],
+ associated_agent_registry="associated_agent_registry_value",
+ )
+ )
+ await client.get_engine(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.GetEngineRequest()
+ assert args[0] == request_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_engines_empty_call_grpc_asyncio():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.list_engines), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ engine_service.ListEnginesResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ await client.list_engines(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = engine_service.ListEnginesRequest()
+ assert args[0] == request_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_iam_policy_empty_call_grpc_asyncio():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ await client.get_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request_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_set_iam_policy_empty_call_grpc_asyncio():
+ client = EngineServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
+ )
+ )
+ await client.set_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = EngineServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_create_engine_rest_bad_request(
+ request_type=engine_service.CreateEngineRequest,
+):
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/collections/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_engine(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ engine_service.CreateEngineRequest,
+ dict,
+ ],
+)
+def test_create_engine_rest_call_success(request_type):
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/collections/sample3"}
+ request_init["engine"] = {
+ "chat_engine_config": {
+ "agent_creation_config": {
+ "business": "business_value",
+ "default_language_code": "default_language_code_value",
+ "time_zone": "time_zone_value",
+ "location": "location_value",
+ },
+ "dialogflow_agent_to_link": "dialogflow_agent_to_link_value",
+ "allow_cross_region": True,
+ },
+ "search_engine_config": {
+ "search_tier": 1,
+ "required_subscription_tier": 1,
+ "search_add_ons": [1],
+ },
+ "media_recommendation_engine_config": {
+ "type_": "type__value",
+ "optimization_objective": "optimization_objective_value",
+ "optimization_objective_config": {
+ "target_field": "target_field_value",
+ "target_field_value_float": 0.2523,
+ },
+ "training_state": 1,
+ "engine_features_config": {
+ "recommended_for_you_config": {
+ "context_event_type": "context_event_type_value"
+ },
+ "most_popular_config": {"time_window_days": 1718},
+ },
+ },
+ "chat_engine_metadata": {"dialogflow_agent": "dialogflow_agent_value"},
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "create_time": {"seconds": 751, "nanos": 543},
+ "update_time": {},
+ "data_store_ids": ["data_store_ids_value1", "data_store_ids_value2"],
+ "solution_type": 1,
+ "industry_vertical": 1,
+ "common_config": {"company_name": "company_name_value"},
+ "knowledge_graph_config": {
+ "enable_cloud_knowledge_graph": True,
+ "cloud_knowledge_graph_types": [
+ "cloud_knowledge_graph_types_value1",
+ "cloud_knowledge_graph_types_value2",
+ ],
+ "enable_private_knowledge_graph": True,
+ "private_knowledge_graph_types": [
+ "private_knowledge_graph_types_value1",
+ "private_knowledge_graph_types_value2",
+ ],
+ "feature_config": {
+ "disable_private_kg_query_understanding": True,
+ "disable_private_kg_enrichment": True,
+ "disable_private_kg_auto_complete": True,
+ "disable_private_kg_query_ui_chips": True,
+ },
+ },
+ "app_type": 1,
+ "disable_analytics": True,
+ "session_config": {
+ "session_management_policy": 1,
+ "session_ttl": {"days": 433},
+ },
+ "features": {},
+ "cmek_config": {
+ "name": "name_value",
+ "kms_key": "kms_key_value",
+ "kms_key_version": "kms_key_version_value",
+ "state": 1,
+ "is_default": True,
+ "last_rotation_timestamp_micros": 3234,
+ "single_region_keys": [{"kms_key": "kms_key_value"}],
+ "notebooklm_state": 1,
+ },
+ "configurable_billing_approach": 1,
+ "model_configs": {},
+ "observability_config": {
+ "observability_enabled": True,
+ "sensitive_logging_enabled": True,
+ },
+ "connector_tenant_info": {},
+ "agent_gateway_setting": {
+ "default_egress_agent_gateway": {"name": "name_value"}
+ },
+ "marketplace_agent_visibility": 1,
+ "procurement_contact_emails": [
+ "procurement_contact_emails_value1",
+ "procurement_contact_emails_value2",
+ ],
+ "associated_agent_registry": "associated_agent_registry_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 = engine_service.CreateEngineRequest.meta.fields["engine"]
+
+ 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["engine"].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["engine"][field])):
+ del request_init["engine"][field][i][subfield]
+ else:
+ del request_init["engine"][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_engine(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_engine_rest_interceptors(null_interceptor):
+ transport = transports.EngineServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EngineServiceRestInterceptor(),
+ )
+ client = EngineServiceClient(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.EngineServiceRestInterceptor, "post_create_engine"
+ ) as post,
+ mock.patch.object(
+ transports.EngineServiceRestInterceptor, "post_create_engine_with_metadata"
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.EngineServiceRestInterceptor, "pre_create_engine"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = engine_service.CreateEngineRequest.pb(
+ engine_service.CreateEngineRequest()
+ )
+ 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 = engine_service.CreateEngineRequest()
+ 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_engine(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_delete_engine_rest_bad_request(
+ request_type=engine_service.DeleteEngineRequest,
+):
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/collections/sample3"}
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/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_engine(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ engine_service.DeleteEngineRequest,
+ dict,
+ ],
+)
+def test_delete_engine_rest_call_success(request_type):
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/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_engine(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_engine_rest_interceptors(null_interceptor):
+ transport = transports.EngineServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.EngineServiceRestInterceptor(),
+ )
+ client = EngineServiceClient(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.EngineServiceRestInterceptor, "post_delete_engine"
+ ) as post,
+ mock.patch.object(
+ transports.EngineServiceRestInterceptor, "post_delete_engine_with_metadata"
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.EngineServiceRestInterceptor, "pre_delete_engine"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = engine_service.DeleteEngineRequest.pb(
+ engine_service.DeleteEngineRequest()
+ )
+ 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 = engine_service.DeleteEngineRequest()
+ 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_engine(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_update_engine_rest_bad_request(
+ request_type=engine_service.UpdateEngineRequest,
+):
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "engine": {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ }
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -4385,23 +6006,27 @@ def test_create_engine_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_engine(request)
+ client.update_engine(request)
@pytest.mark.parametrize(
"request_type",
[
- engine_service.CreateEngineRequest,
+ engine_service.UpdateEngineRequest,
dict,
],
)
-def test_create_engine_rest_call_success(request_type):
+def test_update_engine_rest_call_success(request_type):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/collections/sample3"}
+ request_init = {
+ "engine": {
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ }
+ }
request_init["engine"] = {
"chat_engine_config": {
"agent_creation_config": {
@@ -4413,7 +6038,11 @@ def test_create_engine_rest_call_success(request_type):
"dialogflow_agent_to_link": "dialogflow_agent_to_link_value",
"allow_cross_region": True,
},
- "search_engine_config": {"search_tier": 1, "search_add_ons": [1]},
+ "search_engine_config": {
+ "search_tier": 1,
+ "required_subscription_tier": 1,
+ "search_add_ons": [1],
+ },
"media_recommendation_engine_config": {
"type_": "type__value",
"optimization_objective": "optimization_objective_value",
@@ -4430,7 +6059,7 @@ def test_create_engine_rest_call_success(request_type):
},
},
"chat_engine_metadata": {"dialogflow_agent": "dialogflow_agent_value"},
- "name": "name_value",
+ "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4",
"display_name": "display_name_value",
"create_time": {"seconds": 751, "nanos": 543},
"update_time": {},
@@ -4438,14 +6067,64 @@ def test_create_engine_rest_call_success(request_type):
"solution_type": 1,
"industry_vertical": 1,
"common_config": {"company_name": "company_name_value"},
+ "knowledge_graph_config": {
+ "enable_cloud_knowledge_graph": True,
+ "cloud_knowledge_graph_types": [
+ "cloud_knowledge_graph_types_value1",
+ "cloud_knowledge_graph_types_value2",
+ ],
+ "enable_private_knowledge_graph": True,
+ "private_knowledge_graph_types": [
+ "private_knowledge_graph_types_value1",
+ "private_knowledge_graph_types_value2",
+ ],
+ "feature_config": {
+ "disable_private_kg_query_understanding": True,
+ "disable_private_kg_enrichment": True,
+ "disable_private_kg_auto_complete": True,
+ "disable_private_kg_query_ui_chips": True,
+ },
+ },
+ "app_type": 1,
"disable_analytics": True,
+ "session_config": {
+ "session_management_policy": 1,
+ "session_ttl": {"days": 433},
+ },
+ "features": {},
+ "cmek_config": {
+ "name": "name_value",
+ "kms_key": "kms_key_value",
+ "kms_key_version": "kms_key_version_value",
+ "state": 1,
+ "is_default": True,
+ "last_rotation_timestamp_micros": 3234,
+ "single_region_keys": [{"kms_key": "kms_key_value"}],
+ "notebooklm_state": 1,
+ },
+ "configurable_billing_approach": 1,
+ "model_configs": {},
+ "observability_config": {
+ "observability_enabled": True,
+ "sensitive_logging_enabled": True,
+ },
+ "connector_tenant_info": {},
+ "agent_gateway_setting": {
+ "default_egress_agent_gateway": {"name": "name_value"}
+ },
+ "marketplace_agent_visibility": 1,
+ "procurement_contact_emails": [
+ "procurement_contact_emails_value1",
+ "procurement_contact_emails_value2",
+ ],
+ "associated_agent_registry": "associated_agent_registry_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 = engine_service.CreateEngineRequest.meta.fields["engine"]
+ test_field = engine_service.UpdateEngineRequest.meta.fields["engine"]
def get_message_fields(field):
# Given a field which is a message (composite type), return a list with
@@ -4512,23 +6191,55 @@ def get_message_fields(field):
# Mock the http request call within the method and fake a response.
with mock.patch.object(type(client.transport._session), "request") as req:
# Designate an appropriate value for the returned response.
- return_value = operations_pb2.Operation(name="operations/spam")
+ return_value = gcd_engine.Engine(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_ids=["data_store_ids_value"],
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ app_type=gcd_engine.Engine.AppType.APP_TYPE_INTRANET,
+ disable_analytics=True,
+ configurable_billing_approach=gcd_engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED,
+ marketplace_agent_visibility=gcd_engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY,
+ procurement_contact_emails=["procurement_contact_emails_value"],
+ associated_agent_registry="associated_agent_registry_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 = gcd_engine.Engine.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_engine(request)
+ response = client.update_engine(request)
# Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ assert isinstance(response, gcd_engine.Engine)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.data_store_ids == ["data_store_ids_value"]
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.app_type == gcd_engine.Engine.AppType.APP_TYPE_INTRANET
+ assert response.disable_analytics is True
+ assert (
+ response.configurable_billing_approach
+ == gcd_engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED
+ )
+ assert (
+ response.marketplace_agent_visibility
+ == gcd_engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY
+ )
+ assert response.procurement_contact_emails == ["procurement_contact_emails_value"]
+ assert response.associated_agent_registry == "associated_agent_registry_value"
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_create_engine_rest_interceptors(null_interceptor):
+def test_update_engine_rest_interceptors(null_interceptor):
transport = transports.EngineServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -4540,22 +6251,21 @@ def test_create_engine_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.EngineServiceRestInterceptor, "post_create_engine"
+ transports.EngineServiceRestInterceptor, "post_update_engine"
) as post,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "post_create_engine_with_metadata"
+ transports.EngineServiceRestInterceptor, "post_update_engine_with_metadata"
) as post_with_metadata,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "pre_create_engine"
+ transports.EngineServiceRestInterceptor, "pre_update_engine"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = engine_service.CreateEngineRequest.pb(
- engine_service.CreateEngineRequest()
+ pb_message = engine_service.UpdateEngineRequest.pb(
+ engine_service.UpdateEngineRequest()
)
transcode.return_value = {
"method": "post",
@@ -4567,19 +6277,19 @@ def test_create_engine_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 = gcd_engine.Engine.to_json(gcd_engine.Engine())
req.return_value.content = return_value
- request = engine_service.CreateEngineRequest()
+ request = engine_service.UpdateEngineRequest()
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 = gcd_engine.Engine()
+ post_with_metadata.return_value = gcd_engine.Engine(), metadata
- client.create_engine(
+ client.update_engine(
request,
metadata=[
("key", "val"),
@@ -4592,9 +6302,7 @@ def test_create_engine_rest_interceptors(null_interceptor):
post_with_metadata.assert_called_once()
-def test_delete_engine_rest_bad_request(
- request_type=engine_service.DeleteEngineRequest,
-):
+def test_get_engine_rest_bad_request(request_type=engine_service.GetEngineRequest):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
@@ -4617,17 +6325,17 @@ def test_delete_engine_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_engine(request)
+ client.get_engine(request)
@pytest.mark.parametrize(
"request_type",
[
- engine_service.DeleteEngineRequest,
+ engine_service.GetEngineRequest,
dict,
],
)
-def test_delete_engine_rest_call_success(request_type):
+def test_get_engine_rest_call_success(request_type):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
@@ -4641,23 +6349,55 @@ def test_delete_engine_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 = engine.Engine(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_ids=["data_store_ids_value"],
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ app_type=engine.Engine.AppType.APP_TYPE_INTRANET,
+ disable_analytics=True,
+ configurable_billing_approach=engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED,
+ marketplace_agent_visibility=engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY,
+ procurement_contact_emails=["procurement_contact_emails_value"],
+ associated_agent_registry="associated_agent_registry_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 = engine.Engine.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_engine(request)
+ response = client.get_engine(request)
# Establish that the response is the type that we expect.
- json_return_value = json_format.MessageToJson(return_value)
+ assert isinstance(response, engine.Engine)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.data_store_ids == ["data_store_ids_value"]
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.app_type == engine.Engine.AppType.APP_TYPE_INTRANET
+ assert response.disable_analytics is True
+ assert (
+ response.configurable_billing_approach
+ == engine.Engine.ConfigurableBillingApproach.CONFIGURABLE_BILLING_APPROACH_ENABLED
+ )
+ assert (
+ response.marketplace_agent_visibility
+ == engine.Engine.MarketplaceAgentVisibility.SHOW_AVAILABLE_AGENTS_ONLY
+ )
+ assert response.procurement_contact_emails == ["procurement_contact_emails_value"]
+ assert response.associated_agent_registry == "associated_agent_registry_value"
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_delete_engine_rest_interceptors(null_interceptor):
+def test_get_engine_rest_interceptors(null_interceptor):
transport = transports.EngineServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -4669,22 +6409,21 @@ def test_delete_engine_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.EngineServiceRestInterceptor, "post_delete_engine"
+ transports.EngineServiceRestInterceptor, "post_get_engine"
) as post,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "post_delete_engine_with_metadata"
+ transports.EngineServiceRestInterceptor, "post_get_engine_with_metadata"
) as post_with_metadata,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "pre_delete_engine"
+ transports.EngineServiceRestInterceptor, "pre_get_engine"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = engine_service.DeleteEngineRequest.pb(
- engine_service.DeleteEngineRequest()
+ pb_message = engine_service.GetEngineRequest.pb(
+ engine_service.GetEngineRequest()
)
transcode.return_value = {
"method": "post",
@@ -4696,19 +6435,19 @@ def test_delete_engine_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 = engine.Engine.to_json(engine.Engine())
req.return_value.content = return_value
- request = engine_service.DeleteEngineRequest()
+ request = engine_service.GetEngineRequest()
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 = engine.Engine()
+ post_with_metadata.return_value = engine.Engine(), metadata
- client.delete_engine(
+ client.get_engine(
request,
metadata=[
("key", "val"),
@@ -4721,18 +6460,12 @@ def test_delete_engine_rest_interceptors(null_interceptor):
post_with_metadata.assert_called_once()
-def test_update_engine_rest_bad_request(
- request_type=engine_service.UpdateEngineRequest,
-):
+def test_list_engines_rest_bad_request(request_type=engine_service.ListEnginesRequest):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
- request_init = {
- "engine": {
- "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
- }
- }
+ request_init = {"parent": "projects/sample1/locations/sample2/collections/sample3"}
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -4747,145 +6480,31 @@ def test_update_engine_rest_bad_request(
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_engine(request)
-
-
-@pytest.mark.parametrize(
- "request_type",
- [
- engine_service.UpdateEngineRequest,
- dict,
- ],
-)
-def test_update_engine_rest_call_success(request_type):
- client = EngineServiceClient(
- credentials=ga_credentials.AnonymousCredentials(), transport="rest"
- )
-
- # send a request that will satisfy transcoding
- request_init = {
- "engine": {
- "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
- }
- }
- request_init["engine"] = {
- "chat_engine_config": {
- "agent_creation_config": {
- "business": "business_value",
- "default_language_code": "default_language_code_value",
- "time_zone": "time_zone_value",
- "location": "location_value",
- },
- "dialogflow_agent_to_link": "dialogflow_agent_to_link_value",
- "allow_cross_region": True,
- },
- "search_engine_config": {"search_tier": 1, "search_add_ons": [1]},
- "media_recommendation_engine_config": {
- "type_": "type__value",
- "optimization_objective": "optimization_objective_value",
- "optimization_objective_config": {
- "target_field": "target_field_value",
- "target_field_value_float": 0.2523,
- },
- "training_state": 1,
- "engine_features_config": {
- "recommended_for_you_config": {
- "context_event_type": "context_event_type_value"
- },
- "most_popular_config": {"time_window_days": 1718},
- },
- },
- "chat_engine_metadata": {"dialogflow_agent": "dialogflow_agent_value"},
- "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4",
- "display_name": "display_name_value",
- "create_time": {"seconds": 751, "nanos": 543},
- "update_time": {},
- "data_store_ids": ["data_store_ids_value1", "data_store_ids_value2"],
- "solution_type": 1,
- "industry_vertical": 1,
- "common_config": {"company_name": "company_name_value"},
- "disable_analytics": 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 = engine_service.UpdateEngineRequest.meta.fields["engine"]
-
- 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["engine"].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.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.list_engines(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["engine"][field])):
- del request_init["engine"][field][i][subfield]
- else:
- del request_init["engine"][field][subfield]
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ engine_service.ListEnginesRequest,
+ dict,
+ ],
+)
+def test_list_engines_rest_call_success(request_type):
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/collections/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 = gcd_engine.Engine(
- name="name_value",
- display_name="display_name_value",
- data_store_ids=["data_store_ids_value"],
- solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
- industry_vertical=common.IndustryVertical.GENERIC,
- disable_analytics=True,
+ return_value = engine_service.ListEnginesResponse(
+ next_page_token="next_page_token_value",
)
# Wrap the value into a proper Response obj
@@ -4893,25 +6512,20 @@ def get_message_fields(field):
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = gcd_engine.Engine.pb(return_value)
+ return_value = engine_service.ListEnginesResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_engine(request)
+ response = client.list_engines(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, gcd_engine.Engine)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.data_store_ids == ["data_store_ids_value"]
- assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
- assert response.industry_vertical == common.IndustryVertical.GENERIC
- assert response.disable_analytics is True
+ assert isinstance(response, pagers.ListEnginesPager)
+ assert response.next_page_token == "next_page_token_value"
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_engine_rest_interceptors(null_interceptor):
+def test_list_engines_rest_interceptors(null_interceptor):
transport = transports.EngineServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -4924,20 +6538,20 @@ def test_update_engine_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.EngineServiceRestInterceptor, "post_update_engine"
+ transports.EngineServiceRestInterceptor, "post_list_engines"
) as post,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "post_update_engine_with_metadata"
+ transports.EngineServiceRestInterceptor, "post_list_engines_with_metadata"
) as post_with_metadata,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "pre_update_engine"
+ transports.EngineServiceRestInterceptor, "pre_list_engines"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = engine_service.UpdateEngineRequest.pb(
- engine_service.UpdateEngineRequest()
+ pb_message = engine_service.ListEnginesRequest.pb(
+ engine_service.ListEnginesRequest()
)
transcode.return_value = {
"method": "post",
@@ -4949,19 +6563,21 @@ def test_update_engine_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 = gcd_engine.Engine.to_json(gcd_engine.Engine())
+ return_value = engine_service.ListEnginesResponse.to_json(
+ engine_service.ListEnginesResponse()
+ )
req.return_value.content = return_value
- request = engine_service.UpdateEngineRequest()
+ request = engine_service.ListEnginesRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = gcd_engine.Engine()
- post_with_metadata.return_value = gcd_engine.Engine(), metadata
+ post.return_value = engine_service.ListEnginesResponse()
+ post_with_metadata.return_value = engine_service.ListEnginesResponse(), metadata
- client.update_engine(
+ client.list_engines(
request,
metadata=[
("key", "val"),
@@ -4974,13 +6590,15 @@ def test_update_engine_rest_interceptors(null_interceptor):
post_with_metadata.assert_called_once()
-def test_get_engine_rest_bad_request(request_type=engine_service.GetEngineRequest):
+def test_get_iam_policy_rest_bad_request(
+ request_type=iam_policy_pb2.GetIamPolicyRequest,
+):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ "resource": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
}
request = request_type(**request_init)
@@ -4997,63 +6615,52 @@ def test_get_engine_rest_bad_request(request_type=engine_service.GetEngineReques
response_value.request = mock.Mock()
req.return_value = response_value
req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
- client.get_engine(request)
+ client.get_iam_policy(request)
@pytest.mark.parametrize(
"request_type",
[
- engine_service.GetEngineRequest,
+ iam_policy_pb2.GetIamPolicyRequest,
dict,
],
)
-def test_get_engine_rest_call_success(request_type):
+def test_get_iam_policy_rest_call_success(request_type):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
request_init = {
- "name": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ "resource": "projects/sample1/locations/sample2/collections/sample3/engines/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 = engine.Engine(
- name="name_value",
- display_name="display_name_value",
- data_store_ids=["data_store_ids_value"],
- solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
- industry_vertical=common.IndustryVertical.GENERIC,
- disable_analytics=True,
+ return_value = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
)
# Wrap the value into a proper Response obj
response_value = mock.Mock()
response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = engine.Engine.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_engine(request)
+ response = client.get_iam_policy(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, engine.Engine)
- assert response.name == "name_value"
- assert response.display_name == "display_name_value"
- assert response.data_store_ids == ["data_store_ids_value"]
- assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
- assert response.industry_vertical == common.IndustryVertical.GENERIC
- assert response.disable_analytics is True
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_get_engine_rest_interceptors(null_interceptor):
+def test_get_iam_policy_rest_interceptors(null_interceptor):
transport = transports.EngineServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -5066,21 +6673,19 @@ def test_get_engine_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.EngineServiceRestInterceptor, "post_get_engine"
+ transports.EngineServiceRestInterceptor, "post_get_iam_policy"
) as post,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "post_get_engine_with_metadata"
+ transports.EngineServiceRestInterceptor, "post_get_iam_policy_with_metadata"
) as post_with_metadata,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "pre_get_engine"
+ transports.EngineServiceRestInterceptor, "pre_get_iam_policy"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = engine_service.GetEngineRequest.pb(
- engine_service.GetEngineRequest()
- )
+ pb_message = iam_policy_pb2.GetIamPolicyRequest()
transcode.return_value = {
"method": "post",
"uri": "my_uri",
@@ -5091,19 +6696,19 @@ def test_get_engine_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 = engine.Engine.to_json(engine.Engine())
+ return_value = json_format.MessageToJson(policy_pb2.Policy())
req.return_value.content = return_value
- request = engine_service.GetEngineRequest()
+ request = iam_policy_pb2.GetIamPolicyRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = engine.Engine()
- post_with_metadata.return_value = engine.Engine(), metadata
+ post.return_value = policy_pb2.Policy()
+ post_with_metadata.return_value = policy_pb2.Policy(), metadata
- client.get_engine(
+ client.get_iam_policy(
request,
metadata=[
("key", "val"),
@@ -5116,12 +6721,16 @@ def test_get_engine_rest_interceptors(null_interceptor):
post_with_metadata.assert_called_once()
-def test_list_engines_rest_bad_request(request_type=engine_service.ListEnginesRequest):
+def test_set_iam_policy_rest_bad_request(
+ request_type=iam_policy_pb2.SetIamPolicyRequest,
+):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/collections/sample3"}
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/engines/sample4"
+ }
request = request_type(**request_init)
# Mock the http request call within the method and fake a BadRequest error.
@@ -5137,51 +6746,52 @@ def test_list_engines_rest_bad_request(request_type=engine_service.ListEnginesRe
response_value.request = mock.Mock()
req.return_value = response_value
req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
- client.list_engines(request)
+ client.set_iam_policy(request)
@pytest.mark.parametrize(
"request_type",
[
- engine_service.ListEnginesRequest,
+ iam_policy_pb2.SetIamPolicyRequest,
dict,
],
)
-def test_list_engines_rest_call_success(request_type):
+def test_set_iam_policy_rest_call_success(request_type):
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(), transport="rest"
)
# send a request that will satisfy transcoding
- request_init = {"parent": "projects/sample1/locations/sample2/collections/sample3"}
+ request_init = {
+ "resource": "projects/sample1/locations/sample2/collections/sample3/engines/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 = engine_service.ListEnginesResponse(
- next_page_token="next_page_token_value",
+ return_value = policy_pb2.Policy(
+ version=774,
+ etag=b"etag_blob",
)
# Wrap the value into a proper Response obj
response_value = mock.Mock()
response_value.status_code = 200
-
- # Convert return value to protobuf type
- return_value = engine_service.ListEnginesResponse.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_engines(request)
+ response = client.set_iam_policy(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, pagers.ListEnginesPager)
- assert response.next_page_token == "next_page_token_value"
+ assert isinstance(response, policy_pb2.Policy)
+ assert response.version == 774
+ assert response.etag == b"etag_blob"
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_list_engines_rest_interceptors(null_interceptor):
+def test_set_iam_policy_rest_interceptors(null_interceptor):
transport = transports.EngineServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -5194,21 +6804,19 @@ def test_list_engines_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.EngineServiceRestInterceptor, "post_list_engines"
+ transports.EngineServiceRestInterceptor, "post_set_iam_policy"
) as post,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "post_list_engines_with_metadata"
+ transports.EngineServiceRestInterceptor, "post_set_iam_policy_with_metadata"
) as post_with_metadata,
mock.patch.object(
- transports.EngineServiceRestInterceptor, "pre_list_engines"
+ transports.EngineServiceRestInterceptor, "pre_set_iam_policy"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = engine_service.ListEnginesRequest.pb(
- engine_service.ListEnginesRequest()
- )
+ pb_message = iam_policy_pb2.SetIamPolicyRequest()
transcode.return_value = {
"method": "post",
"uri": "my_uri",
@@ -5219,21 +6827,19 @@ def test_list_engines_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 = engine_service.ListEnginesResponse.to_json(
- engine_service.ListEnginesResponse()
- )
+ return_value = json_format.MessageToJson(policy_pb2.Policy())
req.return_value.content = return_value
- request = engine_service.ListEnginesRequest()
+ request = iam_policy_pb2.SetIamPolicyRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = engine_service.ListEnginesResponse()
- post_with_metadata.return_value = engine_service.ListEnginesResponse(), metadata
+ post.return_value = policy_pb2.Policy()
+ post_with_metadata.return_value = policy_pb2.Policy(), metadata
- client.list_engines(
+ client.set_iam_policy(
request,
metadata=[
("key", "val"),
@@ -5535,6 +7141,44 @@ def test_list_engines_empty_call_rest():
assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_iam_policy_empty_call_rest():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call:
+ client.get_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.GetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_set_iam_policy_empty_call_rest():
+ client = EngineServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call:
+ client.set_iam_policy(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = iam_policy_pb2.SetIamPolicyRequest()
+ assert args[0] == request_msg
+
+
def test_engine_service_rest_lro_client():
client = EngineServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
@@ -5590,6 +7234,8 @@ def test_engine_service_base_transport():
"update_engine",
"get_engine",
"list_engines",
+ "get_iam_policy",
+ "set_iam_policy",
"get_operation",
"cancel_operation",
"list_operations",
@@ -5634,7 +7280,11 @@ def test_engine_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5660,7 +7310,11 @@ def test_engine_service_auth_adc():
EngineServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -5680,7 +7334,11 @@ def test_engine_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5733,7 +7391,11 @@ def test_engine_service_transport_create_channel(transport_class, grpc_helpers):
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -5878,6 +7540,12 @@ def test_engine_service_client_transport_session_collision(transport_name):
session1 = client1.transport.list_engines._session
session2 = client2.transport.list_engines._session
assert session1 != session2
+ session1 = client1.transport.get_iam_policy._session
+ session2 = client2.transport.get_iam_policy._session
+ assert session1 != session2
+ session1 = client1.transport.set_iam_policy._session
+ session2 = client2.transport.set_iam_policy._session
+ assert session1 != session2
def test_engine_service_grpc_transport_channel():
@@ -6039,10 +7707,61 @@ def test_engine_service_grpc_lro_async_client():
assert transport.operations_client is transport.operations_client
-def test_collection_path():
+def test_agent_gateway_path():
project = "squid"
location = "clam"
- collection = "whelk"
+ agent_gateway = "whelk"
+ expected = (
+ "projects/{project}/locations/{location}/agentGateways/{agent_gateway}".format(
+ project=project,
+ location=location,
+ agent_gateway=agent_gateway,
+ )
+ )
+ actual = EngineServiceClient.agent_gateway_path(project, location, agent_gateway)
+ assert expected == actual
+
+
+def test_parse_agent_gateway_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "agent_gateway": "nudibranch",
+ }
+ path = EngineServiceClient.agent_gateway_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EngineServiceClient.parse_agent_gateway_path(path)
+ assert expected == actual
+
+
+def test_cmek_config_path():
+ project = "cuttlefish"
+ location = "mussel"
+ expected = "projects/{project}/locations/{location}/cmekConfig".format(
+ project=project,
+ location=location,
+ )
+ actual = EngineServiceClient.cmek_config_path(project, location)
+ assert expected == actual
+
+
+def test_parse_cmek_config_path():
+ expected = {
+ "project": "winkle",
+ "location": "nautilus",
+ }
+ path = EngineServiceClient.cmek_config_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EngineServiceClient.parse_cmek_config_path(path)
+ assert expected == actual
+
+
+def test_collection_path():
+ project = "scallop"
+ location = "abalone"
+ collection = "squid"
expected = (
"projects/{project}/locations/{location}/collections/{collection}".format(
project=project,
@@ -6056,9 +7775,9 @@ def test_collection_path():
def test_parse_collection_path():
expected = {
- "project": "octopus",
- "location": "oyster",
- "collection": "nudibranch",
+ "project": "clam",
+ "location": "whelk",
+ "collection": "octopus",
}
path = EngineServiceClient.collection_path(**expected)
@@ -6067,11 +7786,76 @@ def test_parse_collection_path():
assert expected == actual
+def test_crypto_keys_path():
+ project = "oyster"
+ location = "nudibranch"
+ key_ring = "cuttlefish"
+ crypto_key = "mussel"
+ expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format(
+ project=project,
+ location=location,
+ key_ring=key_ring,
+ crypto_key=crypto_key,
+ )
+ actual = EngineServiceClient.crypto_keys_path(
+ project, location, key_ring, crypto_key
+ )
+ assert expected == actual
+
+
+def test_parse_crypto_keys_path():
+ expected = {
+ "project": "winkle",
+ "location": "nautilus",
+ "key_ring": "scallop",
+ "crypto_key": "abalone",
+ }
+ path = EngineServiceClient.crypto_keys_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EngineServiceClient.parse_crypto_keys_path(path)
+ assert expected == actual
+
+
+def test_crypto_key_versions_path():
+ project = "squid"
+ location = "clam"
+ key_ring = "whelk"
+ crypto_key = "octopus"
+ crypto_key_version = "oyster"
+ expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format(
+ project=project,
+ location=location,
+ key_ring=key_ring,
+ crypto_key=crypto_key,
+ crypto_key_version=crypto_key_version,
+ )
+ actual = EngineServiceClient.crypto_key_versions_path(
+ project, location, key_ring, crypto_key, crypto_key_version
+ )
+ assert expected == actual
+
+
+def test_parse_crypto_key_versions_path():
+ expected = {
+ "project": "nudibranch",
+ "location": "cuttlefish",
+ "key_ring": "mussel",
+ "crypto_key": "winkle",
+ "crypto_key_version": "nautilus",
+ }
+ path = EngineServiceClient.crypto_key_versions_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = EngineServiceClient.parse_crypto_key_versions_path(path)
+ assert expected == actual
+
+
def test_engine_path():
- project = "cuttlefish"
- location = "mussel"
- collection = "winkle"
- engine = "nautilus"
+ project = "scallop"
+ location = "abalone"
+ collection = "squid"
+ engine = "clam"
expected = "projects/{project}/locations/{location}/collections/{collection}/engines/{engine}".format(
project=project,
location=location,
@@ -6084,10 +7868,10 @@ def test_engine_path():
def test_parse_engine_path():
expected = {
- "project": "scallop",
- "location": "abalone",
- "collection": "squid",
- "engine": "clam",
+ "project": "whelk",
+ "location": "octopus",
+ "collection": "oyster",
+ "engine": "nudibranch",
}
path = EngineServiceClient.engine_path(**expected)
@@ -6097,7 +7881,7 @@ def test_parse_engine_path():
def test_common_billing_account_path():
- billing_account = "whelk"
+ billing_account = "cuttlefish"
expected = "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@@ -6107,7 +7891,7 @@ def test_common_billing_account_path():
def test_parse_common_billing_account_path():
expected = {
- "billing_account": "octopus",
+ "billing_account": "mussel",
}
path = EngineServiceClient.common_billing_account_path(**expected)
@@ -6117,7 +7901,7 @@ def test_parse_common_billing_account_path():
def test_common_folder_path():
- folder = "oyster"
+ folder = "winkle"
expected = "folders/{folder}".format(
folder=folder,
)
@@ -6127,7 +7911,7 @@ def test_common_folder_path():
def test_parse_common_folder_path():
expected = {
- "folder": "nudibranch",
+ "folder": "nautilus",
}
path = EngineServiceClient.common_folder_path(**expected)
@@ -6137,7 +7921,7 @@ def test_parse_common_folder_path():
def test_common_organization_path():
- organization = "cuttlefish"
+ organization = "scallop"
expected = "organizations/{organization}".format(
organization=organization,
)
@@ -6147,7 +7931,7 @@ def test_common_organization_path():
def test_parse_common_organization_path():
expected = {
- "organization": "mussel",
+ "organization": "abalone",
}
path = EngineServiceClient.common_organization_path(**expected)
@@ -6157,7 +7941,7 @@ def test_parse_common_organization_path():
def test_common_project_path():
- project = "winkle"
+ project = "squid"
expected = "projects/{project}".format(
project=project,
)
@@ -6167,7 +7951,7 @@ def test_common_project_path():
def test_parse_common_project_path():
expected = {
- "project": "nautilus",
+ "project": "clam",
}
path = EngineServiceClient.common_project_path(**expected)
@@ -6177,8 +7961,8 @@ def test_parse_common_project_path():
def test_common_location_path():
- project = "scallop"
- location = "abalone"
+ project = "whelk"
+ location = "octopus"
expected = "projects/{project}/locations/{location}".format(
project=project,
location=location,
@@ -6189,8 +7973,8 @@ def test_common_location_path():
def test_parse_common_location_path():
expected = {
- "project": "squid",
- "location": "clam",
+ "project": "oyster",
+ "location": "nudibranch",
}
path = EngineServiceClient.common_location_path(**expected)
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_grounded_generation_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_grounded_generation_service.py
index daff37255d31..2fb0a0040ad7 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_grounded_generation_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_grounded_generation_service.py
@@ -1105,7 +1105,11 @@ def test_grounded_generation_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -2863,7 +2867,11 @@ def test_grounded_generation_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2889,7 +2897,11 @@ def test_grounded_generation_service_auth_adc():
GroundedGenerationServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -2909,7 +2921,11 @@ def test_grounded_generation_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2964,7 +2980,11 @@ def test_grounded_generation_service_transport_create_channel(
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_identity_mapping_store_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_identity_mapping_store_service.py
index d620e2b341d8..cd46cddf441a 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_identity_mapping_store_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_identity_mapping_store_service.py
@@ -1120,7 +1120,11 @@ def test_identity_mapping_store_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -7019,7 +7023,11 @@ def test_identity_mapping_store_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -7045,7 +7053,11 @@ def test_identity_mapping_store_service_auth_adc():
IdentityMappingStoreServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -7065,7 +7077,11 @@ def test_identity_mapping_store_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -7125,7 +7141,11 @@ def test_identity_mapping_store_service_transport_create_channel(
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_license_config_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_license_config_service.py
new file mode 100644
index 000000000000..dfb50237a4f1
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_license_config_service.py
@@ -0,0 +1,7918 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import asyncio
+import json
+import math
+import os
+from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
+from unittest import mock
+from unittest.mock import AsyncMock
+
+import grpc
+import pytest
+from google.api_core import api_core_version
+from google.protobuf import json_format
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
+
+try:
+ from google.auth.aio import credentials as ga_credentials_async
+
+ HAS_GOOGLE_AUTH_AIO = True
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_AUTH_AIO = False
+
+import google.auth
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
+import google.type.date_pb2 as date_pb2 # type: ignore
+from google.api_core import (
+ client_options,
+ gapic_v1,
+ grpc_helpers,
+ grpc_helpers_async,
+ path_template,
+)
+from google.api_core import exceptions as core_exceptions
+from google.api_core import retry as retries
+from google.auth import credentials as ga_credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.location import locations_pb2
+from google.longrunning import operations_pb2 # type: ignore
+from google.oauth2 import service_account
+
+from google.cloud.discoveryengine_v1.services.license_config_service import (
+ LicenseConfigServiceAsyncClient,
+ LicenseConfigServiceClient,
+ pagers,
+ transports,
+)
+from google.cloud.discoveryengine_v1.types import (
+ common,
+ license_config,
+ license_config_service,
+)
+from google.cloud.discoveryengine_v1.types import license_config as gcd_license_config
+
+CRED_INFO_JSON = {
+ "credential_source": "/path/to/file",
+ "credential_type": "service account credentials",
+ "principal": "service-account@example.com",
+}
+CRED_INFO_STRING = json.dumps(CRED_INFO_JSON)
+
+
+@pytest.fixture(autouse=True)
+def disable_mtls_env():
+ with mock.patch.dict(
+ os.environ,
+ {
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false",
+ "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false",
+ },
+ ):
+ yield
+
+
+async def mock_async_gen(data, chunk_size=1):
+ for i in range(0, len(data)): # pragma: NO COVER
+ chunk = data[i : i + chunk_size]
+ yield chunk.encode("utf-8")
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
+# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
+def async_anonymous_credentials():
+ if HAS_GOOGLE_AUTH_AIO:
+ return ga_credentials_async.AnonymousCredentials()
+ return ga_credentials.AnonymousCredentials()
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+# If default endpoint template is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint template so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint_template(client):
+ return (
+ "test.{UNIVERSE_DOMAIN}"
+ if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE)
+ else client._DEFAULT_ENDPOINT_TEMPLATE
+ )
+
+
+@pytest.fixture(autouse=True)
+def set_event_loop():
+ try:
+ asyncio.get_running_loop()
+ yield
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ yield
+ finally:
+ loop.close()
+ asyncio.set_event_loop(None)
+
+
+def test__get_client_cert_source():
+ mock_provided_cert_source = mock.Mock()
+ mock_default_cert_source = mock.Mock()
+
+ assert LicenseConfigServiceClient._get_client_cert_source(None, False) is None
+ assert (
+ LicenseConfigServiceClient._get_client_cert_source(
+ mock_provided_cert_source, False
+ )
+ is None
+ )
+ assert (
+ LicenseConfigServiceClient._get_client_cert_source(
+ mock_provided_cert_source, True
+ )
+ == mock_provided_cert_source
+ )
+
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source", return_value=True
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_default_cert_source,
+ ):
+ assert (
+ LicenseConfigServiceClient._get_client_cert_source(None, True)
+ is mock_default_cert_source
+ )
+ assert (
+ LicenseConfigServiceClient._get_client_cert_source(
+ mock_provided_cert_source, "true"
+ )
+ is mock_provided_cert_source
+ )
+
+
+@pytest.mark.parametrize(
+ "error_code,cred_info_json,show_cred_info",
+ [
+ (401, CRED_INFO_JSON, True),
+ (403, CRED_INFO_JSON, True),
+ (404, CRED_INFO_JSON, True),
+ (500, CRED_INFO_JSON, False),
+ (401, None, False),
+ (403, None, False),
+ (404, None, False),
+ (500, None, False),
+ ],
+)
+def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info):
+ cred = mock.Mock(["get_cred_info"])
+ cred.get_cred_info = mock.Mock(return_value=cred_info_json)
+ client = LicenseConfigServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=["foo"])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ if show_cred_info:
+ assert error.details == ["foo", CRED_INFO_STRING]
+ else:
+ assert error.details == ["foo"]
+
+
+@pytest.mark.parametrize("error_code", [401, 403, 404, 500])
+def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code):
+ cred = mock.Mock([])
+ assert not hasattr(cred, "get_cred_info")
+ client = LicenseConfigServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=[])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ assert error.details == []
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (LicenseConfigServiceClient, "grpc"),
+ (LicenseConfigServiceAsyncClient, "grpc_asyncio"),
+ (LicenseConfigServiceClient, "rest"),
+ ],
+)
+def test_license_config_service_client_from_service_account_info(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info, transport=transport_name)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.LicenseConfigServiceGrpcTransport, "grpc"),
+ (transports.LicenseConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ (transports.LicenseConfigServiceRestTransport, "rest"),
+ ],
+)
+def test_license_config_service_client_service_account_always_use_jwt(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=False)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (LicenseConfigServiceClient, "grpc"),
+ (LicenseConfigServiceAsyncClient, "grpc_asyncio"),
+ (LicenseConfigServiceClient, "rest"),
+ ],
+)
+def test_license_config_service_client_from_service_account_file(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+def test_license_config_service_client_get_transport_class():
+ transport = LicenseConfigServiceClient.get_transport_class()
+ available_transports = [
+ transports.LicenseConfigServiceGrpcTransport,
+ transports.LicenseConfigServiceRestTransport,
+ ]
+ assert transport in available_transports
+
+ transport = LicenseConfigServiceClient.get_transport_class("grpc")
+ assert transport == transports.LicenseConfigServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ LicenseConfigServiceAsyncClient,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceRestTransport,
+ "rest",
+ ),
+ ],
+)
+@mock.patch.object(
+ LicenseConfigServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LicenseConfigServiceClient),
+)
+@mock.patch.object(
+ LicenseConfigServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LicenseConfigServiceAsyncClient),
+)
+def test_license_config_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(LicenseConfigServiceClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(LicenseConfigServiceClient, "get_transport_class") as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name, client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ # Check the case quota_project_id is provided
+ options = client_options.ClientOptions(quota_project_id="octopus")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id="octopus",
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+ # Check the case api_endpoint is provided
+ options = client_options.ClientOptions(
+ api_audience="https://language.googleapis.com"
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience="https://language.googleapis.com",
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceGrpcTransport,
+ "grpc",
+ "true",
+ ),
+ (
+ LicenseConfigServiceAsyncClient,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceGrpcTransport,
+ "grpc",
+ "false",
+ ),
+ (
+ LicenseConfigServiceAsyncClient,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceRestTransport,
+ "rest",
+ "true",
+ ),
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceRestTransport,
+ "rest",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ LicenseConfigServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LicenseConfigServiceClient),
+)
+@mock.patch.object(
+ LicenseConfigServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LicenseConfigServiceAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_license_config_service_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [LicenseConfigServiceClient, LicenseConfigServiceAsyncClient]
+)
+@mock.patch.object(
+ LicenseConfigServiceClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(LicenseConfigServiceClient),
+)
+@mock.patch.object(
+ LicenseConfigServiceAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(LicenseConfigServiceAsyncClient),
+)
+def test_license_config_service_client_get_mtls_endpoint_and_cert_source(client_class):
+ mock_client_cert_source = mock.Mock()
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source == mock_client_cert_source
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported".
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset.
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None)
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None)
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty).
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "")
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "")
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_client_cert_source,
+ ):
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source()
+ )
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source == mock_client_cert_source
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [LicenseConfigServiceClient, LicenseConfigServiceAsyncClient]
+)
+@mock.patch.object(
+ LicenseConfigServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LicenseConfigServiceClient),
+)
+@mock.patch.object(
+ LicenseConfigServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(LicenseConfigServiceAsyncClient),
+)
+def test_license_config_service_client_client_api_endpoint(client_class):
+ mock_client_cert_source = client_cert_source_callback
+ api_override = "foo.com"
+ default_universe = LicenseConfigServiceClient._DEFAULT_UNIVERSE
+ default_endpoint = LicenseConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = LicenseConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true",
+ # use ClientOptions.api_endpoint as the api endpoint regardless.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=api_override
+ )
+ client = client_class(
+ client_options=options,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert client.api_endpoint == api_override
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == default_endpoint
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always",
+ # use the DEFAULT_MTLS_ENDPOINT as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+
+ # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default),
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist,
+ # and ClientOptions.universe_domain="bar.com",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint.
+ options = client_options.ClientOptions()
+ universe_exists = hasattr(options, "universe_domain")
+ if universe_exists:
+ options = client_options.ClientOptions(universe_domain=mock_universe)
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ else:
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == (
+ mock_endpoint if universe_exists else default_endpoint
+ )
+ assert client.universe_domain == (
+ mock_universe if universe_exists else default_universe
+ )
+
+ # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ options = client_options.ClientOptions()
+ if hasattr(options, "universe_domain"):
+ delattr(options, "universe_domain")
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == default_endpoint
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ LicenseConfigServiceAsyncClient,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceRestTransport,
+ "rest",
+ ),
+ ],
+)
+def test_license_config_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(
+ scopes=["1", "2"],
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ LicenseConfigServiceAsyncClient,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceRestTransport,
+ "rest",
+ None,
+ ),
+ ],
+)
+def test_license_config_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+def test_license_config_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.license_config_service.transports.LicenseConfigServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = LicenseConfigServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ LicenseConfigServiceClient,
+ transports.LicenseConfigServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ LicenseConfigServiceAsyncClient,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ ],
+)
+def test_license_config_service_client_create_channel_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # test that the credentials from file are saved and used as the credentials.
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(grpc_helpers, "create_channel") as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ file_creds = ga_credentials.AnonymousCredentials()
+ load_creds.return_value = (file_creds, None)
+ adc.return_value = (creds, None)
+ client = client_class(client_options=options, transport=transport_name)
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=file_creds,
+ credentials_file=None,
+ quota_project_id=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=None,
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.CreateLicenseConfigRequest(),
+ {},
+ ],
+)
+def test_create_license_config(request_type, transport: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=gcd_license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=True,
+ )
+ response = client.create_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.CreateLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_license_config.LicenseConfig)
+ assert response.name == "name_value"
+ assert response.license_count == 1387
+ assert (
+ response.subscription_tier == common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH
+ )
+ assert response.state == gcd_license_config.LicenseConfig.State.ACTIVE
+ assert response.auto_renew is True
+ assert (
+ response.subscription_term
+ == common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH
+ )
+ assert response.free_trial is True
+ assert response.gemini_bundle is True
+ assert response.early_terminated is True
+
+
+def test_create_license_config_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 = LicenseConfigServiceClient(
+ 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 = license_config_service.CreateLicenseConfigRequest(
+ parent="parent_value",
+ license_config_id="license_config_id_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_license_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.create_license_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.CreateLicenseConfigRequest(
+ parent="parent_value",
+ license_config_id="license_config_id_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_create_license_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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_license_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_license_config] = (
+ mock_rpc
+ )
+ request = {}
+ client.create_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_license_config(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_license_config_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 = LicenseConfigServiceAsyncClient(
+ 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_license_config
+ 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_license_config
+ ] = mock_rpc
+
+ request = {}
+ await client.create_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.create_license_config(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",
+ [
+ license_config_service.CreateLicenseConfigRequest(),
+ {},
+ ],
+)
+async def test_create_license_config_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = LicenseConfigServiceAsyncClient(
+ 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_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=gcd_license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=True,
+ )
+ )
+ response = await client.create_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.CreateLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_license_config.LicenseConfig)
+ assert response.name == "name_value"
+ assert response.license_count == 1387
+ assert (
+ response.subscription_tier == common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH
+ )
+ assert response.state == gcd_license_config.LicenseConfig.State.ACTIVE
+ assert response.auto_renew is True
+ assert (
+ response.subscription_term
+ == common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH
+ )
+ assert response.free_trial is True
+ assert response.gemini_bundle is True
+ assert response.early_terminated is True
+
+
+def test_create_license_config_field_headers():
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.CreateLicenseConfigRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_license_config), "__call__"
+ ) as call:
+ call.return_value = gcd_license_config.LicenseConfig()
+ client.create_license_config(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_license_config_field_headers_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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 = license_config_service.CreateLicenseConfigRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_license_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_license_config.LicenseConfig()
+ )
+ await client.create_license_config(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_license_config_flattened():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_license_config.LicenseConfig()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.create_license_config(
+ parent="parent_value",
+ license_config=gcd_license_config.LicenseConfig(name="name_value"),
+ license_config_id="license_config_id_value",
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+ arg = args[0].license_config
+ mock_val = gcd_license_config.LicenseConfig(name="name_value")
+ assert arg == mock_val
+ arg = args[0].license_config_id
+ mock_val = "license_config_id_value"
+ assert arg == mock_val
+
+
+def test_create_license_config_flattened_error():
+ client = LicenseConfigServiceClient(
+ 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_license_config(
+ license_config_service.CreateLicenseConfigRequest(),
+ parent="parent_value",
+ license_config=gcd_license_config.LicenseConfig(name="name_value"),
+ license_config_id="license_config_id_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_create_license_config_flattened_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_license_config.LicenseConfig()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_license_config.LicenseConfig()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.create_license_config(
+ parent="parent_value",
+ license_config=gcd_license_config.LicenseConfig(name="name_value"),
+ license_config_id="license_config_id_value",
+ )
+
+ # Establish that the underlying call was made with the expected
+ # request object values.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
+ arg = args[0].license_config
+ mock_val = gcd_license_config.LicenseConfig(name="name_value")
+ assert arg == mock_val
+ arg = args[0].license_config_id
+ mock_val = "license_config_id_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_create_license_config_flattened_error_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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_license_config(
+ license_config_service.CreateLicenseConfigRequest(),
+ parent="parent_value",
+ license_config=gcd_license_config.LicenseConfig(name="name_value"),
+ license_config_id="license_config_id_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.UpdateLicenseConfigRequest(),
+ {},
+ ],
+)
+def test_update_license_config(request_type, transport: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=gcd_license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=True,
+ )
+ response = client.update_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.UpdateLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_license_config.LicenseConfig)
+ assert response.name == "name_value"
+ assert response.license_count == 1387
+ assert (
+ response.subscription_tier == common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH
+ )
+ assert response.state == gcd_license_config.LicenseConfig.State.ACTIVE
+ assert response.auto_renew is True
+ assert (
+ response.subscription_term
+ == common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH
+ )
+ assert response.free_trial is True
+ assert response.gemini_bundle is True
+ assert response.early_terminated is True
+
+
+def test_update_license_config_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 = LicenseConfigServiceClient(
+ 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 = license_config_service.UpdateLicenseConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_license_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_license_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.UpdateLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_update_license_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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.update_license_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_license_config] = (
+ mock_rpc
+ )
+ request = {}
+ client.update_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_license_config(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_update_license_config_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 = LicenseConfigServiceAsyncClient(
+ 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.update_license_config
+ 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.update_license_config
+ ] = mock_rpc
+
+ request = {}
+ await client.update_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_license_config(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",
+ [
+ license_config_service.UpdateLicenseConfigRequest(),
+ {},
+ ],
+)
+async def test_update_license_config_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = LicenseConfigServiceAsyncClient(
+ 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.update_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=gcd_license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=True,
+ )
+ )
+ response = await client.update_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.UpdateLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_license_config.LicenseConfig)
+ assert response.name == "name_value"
+ assert response.license_count == 1387
+ assert (
+ response.subscription_tier == common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH
+ )
+ assert response.state == gcd_license_config.LicenseConfig.State.ACTIVE
+ assert response.auto_renew is True
+ assert (
+ response.subscription_term
+ == common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH
+ )
+ assert response.free_trial is True
+ assert response.gemini_bundle is True
+ assert response.early_terminated is True
+
+
+def test_update_license_config_field_headers():
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.UpdateLicenseConfigRequest()
+
+ request.license_config.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_license_config), "__call__"
+ ) as call:
+ call.return_value = gcd_license_config.LicenseConfig()
+ client.update_license_config(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",
+ "license_config.name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_license_config_field_headers_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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 = license_config_service.UpdateLicenseConfigRequest()
+
+ request.license_config.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_license_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_license_config.LicenseConfig()
+ )
+ await client.update_license_config(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",
+ "license_config.name=name_value",
+ ) in kw["metadata"]
+
+
+def test_update_license_config_flattened():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_license_config.LicenseConfig()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_license_config(
+ license_config=gcd_license_config.LicenseConfig(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].license_config
+ mock_val = gcd_license_config.LicenseConfig(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+def test_update_license_config_flattened_error():
+ client = LicenseConfigServiceClient(
+ 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_license_config(
+ license_config_service.UpdateLicenseConfigRequest(),
+ license_config=gcd_license_config.LicenseConfig(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_license_config_flattened_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_license_config.LicenseConfig()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_license_config.LicenseConfig()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_license_config(
+ license_config=gcd_license_config.LicenseConfig(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].license_config
+ mock_val = gcd_license_config.LicenseConfig(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_update_license_config_flattened_error_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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_license_config(
+ license_config_service.UpdateLicenseConfigRequest(),
+ license_config=gcd_license_config.LicenseConfig(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.GetLicenseConfigRequest(),
+ {},
+ ],
+)
+def test_get_license_config(request_type, transport: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=True,
+ )
+ response = client.get_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.GetLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, license_config.LicenseConfig)
+ assert response.name == "name_value"
+ assert response.license_count == 1387
+ assert (
+ response.subscription_tier == common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH
+ )
+ assert response.state == license_config.LicenseConfig.State.ACTIVE
+ assert response.auto_renew is True
+ assert (
+ response.subscription_term
+ == common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH
+ )
+ assert response.free_trial is True
+ assert response.gemini_bundle is True
+ assert response.early_terminated is True
+
+
+def test_get_license_config_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 = LicenseConfigServiceClient(
+ 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 = license_config_service.GetLicenseConfigRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_license_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_license_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.GetLicenseConfigRequest(
+ name="name_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_license_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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_license_config in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_license_config] = (
+ mock_rpc
+ )
+ request = {}
+ client.get_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_license_config(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_license_config_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 = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_license_config
+ 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_license_config
+ ] = mock_rpc
+
+ request = {}
+ await client.get_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_license_config(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",
+ [
+ license_config_service.GetLicenseConfigRequest(),
+ {},
+ ],
+)
+async def test_get_license_config_async(request_type, transport: str = "grpc_asyncio"):
+ client = LicenseConfigServiceAsyncClient(
+ 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_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=True,
+ )
+ )
+ response = await client.get_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.GetLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, license_config.LicenseConfig)
+ assert response.name == "name_value"
+ assert response.license_count == 1387
+ assert (
+ response.subscription_tier == common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH
+ )
+ assert response.state == license_config.LicenseConfig.State.ACTIVE
+ assert response.auto_renew is True
+ assert (
+ response.subscription_term
+ == common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH
+ )
+ assert response.free_trial is True
+ assert response.gemini_bundle is True
+ assert response.early_terminated is True
+
+
+def test_get_license_config_field_headers():
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.GetLicenseConfigRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_license_config), "__call__"
+ ) as call:
+ call.return_value = license_config.LicenseConfig()
+ client.get_license_config(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_license_config_field_headers_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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 = license_config_service.GetLicenseConfigRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_license_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config.LicenseConfig()
+ )
+ await client.get_license_config(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_license_config_flattened():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config.LicenseConfig()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_license_config(
+ 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_license_config_flattened_error():
+ client = LicenseConfigServiceClient(
+ 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_license_config(
+ license_config_service.GetLicenseConfigRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_license_config_flattened_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config.LicenseConfig()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config.LicenseConfig()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_license_config(
+ 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_license_config_flattened_error_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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_license_config(
+ license_config_service.GetLicenseConfigRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.ListLicenseConfigsRequest(),
+ {},
+ ],
+)
+def test_list_license_configs(request_type, transport: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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_license_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config_service.ListLicenseConfigsResponse(
+ next_page_token="next_page_token_value",
+ )
+ response = client.list_license_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.ListLicenseConfigsRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListLicenseConfigsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_license_configs_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 = LicenseConfigServiceClient(
+ 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 = license_config_service.ListLicenseConfigsRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ filter="filter_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_license_configs(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.ListLicenseConfigsRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ filter="filter_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_list_license_configs_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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_license_configs in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_license_configs] = (
+ mock_rpc
+ )
+ request = {}
+ client.list_license_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_license_configs(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_license_configs_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 = LicenseConfigServiceAsyncClient(
+ 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_license_configs
+ 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_license_configs
+ ] = mock_rpc
+
+ request = {}
+ await client.list_license_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_license_configs(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",
+ [
+ license_config_service.ListLicenseConfigsRequest(),
+ {},
+ ],
+)
+async def test_list_license_configs_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = LicenseConfigServiceAsyncClient(
+ 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_license_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.ListLicenseConfigsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_license_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.ListLicenseConfigsRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListLicenseConfigsAsyncPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_license_configs_field_headers():
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.ListLicenseConfigsRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs), "__call__"
+ ) as call:
+ call.return_value = license_config_service.ListLicenseConfigsResponse()
+ client.list_license_configs(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_license_configs_field_headers_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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 = license_config_service.ListLicenseConfigsRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.ListLicenseConfigsResponse()
+ )
+ await client.list_license_configs(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_license_configs_flattened():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config_service.ListLicenseConfigsResponse()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_license_configs(
+ 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_license_configs_flattened_error():
+ client = LicenseConfigServiceClient(
+ 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_license_configs(
+ license_config_service.ListLicenseConfigsRequest(),
+ parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_license_configs_flattened_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config_service.ListLicenseConfigsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.ListLicenseConfigsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_license_configs(
+ 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_license_configs_flattened_error_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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_license_configs(
+ license_config_service.ListLicenseConfigsRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_license_configs_pager(transport_name: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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_license_configs), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[],
+ next_page_token="def",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_license_configs(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, license_config.LicenseConfig) for i in results)
+
+
+def test_list_license_configs_pages(transport_name: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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_license_configs), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[],
+ next_page_token="def",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_license_configs(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_license_configs_async_pager():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[],
+ next_page_token="def",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_license_configs(
+ 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, license_config.LicenseConfig) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_license_configs_async_pages():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[],
+ next_page_token="def",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (await client.list_license_configs(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",
+ [
+ license_config_service.DistributeLicenseConfigRequest(),
+ {},
+ ],
+)
+def test_distribute_license_config(request_type, transport: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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.distribute_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config_service.DistributeLicenseConfigResponse()
+ response = client.distribute_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.DistributeLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, license_config_service.DistributeLicenseConfigResponse)
+
+
+def test_distribute_license_config_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 = LicenseConfigServiceClient(
+ 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 = license_config_service.DistributeLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ location="location_value",
+ license_config_id="license_config_id_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.distribute_license_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.distribute_license_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.DistributeLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ location="location_value",
+ license_config_id="license_config_id_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_distribute_license_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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.distribute_license_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.distribute_license_config
+ ] = mock_rpc
+ request = {}
+ client.distribute_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.distribute_license_config(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_distribute_license_config_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 = LicenseConfigServiceAsyncClient(
+ 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.distribute_license_config
+ 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.distribute_license_config
+ ] = mock_rpc
+
+ request = {}
+ await client.distribute_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.distribute_license_config(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",
+ [
+ license_config_service.DistributeLicenseConfigRequest(),
+ {},
+ ],
+)
+async def test_distribute_license_config_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = LicenseConfigServiceAsyncClient(
+ 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.distribute_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.DistributeLicenseConfigResponse()
+ )
+ response = await client.distribute_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.DistributeLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, license_config_service.DistributeLicenseConfigResponse)
+
+
+def test_distribute_license_config_field_headers():
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.DistributeLicenseConfigRequest()
+
+ request.billing_account_license_config = "billing_account_license_config_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.distribute_license_config), "__call__"
+ ) as call:
+ call.return_value = license_config_service.DistributeLicenseConfigResponse()
+ client.distribute_license_config(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",
+ "billing_account_license_config=billing_account_license_config_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_distribute_license_config_field_headers_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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 = license_config_service.DistributeLicenseConfigRequest()
+
+ request.billing_account_license_config = "billing_account_license_config_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.distribute_license_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.DistributeLicenseConfigResponse()
+ )
+ await client.distribute_license_config(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",
+ "billing_account_license_config=billing_account_license_config_value",
+ ) in kw["metadata"]
+
+
+def test_distribute_license_config_flattened():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.distribute_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config_service.DistributeLicenseConfigResponse()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.distribute_license_config(
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ license_config_id="license_config_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].billing_account_license_config
+ mock_val = "billing_account_license_config_value"
+ assert arg == mock_val
+ arg = args[0].project_number
+ mock_val = 1503
+ assert arg == mock_val
+ arg = args[0].location
+ mock_val = "location_value"
+ assert arg == mock_val
+ arg = args[0].license_count
+ mock_val = 1387
+ assert arg == mock_val
+ arg = args[0].license_config_id
+ mock_val = "license_config_id_value"
+ assert arg == mock_val
+
+
+def test_distribute_license_config_flattened_error():
+ client = LicenseConfigServiceClient(
+ 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.distribute_license_config(
+ license_config_service.DistributeLicenseConfigRequest(),
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ license_config_id="license_config_id_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_distribute_license_config_flattened_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.distribute_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config_service.DistributeLicenseConfigResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.DistributeLicenseConfigResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.distribute_license_config(
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ license_config_id="license_config_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].billing_account_license_config
+ mock_val = "billing_account_license_config_value"
+ assert arg == mock_val
+ arg = args[0].project_number
+ mock_val = 1503
+ assert arg == mock_val
+ arg = args[0].location
+ mock_val = "location_value"
+ assert arg == mock_val
+ arg = args[0].license_count
+ mock_val = 1387
+ assert arg == mock_val
+ arg = args[0].license_config_id
+ mock_val = "license_config_id_value"
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_distribute_license_config_flattened_error_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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.distribute_license_config(
+ license_config_service.DistributeLicenseConfigRequest(),
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ license_config_id="license_config_id_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.RetractLicenseConfigRequest(),
+ {},
+ ],
+)
+def test_retract_license_config(request_type, transport: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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.retract_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config_service.RetractLicenseConfigResponse()
+ response = client.retract_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.RetractLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, license_config_service.RetractLicenseConfigResponse)
+
+
+def test_retract_license_config_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 = LicenseConfigServiceClient(
+ 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 = license_config_service.RetractLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.retract_license_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.retract_license_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.RetractLicenseConfigRequest(
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_retract_license_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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.retract_license_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.retract_license_config] = (
+ mock_rpc
+ )
+ request = {}
+ client.retract_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.retract_license_config(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_retract_license_config_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 = LicenseConfigServiceAsyncClient(
+ 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.retract_license_config
+ 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.retract_license_config
+ ] = mock_rpc
+
+ request = {}
+ await client.retract_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.retract_license_config(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",
+ [
+ license_config_service.RetractLicenseConfigRequest(),
+ {},
+ ],
+)
+async def test_retract_license_config_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = LicenseConfigServiceAsyncClient(
+ 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.retract_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.RetractLicenseConfigResponse()
+ )
+ response = await client.retract_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = license_config_service.RetractLicenseConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, license_config_service.RetractLicenseConfigResponse)
+
+
+def test_retract_license_config_field_headers():
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.RetractLicenseConfigRequest()
+
+ request.billing_account_license_config = "billing_account_license_config_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.retract_license_config), "__call__"
+ ) as call:
+ call.return_value = license_config_service.RetractLicenseConfigResponse()
+ client.retract_license_config(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",
+ "billing_account_license_config=billing_account_license_config_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_retract_license_config_field_headers_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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 = license_config_service.RetractLicenseConfigRequest()
+
+ request.billing_account_license_config = "billing_account_license_config_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.retract_license_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.RetractLicenseConfigResponse()
+ )
+ await client.retract_license_config(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",
+ "billing_account_license_config=billing_account_license_config_value",
+ ) in kw["metadata"]
+
+
+def test_retract_license_config_flattened():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.retract_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config_service.RetractLicenseConfigResponse()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.retract_license_config(
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ full_retract=True,
+ license_count=1387,
+ )
+
+ # 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].billing_account_license_config
+ mock_val = "billing_account_license_config_value"
+ assert arg == mock_val
+ arg = args[0].license_config
+ mock_val = "license_config_value"
+ assert arg == mock_val
+ arg = args[0].full_retract
+ mock_val = True
+ assert arg == mock_val
+ arg = args[0].license_count
+ mock_val = 1387
+ assert arg == mock_val
+
+
+def test_retract_license_config_flattened_error():
+ client = LicenseConfigServiceClient(
+ 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.retract_license_config(
+ license_config_service.RetractLicenseConfigRequest(),
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ full_retract=True,
+ license_count=1387,
+ )
+
+
+@pytest.mark.asyncio
+async def test_retract_license_config_flattened_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.retract_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = license_config_service.RetractLicenseConfigResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.RetractLicenseConfigResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.retract_license_config(
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ full_retract=True,
+ license_count=1387,
+ )
+
+ # 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].billing_account_license_config
+ mock_val = "billing_account_license_config_value"
+ assert arg == mock_val
+ arg = args[0].license_config
+ mock_val = "license_config_value"
+ assert arg == mock_val
+ arg = args[0].full_retract
+ mock_val = True
+ assert arg == mock_val
+ arg = args[0].license_count
+ mock_val = 1387
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_retract_license_config_flattened_error_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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.retract_license_config(
+ license_config_service.RetractLicenseConfigRequest(),
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ full_retract=True,
+ license_count=1387,
+ )
+
+
+def test_create_license_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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_license_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_license_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.create_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_license_config(request)
+
+ # Establish 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_license_config_rest_required_fields(
+ request_type=license_config_service.CreateLicenseConfigRequest,
+):
+ transport_class = transports.LicenseConfigServiceRestTransport
+
+ 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._BaseCreateLicenseConfig,
+ "_BaseCreateLicenseConfig__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(("licenseConfigId",))
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
+
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_license_config.LicenseConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = gcd_license_config.LicenseConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_license_config(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_license_config_rest_flattened():
+ client = LicenseConfigServiceClient(
+ 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 = gcd_license_config.LicenseConfig()
+
+ # 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",
+ license_config=gcd_license_config.LicenseConfig(name="name_value"),
+ license_config_id="license_config_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 = gcd_license_config.LicenseConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_license_config(**mock_args)
+
+ # Establish that the underlying call 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/*}/licenseConfigs"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_create_license_config_rest_flattened_error(transport: str = "rest"):
+ client = LicenseConfigServiceClient(
+ 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_license_config(
+ license_config_service.CreateLicenseConfigRequest(),
+ parent="parent_value",
+ license_config=gcd_license_config.LicenseConfig(name="name_value"),
+ license_config_id="license_config_id_value",
+ )
+
+
+def test_update_license_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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_license_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_license_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.update_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_license_config(request)
+
+ # Establish 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_license_config_rest_required_fields(
+ request_type=license_config_service.UpdateLicenseConfigRequest,
+):
+ transport_class = transports.LicenseConfigServiceRestTransport
+
+ 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._BaseUpdateLicenseConfig,
+ "_BaseUpdateLicenseConfig__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(("updateMask",))
+
+ # verify required fields with non-default values are left alone
+
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_license_config.LicenseConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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
+
+ # Convert return value to protobuf type
+ return_value = gcd_license_config.LicenseConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_license_config(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_license_config_rest_flattened():
+ client = LicenseConfigServiceClient(
+ 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 = gcd_license_config.LicenseConfig()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "license_config": {
+ "name": "projects/sample1/locations/sample2/licenseConfigs/sample3"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ license_config=gcd_license_config.LicenseConfig(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
+ # Convert return value to protobuf type
+ return_value = gcd_license_config.LicenseConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_license_config(**mock_args)
+
+ # Establish that the underlying call 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/{license_config.name=projects/*/locations/*/licenseConfigs/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_update_license_config_rest_flattened_error(transport: str = "rest"):
+ client = LicenseConfigServiceClient(
+ 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_license_config(
+ license_config_service.UpdateLicenseConfigRequest(),
+ license_config=gcd_license_config.LicenseConfig(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_get_license_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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_license_config in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_license_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.get_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_license_config(request)
+
+ # Establish 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_license_config_rest_required_fields(
+ request_type=license_config_service.GetLicenseConfigRequest,
+):
+ transport_class = transports.LicenseConfigServiceRestTransport
+
+ 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._BaseGetLicenseConfig,
+ "_BaseGetLicenseConfig__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 = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = license_config.LicenseConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = license_config.LicenseConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_license_config(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_license_config_rest_flattened():
+ client = LicenseConfigServiceClient(
+ 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 = license_config.LicenseConfig()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/licenseConfigs/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 = license_config.LicenseConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_license_config(**mock_args)
+
+ # Establish that the underlying call 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/*/licenseConfigs/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_license_config_rest_flattened_error(transport: str = "rest"):
+ client = LicenseConfigServiceClient(
+ 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_license_config(
+ license_config_service.GetLicenseConfigRequest(),
+ name="name_value",
+ )
+
+
+def test_list_license_configs_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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_license_configs in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_license_configs] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.list_license_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_license_configs(request)
+
+ # Establish 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_license_configs_rest_required_fields(
+ request_type=license_config_service.ListLicenseConfigsRequest,
+):
+ transport_class = transports.LicenseConfigServiceRestTransport
+
+ 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._BaseListLicenseConfigs,
+ "_BaseListLicenseConfigs__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 = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = license_config_service.ListLicenseConfigsResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = license_config_service.ListLicenseConfigsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_license_configs(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_license_configs_rest_flattened():
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.ListLicenseConfigsResponse()
+
+ # 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 = license_config_service.ListLicenseConfigsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_license_configs(**mock_args)
+
+ # Establish that the underlying call 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/*}/licenseConfigs"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_list_license_configs_rest_flattened_error(transport: str = "rest"):
+ client = LicenseConfigServiceClient(
+ 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_license_configs(
+ license_config_service.ListLicenseConfigsRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_license_configs_rest_pager(transport: str = "rest"):
+ client = LicenseConfigServiceClient(
+ 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 = (
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[],
+ next_page_token="def",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ license_config_service.ListLicenseConfigsResponse(
+ license_configs=[
+ license_config.LicenseConfig(),
+ license_config.LicenseConfig(),
+ ],
+ ),
+ )
+ # Two responses for two calls
+ response = response + response
+
+ # Wrap the values into proper Response objs
+ response = tuple(
+ license_config_service.ListLicenseConfigsResponse.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_license_configs(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, license_config.LicenseConfig) for i in results)
+
+ pages = list(client.list_license_configs(request=sample_request).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_distribute_license_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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.distribute_license_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[
+ client._transport.distribute_license_config
+ ] = mock_rpc
+
+ request = {}
+ client.distribute_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.distribute_license_config(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_distribute_license_config_rest_required_fields(
+ request_type=license_config_service.DistributeLicenseConfigRequest,
+):
+ transport_class = transports.LicenseConfigServiceRestTransport
+
+ request_init = {}
+ request_init["billing_account_license_config"] = ""
+ request_init["project_number"] = 0
+ request_init["location"] = ""
+ request_init["license_count"] = 0
+ request = 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._BaseDistributeLicenseConfig,
+ "_BaseDistributeLicenseConfig__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["billingAccountLicenseConfig"] = (
+ "billing_account_license_config_value"
+ )
+ jsonified_request["projectNumber"] = 1503
+ jsonified_request["location"] = "location_value"
+ jsonified_request["licenseCount"] = 1387
+
+ # verify required fields with non-default values are left alone
+ assert "billingAccountLicenseConfig" in jsonified_request
+ assert (
+ jsonified_request["billingAccountLicenseConfig"]
+ == "billing_account_license_config_value"
+ )
+ assert "projectNumber" in jsonified_request
+ assert jsonified_request["projectNumber"] == 1503
+ assert "location" in jsonified_request
+ assert jsonified_request["location"] == "location_value"
+ assert "licenseCount" in jsonified_request
+ assert jsonified_request["licenseCount"] == 1387
+
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = license_config_service.DistributeLicenseConfigResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = license_config_service.DistributeLicenseConfigResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.distribute_license_config(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_distribute_license_config_rest_flattened():
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.DistributeLicenseConfigResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "billing_account_license_config": "billingAccounts/sample1/billingAccountLicenseConfigs/sample2"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ license_config_id="license_config_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 = license_config_service.DistributeLicenseConfigResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ client.distribute_license_config(**mock_args)
+
+ # Establish that the underlying call 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/{billing_account_license_config=billingAccounts/*/billingAccountLicenseConfigs/*}:distributeLicenseConfig"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_distribute_license_config_rest_flattened_error(transport: str = "rest"):
+ client = LicenseConfigServiceClient(
+ 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.distribute_license_config(
+ license_config_service.DistributeLicenseConfigRequest(),
+ billing_account_license_config="billing_account_license_config_value",
+ project_number=1503,
+ location="location_value",
+ license_count=1387,
+ license_config_id="license_config_id_value",
+ )
+
+
+def test_retract_license_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = LicenseConfigServiceClient(
+ 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.retract_license_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.Mock()
+ mock_rpc.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client._transport._wrapped_methods[client._transport.retract_license_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.retract_license_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.retract_license_config(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+def test_retract_license_config_rest_required_fields(
+ request_type=license_config_service.RetractLicenseConfigRequest,
+):
+ transport_class = transports.LicenseConfigServiceRestTransport
+
+ request_init = {}
+ request_init["billing_account_license_config"] = ""
+ request_init["license_config"] = ""
+ request = 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._BaseRetractLicenseConfig,
+ "_BaseRetractLicenseConfig__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["billingAccountLicenseConfig"] = (
+ "billing_account_license_config_value"
+ )
+ jsonified_request["licenseConfig"] = "license_config_value"
+
+ # verify required fields with non-default values are left alone
+ assert "billingAccountLicenseConfig" in jsonified_request
+ assert (
+ jsonified_request["billingAccountLicenseConfig"]
+ == "billing_account_license_config_value"
+ )
+ assert "licenseConfig" in jsonified_request
+ assert jsonified_request["licenseConfig"] == "license_config_value"
+
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = license_config_service.RetractLicenseConfigResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = license_config_service.RetractLicenseConfigResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.retract_license_config(request)
+
+ expected_params = [("$alt", "json;enum-encoding=int")]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_retract_license_config_rest_flattened():
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.RetractLicenseConfigResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "billing_account_license_config": "billingAccounts/sample1/billingAccountLicenseConfigs/sample2"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ full_retract=True,
+ license_count=1387,
+ )
+ 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 = license_config_service.RetractLicenseConfigResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ client.retract_license_config(**mock_args)
+
+ # Establish that the underlying call 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/{billing_account_license_config=billingAccounts/*/billingAccountLicenseConfigs/*}:retractLicenseConfig"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_retract_license_config_rest_flattened_error(transport: str = "rest"):
+ client = LicenseConfigServiceClient(
+ 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.retract_license_config(
+ license_config_service.RetractLicenseConfigRequest(),
+ billing_account_license_config="billing_account_license_config_value",
+ license_config="license_config_value",
+ full_retract=True,
+ license_count=1387,
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.LicenseConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.LicenseConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = LicenseConfigServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.LicenseConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = LicenseConfigServiceClient(
+ 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 = LicenseConfigServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.LicenseConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = LicenseConfigServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.LicenseConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = LicenseConfigServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.LicenseConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.LicenseConfigServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.LicenseConfigServiceGrpcTransport,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ transports.LicenseConfigServiceRestTransport,
+ ],
+)
+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 = LicenseConfigServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = LicenseConfigServiceClient(
+ 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_create_license_config_empty_call_grpc():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_license_config), "__call__"
+ ) as call:
+ call.return_value = gcd_license_config.LicenseConfig()
+ client.create_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.CreateLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_license_config_empty_call_grpc():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_license_config), "__call__"
+ ) as call:
+ call.return_value = gcd_license_config.LicenseConfig()
+ client.update_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.UpdateLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_license_config_empty_call_grpc():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_license_config), "__call__"
+ ) as call:
+ call.return_value = license_config.LicenseConfig()
+ client.get_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.GetLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_license_configs_empty_call_grpc():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs), "__call__"
+ ) as call:
+ call.return_value = license_config_service.ListLicenseConfigsResponse()
+ client.list_license_configs(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.ListLicenseConfigsRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_distribute_license_config_empty_call_grpc():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.distribute_license_config), "__call__"
+ ) as call:
+ call.return_value = license_config_service.DistributeLicenseConfigResponse()
+ client.distribute_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.DistributeLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_retract_license_config_empty_call_grpc():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.retract_license_config), "__call__"
+ ) as call:
+ call.return_value = license_config_service.RetractLicenseConfigResponse()
+ client.retract_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.RetractLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = LicenseConfigServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = LicenseConfigServiceAsyncClient(
+ 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_create_license_config_empty_call_grpc_asyncio():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=gcd_license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=True,
+ )
+ )
+ await client.create_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.CreateLicenseConfigRequest()
+ assert args[0] == request_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_license_config_empty_call_grpc_asyncio():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=gcd_license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=True,
+ )
+ )
+ await client.update_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.UpdateLicenseConfigRequest()
+ assert args[0] == request_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_license_config_empty_call_grpc_asyncio():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=True,
+ )
+ )
+ await client.get_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.GetLicenseConfigRequest()
+ assert args[0] == request_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_license_configs_empty_call_grpc_asyncio():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.ListLicenseConfigsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ await client.list_license_configs(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.ListLicenseConfigsRequest()
+ assert args[0] == request_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_distribute_license_config_empty_call_grpc_asyncio():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.distribute_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.DistributeLicenseConfigResponse()
+ )
+ await client.distribute_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.DistributeLicenseConfigRequest()
+ assert args[0] == request_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_retract_license_config_empty_call_grpc_asyncio():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.retract_license_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ license_config_service.RetractLicenseConfigResponse()
+ )
+ await client.retract_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.RetractLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = LicenseConfigServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_create_license_config_rest_bad_request(
+ request_type=license_config_service.CreateLicenseConfigRequest,
+):
+ client = LicenseConfigServiceClient(
+ 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_license_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.CreateLicenseConfigRequest,
+ dict,
+ ],
+)
+def test_create_license_config_rest_call_success(request_type):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2"}
+ request_init["license_config"] = {
+ "name": "name_value",
+ "license_count": 1387,
+ "subscription_tier": 1,
+ "state": 1,
+ "auto_renew": True,
+ "start_date": {"year": 433, "month": 550, "day": 318},
+ "end_date": {},
+ "subscription_term": 1,
+ "free_trial": True,
+ "gemini_bundle": True,
+ "early_terminated": True,
+ "early_termination_date": {},
+ "last_user_update_time": {"seconds": 751, "nanos": 543},
+ }
+ # 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 = license_config_service.CreateLicenseConfigRequest.meta.fields[
+ "license_config"
+ ]
+
+ 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["license_config"].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["license_config"][field])):
+ del request_init["license_config"][field][i][subfield]
+ else:
+ del request_init["license_config"][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 = gcd_license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=gcd_license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=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 = gcd_license_config.LicenseConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_license_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_license_config.LicenseConfig)
+ assert response.name == "name_value"
+ assert response.license_count == 1387
+ assert (
+ response.subscription_tier == common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH
+ )
+ assert response.state == gcd_license_config.LicenseConfig.State.ACTIVE
+ assert response.auto_renew is True
+ assert (
+ response.subscription_term
+ == common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH
+ )
+ assert response.free_trial is True
+ assert response.gemini_bundle is True
+ assert response.early_terminated is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_license_config_rest_interceptors(null_interceptor):
+ transport = transports.LicenseConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.LicenseConfigServiceRestInterceptor(),
+ )
+ client = LicenseConfigServiceClient(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.LicenseConfigServiceRestInterceptor, "post_create_license_config"
+ ) as post,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor,
+ "post_create_license_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor, "pre_create_license_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = license_config_service.CreateLicenseConfigRequest.pb(
+ license_config_service.CreateLicenseConfigRequest()
+ )
+ 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 = gcd_license_config.LicenseConfig.to_json(
+ gcd_license_config.LicenseConfig()
+ )
+ req.return_value.content = return_value
+
+ request = license_config_service.CreateLicenseConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcd_license_config.LicenseConfig()
+ post_with_metadata.return_value = gcd_license_config.LicenseConfig(), metadata
+
+ client.create_license_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_update_license_config_rest_bad_request(
+ request_type=license_config_service.UpdateLicenseConfigRequest,
+):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "license_config": {
+ "name": "projects/sample1/locations/sample2/licenseConfigs/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_license_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.UpdateLicenseConfigRequest,
+ dict,
+ ],
+)
+def test_update_license_config_rest_call_success(request_type):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "license_config": {
+ "name": "projects/sample1/locations/sample2/licenseConfigs/sample3"
+ }
+ }
+ request_init["license_config"] = {
+ "name": "projects/sample1/locations/sample2/licenseConfigs/sample3",
+ "license_count": 1387,
+ "subscription_tier": 1,
+ "state": 1,
+ "auto_renew": True,
+ "start_date": {"year": 433, "month": 550, "day": 318},
+ "end_date": {},
+ "subscription_term": 1,
+ "free_trial": True,
+ "gemini_bundle": True,
+ "early_terminated": True,
+ "early_termination_date": {},
+ "last_user_update_time": {"seconds": 751, "nanos": 543},
+ }
+ # 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 = license_config_service.UpdateLicenseConfigRequest.meta.fields[
+ "license_config"
+ ]
+
+ 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["license_config"].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["license_config"][field])):
+ del request_init["license_config"][field][i][subfield]
+ else:
+ del request_init["license_config"][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 = gcd_license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=gcd_license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=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 = gcd_license_config.LicenseConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_license_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_license_config.LicenseConfig)
+ assert response.name == "name_value"
+ assert response.license_count == 1387
+ assert (
+ response.subscription_tier == common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH
+ )
+ assert response.state == gcd_license_config.LicenseConfig.State.ACTIVE
+ assert response.auto_renew is True
+ assert (
+ response.subscription_term
+ == common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH
+ )
+ assert response.free_trial is True
+ assert response.gemini_bundle is True
+ assert response.early_terminated is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_license_config_rest_interceptors(null_interceptor):
+ transport = transports.LicenseConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.LicenseConfigServiceRestInterceptor(),
+ )
+ client = LicenseConfigServiceClient(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.LicenseConfigServiceRestInterceptor, "post_update_license_config"
+ ) as post,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor,
+ "post_update_license_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor, "pre_update_license_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = license_config_service.UpdateLicenseConfigRequest.pb(
+ license_config_service.UpdateLicenseConfigRequest()
+ )
+ 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 = gcd_license_config.LicenseConfig.to_json(
+ gcd_license_config.LicenseConfig()
+ )
+ req.return_value.content = return_value
+
+ request = license_config_service.UpdateLicenseConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcd_license_config.LicenseConfig()
+ post_with_metadata.return_value = gcd_license_config.LicenseConfig(), metadata
+
+ client.update_license_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_get_license_config_rest_bad_request(
+ request_type=license_config_service.GetLicenseConfigRequest,
+):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/licenseConfigs/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_license_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.GetLicenseConfigRequest,
+ dict,
+ ],
+)
+def test_get_license_config_rest_call_success(request_type):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/licenseConfigs/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 = license_config.LicenseConfig(
+ name="name_value",
+ license_count=1387,
+ subscription_tier=common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH,
+ state=license_config.LicenseConfig.State.ACTIVE,
+ auto_renew=True,
+ subscription_term=common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH,
+ free_trial=True,
+ gemini_bundle=True,
+ early_terminated=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 = license_config.LicenseConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_license_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, license_config.LicenseConfig)
+ assert response.name == "name_value"
+ assert response.license_count == 1387
+ assert (
+ response.subscription_tier == common.SubscriptionTier.SUBSCRIPTION_TIER_SEARCH
+ )
+ assert response.state == license_config.LicenseConfig.State.ACTIVE
+ assert response.auto_renew is True
+ assert (
+ response.subscription_term
+ == common.SubscriptionTerm.SUBSCRIPTION_TERM_ONE_MONTH
+ )
+ assert response.free_trial is True
+ assert response.gemini_bundle is True
+ assert response.early_terminated is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_license_config_rest_interceptors(null_interceptor):
+ transport = transports.LicenseConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.LicenseConfigServiceRestInterceptor(),
+ )
+ client = LicenseConfigServiceClient(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.LicenseConfigServiceRestInterceptor, "post_get_license_config"
+ ) as post,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor,
+ "post_get_license_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor, "pre_get_license_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = license_config_service.GetLicenseConfigRequest.pb(
+ license_config_service.GetLicenseConfigRequest()
+ )
+ 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 = license_config.LicenseConfig.to_json(
+ license_config.LicenseConfig()
+ )
+ req.return_value.content = return_value
+
+ request = license_config_service.GetLicenseConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = license_config.LicenseConfig()
+ post_with_metadata.return_value = license_config.LicenseConfig(), metadata
+
+ client.get_license_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_list_license_configs_rest_bad_request(
+ request_type=license_config_service.ListLicenseConfigsRequest,
+):
+ client = LicenseConfigServiceClient(
+ 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_license_configs(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.ListLicenseConfigsRequest,
+ dict,
+ ],
+)
+def test_list_license_configs_rest_call_success(request_type):
+ client = LicenseConfigServiceClient(
+ 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 = license_config_service.ListLicenseConfigsResponse(
+ 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 = license_config_service.ListLicenseConfigsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_license_configs(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListLicenseConfigsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_license_configs_rest_interceptors(null_interceptor):
+ transport = transports.LicenseConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.LicenseConfigServiceRestInterceptor(),
+ )
+ client = LicenseConfigServiceClient(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.LicenseConfigServiceRestInterceptor, "post_list_license_configs"
+ ) as post,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor,
+ "post_list_license_configs_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor, "pre_list_license_configs"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = license_config_service.ListLicenseConfigsRequest.pb(
+ license_config_service.ListLicenseConfigsRequest()
+ )
+ 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 = license_config_service.ListLicenseConfigsResponse.to_json(
+ license_config_service.ListLicenseConfigsResponse()
+ )
+ req.return_value.content = return_value
+
+ request = license_config_service.ListLicenseConfigsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = license_config_service.ListLicenseConfigsResponse()
+ post_with_metadata.return_value = (
+ license_config_service.ListLicenseConfigsResponse(),
+ metadata,
+ )
+
+ client.list_license_configs(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_distribute_license_config_rest_bad_request(
+ request_type=license_config_service.DistributeLicenseConfigRequest,
+):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "billing_account_license_config": "billingAccounts/sample1/billingAccountLicenseConfigs/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.distribute_license_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.DistributeLicenseConfigRequest,
+ dict,
+ ],
+)
+def test_distribute_license_config_rest_call_success(request_type):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "billing_account_license_config": "billingAccounts/sample1/billingAccountLicenseConfigs/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 = license_config_service.DistributeLicenseConfigResponse()
+
+ # 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 = license_config_service.DistributeLicenseConfigResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ response = client.distribute_license_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, license_config_service.DistributeLicenseConfigResponse)
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_distribute_license_config_rest_interceptors(null_interceptor):
+ transport = transports.LicenseConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.LicenseConfigServiceRestInterceptor(),
+ )
+ client = LicenseConfigServiceClient(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.LicenseConfigServiceRestInterceptor,
+ "post_distribute_license_config",
+ ) as post,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor,
+ "post_distribute_license_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor,
+ "pre_distribute_license_config",
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = license_config_service.DistributeLicenseConfigRequest.pb(
+ license_config_service.DistributeLicenseConfigRequest()
+ )
+ 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 = license_config_service.DistributeLicenseConfigResponse.to_json(
+ license_config_service.DistributeLicenseConfigResponse()
+ )
+ req.return_value.content = return_value
+
+ request = license_config_service.DistributeLicenseConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = license_config_service.DistributeLicenseConfigResponse()
+ post_with_metadata.return_value = (
+ license_config_service.DistributeLicenseConfigResponse(),
+ metadata,
+ )
+
+ client.distribute_license_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_retract_license_config_rest_bad_request(
+ request_type=license_config_service.RetractLicenseConfigRequest,
+):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "billing_account_license_config": "billingAccounts/sample1/billingAccountLicenseConfigs/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.retract_license_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ license_config_service.RetractLicenseConfigRequest,
+ dict,
+ ],
+)
+def test_retract_license_config_rest_call_success(request_type):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "billing_account_license_config": "billingAccounts/sample1/billingAccountLicenseConfigs/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 = license_config_service.RetractLicenseConfigResponse()
+
+ # 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 = license_config_service.RetractLicenseConfigResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ response = client.retract_license_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, license_config_service.RetractLicenseConfigResponse)
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_retract_license_config_rest_interceptors(null_interceptor):
+ transport = transports.LicenseConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.LicenseConfigServiceRestInterceptor(),
+ )
+ client = LicenseConfigServiceClient(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.LicenseConfigServiceRestInterceptor,
+ "post_retract_license_config",
+ ) as post,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor,
+ "post_retract_license_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.LicenseConfigServiceRestInterceptor, "pre_retract_license_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = license_config_service.RetractLicenseConfigRequest.pb(
+ license_config_service.RetractLicenseConfigRequest()
+ )
+ 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 = license_config_service.RetractLicenseConfigResponse.to_json(
+ license_config_service.RetractLicenseConfigResponse()
+ )
+ req.return_value.content = return_value
+
+ request = license_config_service.RetractLicenseConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = license_config_service.RetractLicenseConfigResponse()
+ post_with_metadata.return_value = (
+ license_config_service.RetractLicenseConfigResponse(),
+ metadata,
+ )
+
+ client.retract_license_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_cancel_operation_rest_bad_request(
+ request_type=operations_pb2.CancelOperationRequest,
+):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = "{}"
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.cancel_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_get_operation_rest_bad_request(
+ request_type=operations_pb2.GetOperationRequest,
+):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.get_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_list_operations_rest_bad_request(
+ request_type=operations_pb2.ListOperationsRequest,
+):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.list_operations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_initialize_client_w_rest():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_create_license_config_empty_call_rest():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_license_config), "__call__"
+ ) as call:
+ client.create_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.CreateLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_license_config_empty_call_rest():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_license_config), "__call__"
+ ) as call:
+ client.update_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.UpdateLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_license_config_empty_call_rest():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_license_config), "__call__"
+ ) as call:
+ client.get_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.GetLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_license_configs_empty_call_rest():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs), "__call__"
+ ) as call:
+ client.list_license_configs(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.ListLicenseConfigsRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_distribute_license_config_empty_call_rest():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.distribute_license_config), "__call__"
+ ) as call:
+ client.distribute_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.DistributeLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_retract_license_config_empty_call_rest():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.retract_license_config), "__call__"
+ ) as call:
+ client.retract_license_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = license_config_service.RetractLicenseConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert isinstance(
+ client.transport,
+ transports.LicenseConfigServiceGrpcTransport,
+ )
+
+
+def test_license_config_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
+ transport = transports.LicenseConfigServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_license_config_service_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.license_config_service.transports.LicenseConfigServiceTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.LicenseConfigServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "create_license_config",
+ "update_license_config",
+ "get_license_config",
+ "list_license_configs",
+ "distribute_license_config",
+ "retract_license_config",
+ "get_operation",
+ "cancel_operation",
+ "list_operations",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ with pytest.raises(NotImplementedError):
+ transport.close()
+
+ # Catch all for all remaining methods and properties
+ remainder = [
+ "kind",
+ ]
+ for r in remainder:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, r)()
+
+
+def test_license_config_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.license_config_service.transports.LicenseConfigServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.LicenseConfigServiceTransport(
+ credentials_file="credentials.json",
+ quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_license_config_service_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.license_config_service.transports.LicenseConfigServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.LicenseConfigServiceTransport()
+ adc.assert_called_once()
+
+
+def test_license_config_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ LicenseConfigServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.LicenseConfigServiceGrpcTransport,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_license_config_service_transport_auth_adc(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.LicenseConfigServiceGrpcTransport,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ transports.LicenseConfigServiceRestTransport,
+ ],
+)
+def test_license_config_service_transport_auth_gdch_credentials(transport_class):
+ host = "https://language.com"
+ api_audience_tests = [None, "https://language2.com"]
+ api_audience_expect = [host, "https://language2.com"]
+ for t, e in zip(api_audience_tests, api_audience_expect):
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ gdch_mock = mock.MagicMock()
+ type(gdch_mock).with_gdch_audience = mock.PropertyMock(
+ return_value=gdch_mock
+ )
+ adc.return_value = (gdch_mock, None)
+ transport_class(host=host, api_audience=t)
+ gdch_mock.with_gdch_audience.assert_called_once_with(e)
+
+
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.LicenseConfigServiceGrpcTransport, grpc_helpers),
+ (transports.LicenseConfigServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_license_config_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=["1", "2"],
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.LicenseConfigServiceGrpcTransport,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_license_config_service_grpc_transport_client_cert_source_for_mtls(
+ transport_class,
+):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_license_config_service_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.LicenseConfigServiceRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_license_config_service_host_no_port(transport_name):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_license_config_service_host_with_port(transport_name):
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com:8000"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:8000"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com:8000"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "rest",
+ ],
+)
+def test_license_config_service_client_transport_session_collision(transport_name):
+ creds1 = ga_credentials.AnonymousCredentials()
+ creds2 = ga_credentials.AnonymousCredentials()
+ client1 = LicenseConfigServiceClient(
+ credentials=creds1,
+ transport=transport_name,
+ )
+ client2 = LicenseConfigServiceClient(
+ credentials=creds2,
+ transport=transport_name,
+ )
+ session1 = client1.transport.create_license_config._session
+ session2 = client2.transport.create_license_config._session
+ assert session1 != session2
+ session1 = client1.transport.update_license_config._session
+ session2 = client2.transport.update_license_config._session
+ assert session1 != session2
+ session1 = client1.transport.get_license_config._session
+ session2 = client2.transport.get_license_config._session
+ assert session1 != session2
+ session1 = client1.transport.list_license_configs._session
+ session2 = client2.transport.list_license_configs._session
+ assert session1 != session2
+ session1 = client1.transport.distribute_license_config._session
+ session2 = client2.transport.distribute_license_config._session
+ assert session1 != session2
+ session1 = client1.transport.retract_license_config._session
+ session2 = client2.transport.retract_license_config._session
+ assert session1 != session2
+
+
+def test_license_config_service_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.LicenseConfigServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_license_config_service_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.LicenseConfigServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.filterwarnings("ignore::FutureWarning")
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.LicenseConfigServiceGrpcTransport,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_license_config_service_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = ga_credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.LicenseConfigServiceGrpcTransport,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_license_config_service_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_billing_account_license_config_path():
+ billing_account = "squid"
+ billing_account_license_config = "clam"
+ expected = "billingAccounts/{billing_account}/billingAccountLicenseConfigs/{billing_account_license_config}".format(
+ billing_account=billing_account,
+ billing_account_license_config=billing_account_license_config,
+ )
+ actual = LicenseConfigServiceClient.billing_account_license_config_path(
+ billing_account, billing_account_license_config
+ )
+ assert expected == actual
+
+
+def test_parse_billing_account_license_config_path():
+ expected = {
+ "billing_account": "whelk",
+ "billing_account_license_config": "octopus",
+ }
+ path = LicenseConfigServiceClient.billing_account_license_config_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = LicenseConfigServiceClient.parse_billing_account_license_config_path(path)
+ assert expected == actual
+
+
+def test_license_config_path():
+ project = "oyster"
+ location = "nudibranch"
+ license_config = "cuttlefish"
+ expected = "projects/{project}/locations/{location}/licenseConfigs/{license_config}".format(
+ project=project,
+ location=location,
+ license_config=license_config,
+ )
+ actual = LicenseConfigServiceClient.license_config_path(
+ project, location, license_config
+ )
+ assert expected == actual
+
+
+def test_parse_license_config_path():
+ expected = {
+ "project": "mussel",
+ "location": "winkle",
+ "license_config": "nautilus",
+ }
+ path = LicenseConfigServiceClient.license_config_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = LicenseConfigServiceClient.parse_license_config_path(path)
+ assert expected == actual
+
+
+def test_location_path():
+ project = "scallop"
+ location = "abalone"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = LicenseConfigServiceClient.location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_location_path():
+ expected = {
+ "project": "squid",
+ "location": "clam",
+ }
+ path = LicenseConfigServiceClient.location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = LicenseConfigServiceClient.parse_location_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "whelk"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = LicenseConfigServiceClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "octopus",
+ }
+ path = LicenseConfigServiceClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = LicenseConfigServiceClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "oyster"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = LicenseConfigServiceClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "nudibranch",
+ }
+ path = LicenseConfigServiceClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = LicenseConfigServiceClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "cuttlefish"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = LicenseConfigServiceClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "mussel",
+ }
+ path = LicenseConfigServiceClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = LicenseConfigServiceClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "winkle"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = LicenseConfigServiceClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "nautilus",
+ }
+ path = LicenseConfigServiceClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = LicenseConfigServiceClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "scallop"
+ location = "abalone"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = LicenseConfigServiceClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "squid",
+ "location": "clam",
+ }
+ path = LicenseConfigServiceClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = LicenseConfigServiceClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.LicenseConfigServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.LicenseConfigServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = LicenseConfigServiceClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+def test_cancel_operation(transport: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
+ client = LicenseConfigServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+def test_cancel_operation_field_headers():
+ client = LicenseConfigServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = None
+
+ client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_field_headers_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_cancel_operation_from_dict():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_from_dict_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_cancel_operation_flattened():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_flattened_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+def test_get_operation(transport: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+@pytest.mark.asyncio
+async def test_get_operation_async(transport: str = "grpc_asyncio"):
+ client = LicenseConfigServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_get_operation_field_headers():
+ client = LicenseConfigServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_operation_field_headers_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_get_operation_from_dict():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ response = client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_from_dict_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_get_operation_flattened():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_flattened_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+def test_list_operations(transport: str = "grpc"):
+ client = LicenseConfigServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+ response = client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+@pytest.mark.asyncio
+async def test_list_operations_async(transport: str = "grpc_asyncio"):
+ client = LicenseConfigServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_list_operations_field_headers():
+ client = LicenseConfigServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_operations_field_headers_async():
+ client = LicenseConfigServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+def test_list_operations_from_dict():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ response = client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_from_dict_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_list_operations_flattened():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_flattened_async():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+def test_transport_close_grpc():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+@pytest.mark.asyncio
+async def test_transport_close_grpc_asyncio():
+ client = LicenseConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_transport_close_rest():
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_session")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_client_ctx():
+ transports = [
+ "rest",
+ "grpc",
+ ]
+ for transport in transports:
+ client = LicenseConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ # Test client calls underlying transport.
+ with mock.patch.object(type(client.transport), "close") as close:
+ close.assert_not_called()
+ with client:
+ pass
+ close.assert_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class",
+ [
+ (LicenseConfigServiceClient, transports.LicenseConfigServiceGrpcTransport),
+ (
+ LicenseConfigServiceAsyncClient,
+ transports.LicenseConfigServiceGrpcAsyncIOTransport,
+ ),
+ ],
+)
+def test_api_key_credentials(client_class, transport_class):
+ with mock.patch.object(
+ google.auth._default, "get_api_key_credentials", create=True
+ ) as get_api_key_credentials:
+ mock_cred = mock.Mock()
+ get_api_key_credentials.return_value = mock_cred
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=mock_cred,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_project_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_project_service.py
index 07d23ac95a36..ead803270499 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_project_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_project_service.py
@@ -1050,7 +1050,11 @@ def test_project_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -2195,7 +2199,11 @@ def test_project_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2221,7 +2229,11 @@ def test_project_service_auth_adc():
ProjectServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -2241,7 +2253,11 @@ def test_project_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2294,7 +2310,11 @@ def test_project_service_transport_create_channel(transport_class, grpc_helpers)
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -2590,8 +2610,36 @@ def test_project_service_grpc_lro_async_client():
assert transport.operations_client is transport.operations_client
+def test_content_policy_path():
+ organization = "squid"
+ location = "clam"
+ content_policy = "whelk"
+ expected = "organizations/{organization}/locations/{location}/contentPolicies/{content_policy}".format(
+ organization=organization,
+ location=location,
+ content_policy=content_policy,
+ )
+ actual = ProjectServiceClient.content_policy_path(
+ organization, location, content_policy
+ )
+ assert expected == actual
+
+
+def test_parse_content_policy_path():
+ expected = {
+ "organization": "octopus",
+ "location": "oyster",
+ "content_policy": "nudibranch",
+ }
+ path = ProjectServiceClient.content_policy_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ProjectServiceClient.parse_content_policy_path(path)
+ assert expected == actual
+
+
def test_project_path():
- project = "squid"
+ project = "cuttlefish"
expected = "projects/{project}".format(
project=project,
)
@@ -2601,7 +2649,7 @@ def test_project_path():
def test_parse_project_path():
expected = {
- "project": "clam",
+ "project": "mussel",
}
path = ProjectServiceClient.project_path(**expected)
@@ -2610,6 +2658,32 @@ def test_parse_project_path():
assert expected == actual
+def test_template_path():
+ project = "winkle"
+ location = "nautilus"
+ template = "scallop"
+ expected = "projects/{project}/locations/{location}/templates/{template}".format(
+ project=project,
+ location=location,
+ template=template,
+ )
+ actual = ProjectServiceClient.template_path(project, location, template)
+ assert expected == actual
+
+
+def test_parse_template_path():
+ expected = {
+ "project": "abalone",
+ "location": "squid",
+ "template": "clam",
+ }
+ path = ProjectServiceClient.template_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = ProjectServiceClient.parse_template_path(path)
+ assert expected == actual
+
+
def test_common_billing_account_path():
billing_account = "whelk"
expected = "billingAccounts/{billing_account}".format(
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_rank_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_rank_service.py
index 9a81fd2ac305..0f35a1aee36f 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_rank_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_rank_service.py
@@ -1028,7 +1028,11 @@ def test_rank_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -1966,7 +1970,11 @@ def test_rank_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -1992,7 +2000,11 @@ def test_rank_service_auth_adc():
RankServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -2012,7 +2024,11 @@ def test_rank_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2065,7 +2081,11 @@ def test_rank_service_transport_create_channel(transport_class, grpc_helpers):
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_recommendation_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_recommendation_service.py
index 979ac5fa6591..a8c6c309818e 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_recommendation_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_recommendation_service.py
@@ -42,6 +42,7 @@
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.type.latlng_pb2 as latlng_pb2 # type: ignore
from google.api_core import (
client_options,
gapic_v1,
@@ -64,7 +65,9 @@
)
from google.cloud.discoveryengine_v1.types import (
common,
+ feedback,
recommendation_service,
+ session,
user_event,
)
@@ -1102,7 +1105,11 @@ def test_recommendation_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -2080,7 +2087,11 @@ def test_recommendation_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2106,7 +2117,11 @@ def test_recommendation_service_auth_adc():
RecommendationServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -2126,7 +2141,11 @@ def test_recommendation_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2179,7 +2198,11 @@ def test_recommendation_service_transport_create_channel(transport_class, grpc_h
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_schema_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_schema_service.py
index 43aa14073703..6a01b50572c5 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_schema_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_schema_service.py
@@ -1054,7 +1054,11 @@ def test_schema_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -5310,7 +5314,11 @@ def test_schema_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5336,7 +5344,11 @@ def test_schema_service_auth_adc():
SchemaServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -5356,7 +5368,11 @@ def test_schema_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5409,7 +5425,11 @@ def test_schema_service_transport_create_channel(transport_class, grpc_helpers):
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_service.py
index ee8f038337ed..20f46be396b5 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_service.py
@@ -40,6 +40,7 @@
import google.auth
import google.protobuf.struct_pb2 as struct_pb2 # type: ignore
+import google.type.latlng_pb2 as latlng_pb2 # type: ignore
from google.api_core import (
client_options,
gapic_v1,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_tuning_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_tuning_service.py
index 49d50c90666d..35ae7bddce38 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_tuning_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_search_tuning_service.py
@@ -1103,7 +1103,11 @@ def test_search_tuning_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -2684,7 +2688,11 @@ def test_search_tuning_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2710,7 +2718,11 @@ def test_search_tuning_service_auth_adc():
SearchTuningServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -2730,7 +2742,11 @@ def test_search_tuning_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2783,7 +2799,11 @@ def test_search_tuning_service_transport_create_channel(transport_class, grpc_he
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_serving_config_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_serving_config_service.py
index 8bc43a67d912..42f0cee9a68d 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_serving_config_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_serving_config_service.py
@@ -59,11 +59,13 @@
from google.cloud.discoveryengine_v1.services.serving_config_service import (
ServingConfigServiceAsyncClient,
ServingConfigServiceClient,
+ pagers,
transports,
)
from google.cloud.discoveryengine_v1.types import (
common,
search_service,
+ serving_config,
serving_config_service,
)
from google.cloud.discoveryengine_v1.types import serving_config as gcd_serving_config
@@ -1102,7 +1104,11 @@ def test_serving_config_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -1116,11 +1122,11 @@ def test_serving_config_service_client_create_channel_credentials_file(
@pytest.mark.parametrize(
"request_type",
[
- serving_config_service.UpdateServingConfigRequest(),
+ serving_config_service.CreateServingConfigRequest(),
{},
],
)
-def test_update_serving_config(request_type, transport: str = "grpc"):
+def test_create_serving_config(request_type, transport: str = "grpc"):
client = ServingConfigServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -1132,7 +1138,7 @@ def test_update_serving_config(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_serving_config), "__call__"
+ type(client.transport.create_serving_config), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = gcd_serving_config.ServingConfig(
@@ -1152,12 +1158,12 @@ def test_update_serving_config(request_type, transport: str = "grpc"):
ignore_control_ids=["ignore_control_ids_value"],
promote_control_ids=["promote_control_ids_value"],
)
- response = client.update_serving_config(request)
+ response = client.create_serving_config(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
- request = serving_config_service.UpdateServingConfigRequest()
+ request = serving_config_service.CreateServingConfigRequest()
assert args[0] == request
# Establish that the response is the type that we expect.
@@ -1179,7 +1185,7 @@ def test_update_serving_config(request_type, transport: str = "grpc"):
assert response.promote_control_ids == ["promote_control_ids_value"]
-def test_update_serving_config_non_empty_request_with_auto_populated_field():
+def test_create_serving_config_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 = ServingConfigServiceClient(
@@ -1190,23 +1196,29 @@ def test_update_serving_config_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 = serving_config_service.UpdateServingConfigRequest()
+ request = serving_config_service.CreateServingConfigRequest(
+ parent="parent_value",
+ serving_config_id="serving_config_id_value",
+ )
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
- type(client.transport.update_serving_config), "__call__"
+ type(client.transport.create_serving_config), "__call__"
) as call:
call.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client.update_serving_config(request=request)
+ client.create_serving_config(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- request_msg = serving_config_service.UpdateServingConfigRequest()
+ request_msg = serving_config_service.CreateServingConfigRequest(
+ parent="parent_value",
+ serving_config_id="serving_config_id_value",
+ )
assert args[0] == request_msg
-def test_update_serving_config_use_cached_wrapped_rpc():
+def test_create_serving_config_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -1221,7 +1233,7 @@ def test_update_serving_config_use_cached_wrapped_rpc():
# Ensure method has been cached
assert (
- client._transport.update_serving_config
+ client._transport.create_serving_config
in client._transport._wrapped_methods
)
@@ -1230,16 +1242,16 @@ def test_update_serving_config_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_serving_config] = (
+ client._transport._wrapped_methods[client._transport.create_serving_config] = (
mock_rpc
)
request = {}
- client.update_serving_config(request)
+ client.create_serving_config(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.update_serving_config(request)
+ client.create_serving_config(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
@@ -1247,7 +1259,7 @@ def test_update_serving_config_use_cached_wrapped_rpc():
@pytest.mark.asyncio
-async def test_update_serving_config_async_use_cached_wrapped_rpc(
+async def test_create_serving_config_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
@@ -1264,7 +1276,7 @@ async def test_update_serving_config_async_use_cached_wrapped_rpc(
# Ensure method has been cached
assert (
- client._client._transport.update_serving_config
+ client._client._transport.create_serving_config
in client._client._transport._wrapped_methods
)
@@ -1272,16 +1284,16 @@ async def test_update_serving_config_async_use_cached_wrapped_rpc(
mock_rpc = mock.AsyncMock()
mock_rpc.return_value = mock.Mock()
client._client._transport._wrapped_methods[
- client._client._transport.update_serving_config
+ client._client._transport.create_serving_config
] = mock_rpc
request = {}
- await client.update_serving_config(request)
+ await client.create_serving_config(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- await client.update_serving_config(request)
+ await client.create_serving_config(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
@@ -1292,11 +1304,11 @@ async def test_update_serving_config_async_use_cached_wrapped_rpc(
@pytest.mark.parametrize(
"request_type",
[
- serving_config_service.UpdateServingConfigRequest(),
+ serving_config_service.CreateServingConfigRequest(),
{},
],
)
-async def test_update_serving_config_async(
+async def test_create_serving_config_async(
request_type, transport: str = "grpc_asyncio"
):
client = ServingConfigServiceAsyncClient(
@@ -1310,7 +1322,7 @@ async def test_update_serving_config_async(
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
- type(client.transport.update_serving_config), "__call__"
+ type(client.transport.create_serving_config), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
@@ -1332,12 +1344,12 @@ async def test_update_serving_config_async(
promote_control_ids=["promote_control_ids_value"],
)
)
- response = await client.update_serving_config(request)
+ response = await client.create_serving_config(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
- request = serving_config_service.UpdateServingConfigRequest()
+ request = serving_config_service.CreateServingConfigRequest()
assert args[0] == request
# Establish that the response is the type that we expect.
@@ -1359,23 +1371,23 @@ async def test_update_serving_config_async(
assert response.promote_control_ids == ["promote_control_ids_value"]
-def test_update_serving_config_field_headers():
+def test_create_serving_config_field_headers():
client = ServingConfigServiceClient(
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 = serving_config_service.UpdateServingConfigRequest()
+ request = serving_config_service.CreateServingConfigRequest()
- request.serving_config.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_serving_config), "__call__"
+ type(client.transport.create_serving_config), "__call__"
) as call:
call.return_value = gcd_serving_config.ServingConfig()
- client.update_serving_config(request)
+ client.create_serving_config(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
@@ -1386,30 +1398,30 @@ def test_update_serving_config_field_headers():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "serving_config.name=name_value",
+ "parent=parent_value",
) in kw["metadata"]
@pytest.mark.asyncio
-async def test_update_serving_config_field_headers_async():
+async def test_create_serving_config_field_headers_async():
client = ServingConfigServiceAsyncClient(
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 = serving_config_service.UpdateServingConfigRequest()
+ request = serving_config_service.CreateServingConfigRequest()
- request.serving_config.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_serving_config), "__call__"
+ type(client.transport.create_serving_config), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
gcd_serving_config.ServingConfig()
)
- await client.update_serving_config(request)
+ await client.create_serving_config(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -1420,36 +1432,40 @@ async def test_update_serving_config_field_headers_async():
_, _, kw = call.mock_calls[0]
assert (
"x-goog-request-params",
- "serving_config.name=name_value",
+ "parent=parent_value",
) in kw["metadata"]
-def test_update_serving_config_flattened():
+def test_create_serving_config_flattened():
client = ServingConfigServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
- type(client.transport.update_serving_config), "__call__"
+ type(client.transport.create_serving_config), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = gcd_serving_config.ServingConfig()
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
- client.update_serving_config(
+ client.create_serving_config(
+ parent="parent_value",
serving_config=gcd_serving_config.ServingConfig(
media_config=gcd_serving_config.ServingConfig.MediaConfig(
content_watched_percentage_threshold=0.3811
)
),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ serving_config_id="serving_config_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
arg = args[0].serving_config
mock_val = gcd_serving_config.ServingConfig(
media_config=gcd_serving_config.ServingConfig.MediaConfig(
@@ -1457,12 +1473,12 @@ def test_update_serving_config_flattened():
)
)
assert arg == mock_val
- arg = args[0].update_mask
- mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ arg = args[0].serving_config_id
+ mock_val = "serving_config_id_value"
assert arg == mock_val
-def test_update_serving_config_flattened_error():
+def test_create_serving_config_flattened_error():
client = ServingConfigServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
)
@@ -1470,26 +1486,27 @@ def test_update_serving_config_flattened_error():
# Attempting to call a method with both a request object and flattened
# fields is an error.
with pytest.raises(ValueError):
- client.update_serving_config(
- serving_config_service.UpdateServingConfigRequest(),
+ client.create_serving_config(
+ serving_config_service.CreateServingConfigRequest(),
+ parent="parent_value",
serving_config=gcd_serving_config.ServingConfig(
media_config=gcd_serving_config.ServingConfig.MediaConfig(
content_watched_percentage_threshold=0.3811
)
),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ serving_config_id="serving_config_id_value",
)
@pytest.mark.asyncio
-async def test_update_serving_config_flattened_async():
+async def test_create_serving_config_flattened_async():
client = ServingConfigServiceAsyncClient(
credentials=async_anonymous_credentials(),
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
- type(client.transport.update_serving_config), "__call__"
+ type(client.transport.create_serving_config), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = gcd_serving_config.ServingConfig()
@@ -1499,19 +1516,23 @@ async def test_update_serving_config_flattened_async():
)
# Call the method with a truthy value for each flattened field,
# using the keyword arguments to the method.
- response = await client.update_serving_config(
+ response = await client.create_serving_config(
+ parent="parent_value",
serving_config=gcd_serving_config.ServingConfig(
media_config=gcd_serving_config.ServingConfig.MediaConfig(
content_watched_percentage_threshold=0.3811
)
),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ serving_config_id="serving_config_id_value",
)
# Establish that the underlying call was made with the expected
# request object values.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
+ arg = args[0].parent
+ mock_val = "parent_value"
+ assert arg == mock_val
arg = args[0].serving_config
mock_val = gcd_serving_config.ServingConfig(
media_config=gcd_serving_config.ServingConfig.MediaConfig(
@@ -1519,13 +1540,13 @@ async def test_update_serving_config_flattened_async():
)
)
assert arg == mock_val
- arg = args[0].update_mask
- mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ arg = args[0].serving_config_id
+ mock_val = "serving_config_id_value"
assert arg == mock_val
@pytest.mark.asyncio
-async def test_update_serving_config_flattened_error_async():
+async def test_create_serving_config_flattened_error_async():
client = ServingConfigServiceAsyncClient(
credentials=async_anonymous_credentials(),
)
@@ -1533,24 +1554,91 @@ async def test_update_serving_config_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_serving_config(
- serving_config_service.UpdateServingConfigRequest(),
+ await client.create_serving_config(
+ serving_config_service.CreateServingConfigRequest(),
+ parent="parent_value",
serving_config=gcd_serving_config.ServingConfig(
media_config=gcd_serving_config.ServingConfig.MediaConfig(
content_watched_percentage_threshold=0.3811
)
),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ serving_config_id="serving_config_id_value",
)
-def test_update_serving_config_rest_use_cached_wrapped_rpc():
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ serving_config_service.DeleteServingConfigRequest(),
+ {},
+ ],
+)
+def test_delete_serving_config(request_type, transport: str = "grpc"):
+ client = ServingConfigServiceClient(
+ 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_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.delete_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = serving_config_service.DeleteServingConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_delete_serving_config_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 = ServingConfigServiceClient(
+ 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 = serving_config_service.DeleteServingConfigRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_serving_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.delete_serving_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.DeleteServingConfigRequest(
+ name="name_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_delete_serving_config_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
client = ServingConfigServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport="grpc",
)
# Should wrap all calls on client creation
@@ -1559,7 +1647,7 @@ def test_update_serving_config_rest_use_cached_wrapped_rpc():
# Ensure method has been cached
assert (
- client._transport.update_serving_config
+ client._transport.delete_serving_config
in client._transport._wrapped_methods
)
@@ -1568,358 +1656,3470 @@ def test_update_serving_config_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_serving_config] = (
+ client._transport._wrapped_methods[client._transport.delete_serving_config] = (
mock_rpc
)
-
request = {}
- client.update_serving_config(request)
+ client.delete_serving_config(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.update_serving_config(request)
+ client.delete_serving_config(request)
# Establish 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_serving_config_rest_required_fields(
- request_type=serving_config_service.UpdateServingConfigRequest,
+@pytest.mark.asyncio
+async def test_delete_serving_config_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
):
- transport_class = transports.ServingConfigServiceRestTransport
+ # Clients should use _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 = ServingConfigServiceAsyncClient(
+ 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.delete_serving_config
+ in client._client._transport._wrapped_methods
+ )
- default_values = getattr(
- transport_class._BaseUpdateServingConfig,
- "_BaseUpdateServingConfig__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_serving_config
+ ] = mock_rpc
- # verify required fields with default values are now present
+ request = {}
+ await client.delete_serving_config(request)
- # Check that path parameters and body parameters are not mixing in.
- assert not set(unset_fields) - set(("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
+ await client.delete_serving_config(request)
- client = ServingConfigServiceClient(
- 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 = gcd_serving_config.ServingConfig()
- # Mock the http request call within the method and fake a response.
- with mock.patch.object(Session, "request") as req:
- # We need to mock transcode() because providing default values
- # for required fields will fail the real version if the http_options
- # expect actual values for those fields.
- with mock.patch.object(path_template, "transcode") as transcode:
- # A uri without fields and an empty body will force 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
+@pytest.mark.asyncio
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ serving_config_service.DeleteServingConfigRequest(),
+ {},
+ ],
+)
+async def test_delete_serving_config_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
- # Convert return value to protobuf type
- return_value = gcd_serving_config.ServingConfig.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_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.delete_serving_config(request)
- response = client.update_serving_config(request)
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = serving_config_service.DeleteServingConfigRequest()
+ 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 response is None
-def test_update_serving_config_rest_flattened():
+def test_delete_serving_config_field_headers():
client = ServingConfigServiceClient(
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 = gcd_serving_config.ServingConfig()
+ # Any value that is part of the HTTP/1.1 URI should be sent as
+ # a field header. Set these to a non-empty value.
+ request = serving_config_service.DeleteServingConfigRequest()
- # get arguments that satisfy an http rule for this method
- sample_request = {
- "serving_config": {
- "name": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4"
- }
- }
+ request.name = "name_value"
- # get truthy value for each flattened field
- mock_args = dict(
- serving_config=gcd_serving_config.ServingConfig(
- media_config=gcd_serving_config.ServingConfig.MediaConfig(
- content_watched_percentage_threshold=0.3811
- )
- ),
- update_mask=field_mask_pb2.FieldMask(paths=["paths_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_serving_config), "__call__"
+ ) as call:
+ call.return_value = None
+ client.delete_serving_config(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 = gcd_serving_config.ServingConfig.pb(return_value)
- json_return_value = json_format.MessageToJson(return_value)
- response_value._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.update_serving_config(**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/{serving_config.name=projects/*/locations/*/dataStores/*/servingConfigs/*}"
- % client.transport._host,
- args[1],
- )
+@pytest.mark.asyncio
+async def test_delete_serving_config_field_headers_async():
+ client = ServingConfigServiceAsyncClient(
+ 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 = serving_config_service.DeleteServingConfigRequest()
+
+ request.name = "name_value"
-def test_update_serving_config_rest_flattened_error(transport: str = "rest"):
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_serving_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.delete_serving_config(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_serving_config_flattened():
client = ServingConfigServiceClient(
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_serving_config(
- serving_config_service.UpdateServingConfigRequest(),
- serving_config=gcd_serving_config.ServingConfig(
- media_config=gcd_serving_config.ServingConfig.MediaConfig(
- content_watched_percentage_threshold=0.3811
- )
- ),
- 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_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.delete_serving_config(
+ 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_credentials_transport_error():
- # It is an error to provide credentials and a transport instance.
- transport = transports.ServingConfigServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- with pytest.raises(ValueError):
- client = ServingConfigServiceClient(
- credentials=ga_credentials.AnonymousCredentials(),
- transport=transport,
- )
- # It is an error to provide a credentials file and a transport instance.
- transport = transports.ServingConfigServiceGrpcTransport(
+def test_delete_serving_config_flattened_error():
+ client = ServingConfigServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
)
- with pytest.raises(ValueError):
- client = ServingConfigServiceClient(
- client_options={"credentials_file": "credentials.json"},
- transport=transport,
- )
- # It is an error to provide an api_key and a transport instance.
- transport = transports.ServingConfigServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- options = client_options.ClientOptions()
- options.api_key = "api_key"
+ # Attempting to call a method with both a request object and flattened
+ # fields is an error.
with pytest.raises(ValueError):
- client = ServingConfigServiceClient(
- client_options=options,
- transport=transport,
+ client.delete_serving_config(
+ serving_config_service.DeleteServingConfigRequest(),
+ name="name_value",
)
- # It is an error to provide an api_key and a credential.
- options = client_options.ClientOptions()
- options.api_key = "api_key"
- with pytest.raises(ValueError):
- client = ServingConfigServiceClient(
- client_options=options, credentials=ga_credentials.AnonymousCredentials()
- )
- # It is an error to provide scopes and a transport instance.
- transport = transports.ServingConfigServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
+@pytest.mark.asyncio
+async def test_delete_serving_config_flattened_async():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
)
- with pytest.raises(ValueError):
- client = ServingConfigServiceClient(
- client_options={"scopes": ["1", "2"]},
- transport=transport,
- )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
-def test_transport_instance():
- # A client may be instantiated with a custom transport instance.
- transport = transports.ServingConfigServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- client = ServingConfigServiceClient(transport=transport)
- assert client.transport is transport
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.delete_serving_config(
+ 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
-def test_transport_get_channel():
- # A client may be instantiated with a custom transport instance.
- transport = transports.ServingConfigServiceGrpcTransport(
- credentials=ga_credentials.AnonymousCredentials(),
- )
- channel = transport.grpc_channel
- assert channel
- transport = transports.ServingConfigServiceGrpcAsyncIOTransport(
- credentials=ga_credentials.AnonymousCredentials(),
+@pytest.mark.asyncio
+async def test_delete_serving_config_flattened_error_async():
+ client = ServingConfigServiceAsyncClient(
+ 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_serving_config(
+ serving_config_service.DeleteServingConfigRequest(),
+ name="name_value",
+ )
@pytest.mark.parametrize(
- "transport_class",
+ "request_type",
[
- transports.ServingConfigServiceGrpcTransport,
- transports.ServingConfigServiceGrpcAsyncIOTransport,
- transports.ServingConfigServiceRestTransport,
+ serving_config_service.UpdateServingConfigRequest(),
+ {},
],
)
-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 = ServingConfigServiceClient.get_transport_class("grpc")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "grpc"
-
-
-def test_initialize_client_w_grpc():
- client = ServingConfigServiceClient(
- 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_update_serving_config_empty_call_grpc():
+def test_update_serving_config(request_type, transport: str = "grpc"):
client = ServingConfigServiceClient(
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.update_serving_config), "__call__"
) as call:
- call.return_value = gcd_serving_config.ServingConfig()
- client.update_serving_config(request=None)
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_serving_config.ServingConfig(
+ name="name_value",
+ display_name="display_name_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ model_id="model_id_value",
+ diversity_level="diversity_level_value",
+ ranking_expression="ranking_expression_value",
+ filter_control_ids=["filter_control_ids_value"],
+ boost_control_ids=["boost_control_ids_value"],
+ redirect_control_ids=["redirect_control_ids_value"],
+ synonyms_control_ids=["synonyms_control_ids_value"],
+ oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
+ dissociate_control_ids=["dissociate_control_ids_value"],
+ replacement_control_ids=["replacement_control_ids_value"],
+ ignore_control_ids=["ignore_control_ids_value"],
+ promote_control_ids=["promote_control_ids_value"],
+ )
+ response = client.update_serving_config(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 = serving_config_service.UpdateServingConfigRequest()
- assert args[0] == request_msg
-
-
-def test_transport_kind_grpc_asyncio():
- transport = ServingConfigServiceAsyncClient.get_transport_class("grpc_asyncio")(
- credentials=async_anonymous_credentials()
- )
- assert transport.kind == "grpc_asyncio"
-
+ request = serving_config_service.UpdateServingConfigRequest()
+ assert args[0] == request
-def test_initialize_client_w_grpc_asyncio():
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_serving_config.ServingConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.model_id == "model_id_value"
+ assert response.diversity_level == "diversity_level_value"
+ assert response.ranking_expression == "ranking_expression_value"
+ assert response.filter_control_ids == ["filter_control_ids_value"]
+ assert response.boost_control_ids == ["boost_control_ids_value"]
+ assert response.redirect_control_ids == ["redirect_control_ids_value"]
+ assert response.synonyms_control_ids == ["synonyms_control_ids_value"]
+ assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"]
+ assert response.dissociate_control_ids == ["dissociate_control_ids_value"]
+ assert response.replacement_control_ids == ["replacement_control_ids_value"]
+ assert response.ignore_control_ids == ["ignore_control_ids_value"]
+ assert response.promote_control_ids == ["promote_control_ids_value"]
+
+
+def test_update_serving_config_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 = ServingConfigServiceClient(
+ 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 = serving_config_service.UpdateServingConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_serving_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_serving_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.UpdateServingConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_update_serving_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ServingConfigServiceClient(
+ 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.update_serving_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_serving_config] = (
+ mock_rpc
+ )
+ request = {}
+ client.update_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_serving_config(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_update_serving_config_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 = ServingConfigServiceAsyncClient(
+ 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.update_serving_config
+ 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.update_serving_config
+ ] = mock_rpc
+
+ request = {}
+ await client.update_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_serving_config(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",
+ [
+ serving_config_service.UpdateServingConfigRequest(),
+ {},
+ ],
+)
+async def test_update_serving_config_async(
+ request_type, transport: str = "grpc_asyncio"
+):
client = ServingConfigServiceAsyncClient(
- credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ credentials=async_anonymous_credentials(),
+ transport=transport,
)
- assert client is not 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
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_serving_config.ServingConfig(
+ name="name_value",
+ display_name="display_name_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ model_id="model_id_value",
+ diversity_level="diversity_level_value",
+ ranking_expression="ranking_expression_value",
+ filter_control_ids=["filter_control_ids_value"],
+ boost_control_ids=["boost_control_ids_value"],
+ redirect_control_ids=["redirect_control_ids_value"],
+ synonyms_control_ids=["synonyms_control_ids_value"],
+ oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
+ dissociate_control_ids=["dissociate_control_ids_value"],
+ replacement_control_ids=["replacement_control_ids_value"],
+ ignore_control_ids=["ignore_control_ids_value"],
+ promote_control_ids=["promote_control_ids_value"],
+ )
+ )
+ response = await client.update_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = serving_config_service.UpdateServingConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_serving_config.ServingConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.model_id == "model_id_value"
+ assert response.diversity_level == "diversity_level_value"
+ assert response.ranking_expression == "ranking_expression_value"
+ assert response.filter_control_ids == ["filter_control_ids_value"]
+ assert response.boost_control_ids == ["boost_control_ids_value"]
+ assert response.redirect_control_ids == ["redirect_control_ids_value"]
+ assert response.synonyms_control_ids == ["synonyms_control_ids_value"]
+ assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"]
+ assert response.dissociate_control_ids == ["dissociate_control_ids_value"]
+ assert response.replacement_control_ids == ["replacement_control_ids_value"]
+ assert response.ignore_control_ids == ["ignore_control_ids_value"]
+ assert response.promote_control_ids == ["promote_control_ids_value"]
+
+
+def test_update_serving_config_field_headers():
+ client = ServingConfigServiceClient(
+ 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 = serving_config_service.UpdateServingConfigRequest()
+
+ request.serving_config.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_serving_config), "__call__"
+ ) as call:
+ call.return_value = gcd_serving_config.ServingConfig()
+ client.update_serving_config(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",
+ "serving_config.name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_serving_config_field_headers_async():
+ client = ServingConfigServiceAsyncClient(
+ 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 = serving_config_service.UpdateServingConfigRequest()
+
+ request.serving_config.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_serving_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_serving_config.ServingConfig()
+ )
+ await client.update_serving_config(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",
+ "serving_config.name=name_value",
+ ) in kw["metadata"]
+
+
+def test_update_serving_config_flattened():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_serving_config.ServingConfig()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_serving_config(
+ serving_config=gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ ),
+ 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].serving_config
+ mock_val = gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ )
+ 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_serving_config_flattened_error():
+ client = ServingConfigServiceClient(
+ 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_serving_config(
+ serving_config_service.UpdateServingConfigRequest(),
+ serving_config=gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_serving_config_flattened_async():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_serving_config.ServingConfig()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_serving_config.ServingConfig()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_serving_config(
+ serving_config=gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ ),
+ 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].serving_config
+ mock_val = gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ )
+ 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_serving_config_flattened_error_async():
+ client = ServingConfigServiceAsyncClient(
+ 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_serving_config(
+ serving_config_service.UpdateServingConfigRequest(),
+ serving_config=gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ serving_config_service.GetServingConfigRequest(),
+ {},
+ ],
+)
+def test_get_serving_config(request_type, transport: str = "grpc"):
+ client = ServingConfigServiceClient(
+ 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_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = serving_config.ServingConfig(
+ name="name_value",
+ display_name="display_name_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ model_id="model_id_value",
+ diversity_level="diversity_level_value",
+ ranking_expression="ranking_expression_value",
+ filter_control_ids=["filter_control_ids_value"],
+ boost_control_ids=["boost_control_ids_value"],
+ redirect_control_ids=["redirect_control_ids_value"],
+ synonyms_control_ids=["synonyms_control_ids_value"],
+ oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
+ dissociate_control_ids=["dissociate_control_ids_value"],
+ replacement_control_ids=["replacement_control_ids_value"],
+ ignore_control_ids=["ignore_control_ids_value"],
+ promote_control_ids=["promote_control_ids_value"],
+ )
+ response = client.get_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = serving_config_service.GetServingConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, serving_config.ServingConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.model_id == "model_id_value"
+ assert response.diversity_level == "diversity_level_value"
+ assert response.ranking_expression == "ranking_expression_value"
+ assert response.filter_control_ids == ["filter_control_ids_value"]
+ assert response.boost_control_ids == ["boost_control_ids_value"]
+ assert response.redirect_control_ids == ["redirect_control_ids_value"]
+ assert response.synonyms_control_ids == ["synonyms_control_ids_value"]
+ assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"]
+ assert response.dissociate_control_ids == ["dissociate_control_ids_value"]
+ assert response.replacement_control_ids == ["replacement_control_ids_value"]
+ assert response.ignore_control_ids == ["ignore_control_ids_value"]
+ assert response.promote_control_ids == ["promote_control_ids_value"]
+
+
+def test_get_serving_config_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 = ServingConfigServiceClient(
+ 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 = serving_config_service.GetServingConfigRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_serving_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_serving_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.GetServingConfigRequest(
+ name="name_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_serving_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ServingConfigServiceClient(
+ 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_serving_config in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_serving_config] = (
+ mock_rpc
+ )
+ request = {}
+ client.get_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_serving_config(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_serving_config_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 = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_serving_config
+ 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_serving_config
+ ] = mock_rpc
+
+ request = {}
+ await client.get_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_serving_config(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",
+ [
+ serving_config_service.GetServingConfigRequest(),
+ {},
+ ],
+)
+async def test_get_serving_config_async(request_type, transport: str = "grpc_asyncio"):
+ client = ServingConfigServiceAsyncClient(
+ 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_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ serving_config.ServingConfig(
+ name="name_value",
+ display_name="display_name_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ model_id="model_id_value",
+ diversity_level="diversity_level_value",
+ ranking_expression="ranking_expression_value",
+ filter_control_ids=["filter_control_ids_value"],
+ boost_control_ids=["boost_control_ids_value"],
+ redirect_control_ids=["redirect_control_ids_value"],
+ synonyms_control_ids=["synonyms_control_ids_value"],
+ oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
+ dissociate_control_ids=["dissociate_control_ids_value"],
+ replacement_control_ids=["replacement_control_ids_value"],
+ ignore_control_ids=["ignore_control_ids_value"],
+ promote_control_ids=["promote_control_ids_value"],
+ )
+ )
+ response = await client.get_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = serving_config_service.GetServingConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, serving_config.ServingConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.model_id == "model_id_value"
+ assert response.diversity_level == "diversity_level_value"
+ assert response.ranking_expression == "ranking_expression_value"
+ assert response.filter_control_ids == ["filter_control_ids_value"]
+ assert response.boost_control_ids == ["boost_control_ids_value"]
+ assert response.redirect_control_ids == ["redirect_control_ids_value"]
+ assert response.synonyms_control_ids == ["synonyms_control_ids_value"]
+ assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"]
+ assert response.dissociate_control_ids == ["dissociate_control_ids_value"]
+ assert response.replacement_control_ids == ["replacement_control_ids_value"]
+ assert response.ignore_control_ids == ["ignore_control_ids_value"]
+ assert response.promote_control_ids == ["promote_control_ids_value"]
+
+
+def test_get_serving_config_field_headers():
+ client = ServingConfigServiceClient(
+ 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 = serving_config_service.GetServingConfigRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_serving_config), "__call__"
+ ) as call:
+ call.return_value = serving_config.ServingConfig()
+ client.get_serving_config(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_serving_config_field_headers_async():
+ client = ServingConfigServiceAsyncClient(
+ 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 = serving_config_service.GetServingConfigRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_serving_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ serving_config.ServingConfig()
+ )
+ await client.get_serving_config(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_serving_config_flattened():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = serving_config.ServingConfig()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_serving_config(
+ 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_serving_config_flattened_error():
+ client = ServingConfigServiceClient(
+ 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_serving_config(
+ serving_config_service.GetServingConfigRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_serving_config_flattened_async():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = serving_config.ServingConfig()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ serving_config.ServingConfig()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_serving_config(
+ 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_serving_config_flattened_error_async():
+ client = ServingConfigServiceAsyncClient(
+ 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_serving_config(
+ serving_config_service.GetServingConfigRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ serving_config_service.ListServingConfigsRequest(),
+ {},
+ ],
+)
+def test_list_serving_configs(request_type, transport: str = "grpc"):
+ client = ServingConfigServiceClient(
+ 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_serving_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = serving_config_service.ListServingConfigsResponse(
+ next_page_token="next_page_token_value",
+ )
+ response = client.list_serving_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = serving_config_service.ListServingConfigsRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListServingConfigsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_serving_configs_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 = ServingConfigServiceClient(
+ 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 = serving_config_service.ListServingConfigsRequest(
+ 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.list_serving_configs), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.list_serving_configs(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.ListServingConfigsRequest(
+ parent="parent_value",
+ page_token="page_token_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_list_serving_configs_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ServingConfigServiceClient(
+ 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_serving_configs in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_serving_configs] = (
+ mock_rpc
+ )
+ request = {}
+ client.list_serving_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_serving_configs(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_serving_configs_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 = ServingConfigServiceAsyncClient(
+ 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_serving_configs
+ 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_serving_configs
+ ] = mock_rpc
+
+ request = {}
+ await client.list_serving_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.list_serving_configs(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",
+ [
+ serving_config_service.ListServingConfigsRequest(),
+ {},
+ ],
+)
+async def test_list_serving_configs_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = ServingConfigServiceAsyncClient(
+ 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_serving_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ serving_config_service.ListServingConfigsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ response = await client.list_serving_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = serving_config_service.ListServingConfigsRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListServingConfigsAsyncPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+def test_list_serving_configs_field_headers():
+ client = ServingConfigServiceClient(
+ 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 = serving_config_service.ListServingConfigsRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_serving_configs), "__call__"
+ ) as call:
+ call.return_value = serving_config_service.ListServingConfigsResponse()
+ client.list_serving_configs(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_serving_configs_field_headers_async():
+ client = ServingConfigServiceAsyncClient(
+ 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 = serving_config_service.ListServingConfigsRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_serving_configs), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ serving_config_service.ListServingConfigsResponse()
+ )
+ await client.list_serving_configs(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_serving_configs_flattened():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_serving_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = serving_config_service.ListServingConfigsResponse()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_serving_configs(
+ 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_serving_configs_flattened_error():
+ client = ServingConfigServiceClient(
+ 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_serving_configs(
+ serving_config_service.ListServingConfigsRequest(),
+ parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_serving_configs_flattened_async():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_serving_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = serving_config_service.ListServingConfigsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ serving_config_service.ListServingConfigsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_serving_configs(
+ 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_serving_configs_flattened_error_async():
+ client = ServingConfigServiceAsyncClient(
+ 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_serving_configs(
+ serving_config_service.ListServingConfigsRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_serving_configs_pager(transport_name: str = "grpc"):
+ client = ServingConfigServiceClient(
+ 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_serving_configs), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[],
+ next_page_token="def",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+
+ expected_metadata = ()
+ retry = retries.Retry()
+ timeout = 5
+ expected_metadata = tuple(expected_metadata) + (
+ gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)),
+ )
+ pager = client.list_serving_configs(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, serving_config.ServingConfig) for i in results)
+
+
+def test_list_serving_configs_pages(transport_name: str = "grpc"):
+ client = ServingConfigServiceClient(
+ 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_serving_configs), "__call__"
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[],
+ next_page_token="def",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = list(client.list_serving_configs(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_serving_configs_async_pager():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_serving_configs),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[],
+ next_page_token="def",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+ async_pager = await client.list_serving_configs(
+ 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, serving_config.ServingConfig) for i in responses)
+
+
+@pytest.mark.asyncio
+async def test_list_serving_configs_async_pages():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_serving_configs),
+ "__call__",
+ new_callable=mock.AsyncMock,
+ ) as call:
+ # Set the response to a series of pages.
+ call.side_effect = (
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[],
+ next_page_token="def",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ ),
+ RuntimeError,
+ )
+ pages = []
+ async for page_ in (await client.list_serving_configs(request={})).pages:
+ pages.append(page_)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_create_serving_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ServingConfigServiceClient(
+ 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_serving_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_serving_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.create_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.create_serving_config(request)
+
+ # Establish 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_serving_config_rest_required_fields(
+ request_type=serving_config_service.CreateServingConfigRequest,
+):
+ transport_class = transports.ServingConfigServiceRestTransport
+
+ request_init = {}
+ request_init["parent"] = ""
+ request_init["serving_config_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 "servingConfigId" not in jsonified_request
+
+ default_values = getattr(
+ transport_class._BaseCreateServingConfig,
+ "_BaseCreateServingConfig__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 "servingConfigId" in jsonified_request
+ assert jsonified_request["servingConfigId"] == request_init["serving_config_id"]
+
+ jsonified_request["parent"] = "parent_value"
+ jsonified_request["servingConfigId"] = "serving_config_id_value"
+
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("servingConfigId",))
+
+ # verify required fields with non-default values are left alone
+ assert "parent" in jsonified_request
+ assert jsonified_request["parent"] == "parent_value"
+ assert "servingConfigId" in jsonified_request
+ assert jsonified_request["servingConfigId"] == "serving_config_id_value"
+
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_serving_config.ServingConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = gcd_serving_config.ServingConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_serving_config(request)
+
+ expected_params = [
+ (
+ "servingConfigId",
+ "",
+ ),
+ ("$alt", "json;enum-encoding=int"),
+ ]
+ actual_params = req.call_args.kwargs["params"]
+ assert sorted(expected_params) == sorted(actual_params)
+
+
+def test_create_serving_config_rest_flattened():
+ client = ServingConfigServiceClient(
+ 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 = gcd_serving_config.ServingConfig()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/dataStores/sample3"
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ parent="parent_value",
+ serving_config=gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ ),
+ serving_config_id="serving_config_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 = gcd_serving_config.ServingConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_serving_config(**mock_args)
+
+ # Establish that the underlying call 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/*/dataStores/*}/servingConfigs"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_create_serving_config_rest_flattened_error(transport: str = "rest"):
+ client = ServingConfigServiceClient(
+ 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_serving_config(
+ serving_config_service.CreateServingConfigRequest(),
+ parent="parent_value",
+ serving_config=gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ ),
+ serving_config_id="serving_config_id_value",
+ )
+
+
+def test_delete_serving_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ServingConfigServiceClient(
+ 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_serving_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_serving_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.delete_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.delete_serving_config(request)
+
+ # Establish 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_serving_config_rest_required_fields(
+ request_type=serving_config_service.DeleteServingConfigRequest,
+):
+ transport_class = transports.ServingConfigServiceRestTransport
+
+ 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._BaseDeleteServingConfig,
+ "_BaseDeleteServingConfig__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 = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = None
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = ""
+
+ response_value._content = json_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_serving_config(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_serving_config_rest_flattened():
+ client = ServingConfigServiceClient(
+ 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 = None
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = ""
+ response_value._content = 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_serving_config(**mock_args)
+
+ # Establish that the underlying call 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/*/dataStores/*/servingConfigs/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_delete_serving_config_rest_flattened_error(transport: str = "rest"):
+ client = ServingConfigServiceClient(
+ 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_serving_config(
+ serving_config_service.DeleteServingConfigRequest(),
+ name="name_value",
+ )
+
+
+def test_update_serving_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ServingConfigServiceClient(
+ 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_serving_config
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_serving_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.update_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_serving_config(request)
+
+ # Establish 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_serving_config_rest_required_fields(
+ request_type=serving_config_service.UpdateServingConfigRequest,
+):
+ transport_class = transports.ServingConfigServiceRestTransport
+
+ 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._BaseUpdateServingConfig,
+ "_BaseUpdateServingConfig__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(("updateMask",))
+
+ # verify required fields with non-default values are left alone
+
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_serving_config.ServingConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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
+
+ # Convert return value to protobuf type
+ return_value = gcd_serving_config.ServingConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_serving_config(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_serving_config_rest_flattened():
+ client = ServingConfigServiceClient(
+ 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 = gcd_serving_config.ServingConfig()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "serving_config": {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/sample4"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ serving_config=gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ ),
+ 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 = gcd_serving_config.ServingConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_serving_config(**mock_args)
+
+ # Establish that the underlying call 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/{serving_config.name=projects/*/locations/*/dataStores/*/servingConfigs/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_update_serving_config_rest_flattened_error(transport: str = "rest"):
+ client = ServingConfigServiceClient(
+ 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_serving_config(
+ serving_config_service.UpdateServingConfigRequest(),
+ serving_config=gcd_serving_config.ServingConfig(
+ media_config=gcd_serving_config.ServingConfig.MediaConfig(
+ content_watched_percentage_threshold=0.3811
+ )
+ ),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_get_serving_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ServingConfigServiceClient(
+ 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_serving_config in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_serving_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.get_serving_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_serving_config(request)
+
+ # Establish 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_serving_config_rest_required_fields(
+ request_type=serving_config_service.GetServingConfigRequest,
+):
+ transport_class = transports.ServingConfigServiceRestTransport
+
+ 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._BaseGetServingConfig,
+ "_BaseGetServingConfig__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 = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = serving_config.ServingConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = serving_config.ServingConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_serving_config(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_serving_config_rest_flattened():
+ client = ServingConfigServiceClient(
+ 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 = serving_config.ServingConfig()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = serving_config.ServingConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_serving_config(**mock_args)
+
+ # Establish that the underlying call 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/*/dataStores/*/servingConfigs/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_serving_config_rest_flattened_error(transport: str = "rest"):
+ client = ServingConfigServiceClient(
+ 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_serving_config(
+ serving_config_service.GetServingConfigRequest(),
+ name="name_value",
+ )
+
+
+def test_list_serving_configs_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = ServingConfigServiceClient(
+ 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_serving_configs in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_serving_configs] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.list_serving_configs(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_serving_configs(request)
+
+ # Establish 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_serving_configs_rest_required_fields(
+ request_type=serving_config_service.ListServingConfigsRequest,
+):
+ transport_class = transports.ServingConfigServiceRestTransport
+
+ 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._BaseListServingConfigs,
+ "_BaseListServingConfigs__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 = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = serving_config_service.ListServingConfigsResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = serving_config_service.ListServingConfigsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_serving_configs(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_serving_configs_rest_flattened():
+ client = ServingConfigServiceClient(
+ 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 = serving_config_service.ListServingConfigsResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/dataStores/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 = serving_config_service.ListServingConfigsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_serving_configs(**mock_args)
+
+ # Establish that the underlying call 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/*/dataStores/*}/servingConfigs"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_list_serving_configs_rest_flattened_error(transport: str = "rest"):
+ client = ServingConfigServiceClient(
+ 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_serving_configs(
+ serving_config_service.ListServingConfigsRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_serving_configs_rest_pager(transport: str = "rest"):
+ client = ServingConfigServiceClient(
+ 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 = (
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="abc",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[],
+ next_page_token="def",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ ],
+ next_page_token="ghi",
+ ),
+ serving_config_service.ListServingConfigsResponse(
+ serving_configs=[
+ serving_config.ServingConfig(),
+ serving_config.ServingConfig(),
+ ],
+ ),
+ )
+ # Two responses for two calls
+ response = response + response
+
+ # Wrap the values into proper Response objs
+ response = tuple(
+ serving_config_service.ListServingConfigsResponse.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/dataStores/sample3"
+ }
+
+ pager = client.list_serving_configs(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, serving_config.ServingConfig) for i in results)
+
+ pages = list(client.list_serving_configs(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.ServingConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.ServingConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ServingConfigServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.ServingConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = ServingConfigServiceClient(
+ 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 = ServingConfigServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.ServingConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = ServingConfigServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ServingConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = ServingConfigServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.ServingConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.ServingConfigServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.ServingConfigServiceGrpcTransport,
+ transports.ServingConfigServiceGrpcAsyncIOTransport,
+ transports.ServingConfigServiceRestTransport,
+ ],
+)
+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 = ServingConfigServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = ServingConfigServiceClient(
+ 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_create_serving_config_empty_call_grpc():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_serving_config), "__call__"
+ ) as call:
+ call.return_value = gcd_serving_config.ServingConfig()
+ client.create_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.CreateServingConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_serving_config_empty_call_grpc():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_serving_config), "__call__"
+ ) as call:
+ call.return_value = None
+ client.delete_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.DeleteServingConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_serving_config_empty_call_grpc():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_serving_config), "__call__"
+ ) as call:
+ call.return_value = gcd_serving_config.ServingConfig()
+ client.update_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.UpdateServingConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_serving_config_empty_call_grpc():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_serving_config), "__call__"
+ ) as call:
+ call.return_value = serving_config.ServingConfig()
+ client.get_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.GetServingConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_serving_configs_empty_call_grpc():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_serving_configs), "__call__"
+ ) as call:
+ call.return_value = serving_config_service.ListServingConfigsResponse()
+ client.list_serving_configs(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.ListServingConfigsRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = ServingConfigServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = ServingConfigServiceAsyncClient(
+ 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_create_serving_config_empty_call_grpc_asyncio():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_serving_config.ServingConfig(
+ name="name_value",
+ display_name="display_name_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ model_id="model_id_value",
+ diversity_level="diversity_level_value",
+ ranking_expression="ranking_expression_value",
+ filter_control_ids=["filter_control_ids_value"],
+ boost_control_ids=["boost_control_ids_value"],
+ redirect_control_ids=["redirect_control_ids_value"],
+ synonyms_control_ids=["synonyms_control_ids_value"],
+ oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
+ dissociate_control_ids=["dissociate_control_ids_value"],
+ replacement_control_ids=["replacement_control_ids_value"],
+ ignore_control_ids=["ignore_control_ids_value"],
+ promote_control_ids=["promote_control_ids_value"],
+ )
+ )
+ await client.create_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.CreateServingConfigRequest()
+ assert args[0] == request_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_serving_config_empty_call_grpc_asyncio():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.delete_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.DeleteServingConfigRequest()
+ assert args[0] == request_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_serving_config_empty_call_grpc_asyncio():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_serving_config.ServingConfig(
+ name="name_value",
+ display_name="display_name_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ model_id="model_id_value",
+ diversity_level="diversity_level_value",
+ ranking_expression="ranking_expression_value",
+ filter_control_ids=["filter_control_ids_value"],
+ boost_control_ids=["boost_control_ids_value"],
+ redirect_control_ids=["redirect_control_ids_value"],
+ synonyms_control_ids=["synonyms_control_ids_value"],
+ oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
+ dissociate_control_ids=["dissociate_control_ids_value"],
+ replacement_control_ids=["replacement_control_ids_value"],
+ ignore_control_ids=["ignore_control_ids_value"],
+ promote_control_ids=["promote_control_ids_value"],
+ )
+ )
+ await client.update_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.UpdateServingConfigRequest()
+ assert args[0] == request_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_serving_config_empty_call_grpc_asyncio():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_serving_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ serving_config.ServingConfig(
+ name="name_value",
+ display_name="display_name_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ model_id="model_id_value",
+ diversity_level="diversity_level_value",
+ ranking_expression="ranking_expression_value",
+ filter_control_ids=["filter_control_ids_value"],
+ boost_control_ids=["boost_control_ids_value"],
+ redirect_control_ids=["redirect_control_ids_value"],
+ synonyms_control_ids=["synonyms_control_ids_value"],
+ oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
+ dissociate_control_ids=["dissociate_control_ids_value"],
+ replacement_control_ids=["replacement_control_ids_value"],
+ ignore_control_ids=["ignore_control_ids_value"],
+ promote_control_ids=["promote_control_ids_value"],
+ )
+ )
+ await client.get_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.GetServingConfigRequest()
+ assert args[0] == request_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_serving_configs_empty_call_grpc_asyncio():
+ client = ServingConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_serving_configs), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ serving_config_service.ListServingConfigsResponse(
+ next_page_token="next_page_token_value",
+ )
+ )
+ await client.list_serving_configs(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.ListServingConfigsRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = ServingConfigServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_create_serving_config_rest_bad_request(
+ request_type=serving_config_service.CreateServingConfigRequest,
+):
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/dataStores/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_serving_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ serving_config_service.CreateServingConfigRequest,
+ dict,
+ ],
+)
+def test_create_serving_config_rest_call_success(request_type):
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/dataStores/sample3"}
+ request_init["serving_config"] = {
+ "media_config": {
+ "content_watched_percentage_threshold": 0.3811,
+ "content_watched_seconds_threshold": 0.3508,
+ "demotion_event_type": "demotion_event_type_value",
+ "demote_content_watched_past_days": 3390,
+ "content_freshness_cutoff_days": 3105,
+ },
+ "generic_config": {
+ "content_search_spec": {
+ "snippet_spec": {
+ "max_snippet_count": 1840,
+ "reference_only": True,
+ "return_snippet": True,
+ },
+ "summary_spec": {
+ "summary_result_count": 2196,
+ "include_citations": True,
+ "ignore_adversarial_query": True,
+ "ignore_non_summary_seeking_query": True,
+ "ignore_low_relevant_content": True,
+ "ignore_jail_breaking_query": True,
+ "model_prompt_spec": {"preamble": "preamble_value"},
+ "language_code": "language_code_value",
+ "model_spec": {"version": "version_value"},
+ "use_semantic_chunks": True,
+ },
+ "extractive_content_spec": {
+ "max_extractive_answer_count": 2907,
+ "max_extractive_segment_count": 3006,
+ "return_extractive_segment_score": True,
+ "num_previous_segments": 2289,
+ "num_next_segments": 1843,
+ },
+ "search_result_mode": 1,
+ "chunk_spec": {"num_previous_chunks": 2071, "num_next_chunks": 1625},
+ }
+ },
+ "name": "name_value",
+ "display_name": "display_name_value",
+ "solution_type": 1,
+ "model_id": "model_id_value",
+ "diversity_level": "diversity_level_value",
+ "ranking_expression": "ranking_expression_value",
+ "create_time": {"seconds": 751, "nanos": 543},
+ "update_time": {},
+ "filter_control_ids": [
+ "filter_control_ids_value1",
+ "filter_control_ids_value2",
+ ],
+ "boost_control_ids": ["boost_control_ids_value1", "boost_control_ids_value2"],
+ "redirect_control_ids": [
+ "redirect_control_ids_value1",
+ "redirect_control_ids_value2",
+ ],
+ "synonyms_control_ids": [
+ "synonyms_control_ids_value1",
+ "synonyms_control_ids_value2",
+ ],
+ "oneway_synonyms_control_ids": [
+ "oneway_synonyms_control_ids_value1",
+ "oneway_synonyms_control_ids_value2",
+ ],
+ "dissociate_control_ids": [
+ "dissociate_control_ids_value1",
+ "dissociate_control_ids_value2",
+ ],
+ "replacement_control_ids": [
+ "replacement_control_ids_value1",
+ "replacement_control_ids_value2",
+ ],
+ "ignore_control_ids": [
+ "ignore_control_ids_value1",
+ "ignore_control_ids_value2",
+ ],
+ "promote_control_ids": [
+ "promote_control_ids_value1",
+ "promote_control_ids_value2",
+ ],
+ "answer_generation_spec": {
+ "user_defined_classifier_spec": {
+ "enable_user_defined_classifier": True,
+ "preamble": "preamble_value",
+ "model_id": "model_id_value",
+ "task_marker": "task_marker_value",
+ "top_p": 0.546,
+ "top_k": 541,
+ "temperature": 0.1198,
+ "seed": 417,
+ }
+ },
+ }
+ # 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 = serving_config_service.CreateServingConfigRequest.meta.fields[
+ "serving_config"
+ ]
+
+ 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["serving_config"].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["serving_config"][field])):
+ del request_init["serving_config"][field][i][subfield]
+ else:
+ del request_init["serving_config"][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 = gcd_serving_config.ServingConfig(
+ name="name_value",
+ display_name="display_name_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ model_id="model_id_value",
+ diversity_level="diversity_level_value",
+ ranking_expression="ranking_expression_value",
+ filter_control_ids=["filter_control_ids_value"],
+ boost_control_ids=["boost_control_ids_value"],
+ redirect_control_ids=["redirect_control_ids_value"],
+ synonyms_control_ids=["synonyms_control_ids_value"],
+ oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
+ dissociate_control_ids=["dissociate_control_ids_value"],
+ replacement_control_ids=["replacement_control_ids_value"],
+ ignore_control_ids=["ignore_control_ids_value"],
+ promote_control_ids=["promote_control_ids_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 = gcd_serving_config.ServingConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_serving_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_serving_config.ServingConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.model_id == "model_id_value"
+ assert response.diversity_level == "diversity_level_value"
+ assert response.ranking_expression == "ranking_expression_value"
+ assert response.filter_control_ids == ["filter_control_ids_value"]
+ assert response.boost_control_ids == ["boost_control_ids_value"]
+ assert response.redirect_control_ids == ["redirect_control_ids_value"]
+ assert response.synonyms_control_ids == ["synonyms_control_ids_value"]
+ assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"]
+ assert response.dissociate_control_ids == ["dissociate_control_ids_value"]
+ assert response.replacement_control_ids == ["replacement_control_ids_value"]
+ assert response.ignore_control_ids == ["ignore_control_ids_value"]
+ assert response.promote_control_ids == ["promote_control_ids_value"]
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_create_serving_config_rest_interceptors(null_interceptor):
+ transport = transports.ServingConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.ServingConfigServiceRestInterceptor(),
+ )
+ client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_create_serving_config"
+ ) as post,
+ mock.patch.object(
+ transports.ServingConfigServiceRestInterceptor,
+ "post_create_serving_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.ServingConfigServiceRestInterceptor, "pre_create_serving_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = serving_config_service.CreateServingConfigRequest.pb(
+ serving_config_service.CreateServingConfigRequest()
+ )
+ 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 = gcd_serving_config.ServingConfig.to_json(
+ gcd_serving_config.ServingConfig()
+ )
+ req.return_value.content = return_value
+
+ request = serving_config_service.CreateServingConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcd_serving_config.ServingConfig()
+ post_with_metadata.return_value = gcd_serving_config.ServingConfig(), metadata
+
+ client.create_serving_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_delete_serving_config_rest_bad_request(
+ request_type=serving_config_service.DeleteServingConfigRequest,
+):
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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_serving_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ serving_config_service.DeleteServingConfigRequest,
+ dict,
+ ],
+)
+def test_delete_serving_config_rest_call_success(request_type):
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = None
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = ""
+ response_value.content = json_return_value.encode("UTF-8")
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ response = client.delete_serving_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is 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_update_serving_config_empty_call_grpc_asyncio():
- client = ServingConfigServiceAsyncClient(
- credentials=async_anonymous_credentials(),
- transport="grpc_asyncio",
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_delete_serving_config_rest_interceptors(null_interceptor):
+ transport = transports.ServingConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.ServingConfigServiceRestInterceptor(),
)
+ client = ServingConfigServiceClient(transport=transport)
- # Mock the actual call, and fake the request.
- with mock.patch.object(
- type(client.transport.update_serving_config), "__call__"
- ) as call:
- # Designate an appropriate return value for the call.
- call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- gcd_serving_config.ServingConfig(
- name="name_value",
- display_name="display_name_value",
- solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
- model_id="model_id_value",
- diversity_level="diversity_level_value",
- ranking_expression="ranking_expression_value",
- filter_control_ids=["filter_control_ids_value"],
- boost_control_ids=["boost_control_ids_value"],
- redirect_control_ids=["redirect_control_ids_value"],
- synonyms_control_ids=["synonyms_control_ids_value"],
- oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
- dissociate_control_ids=["dissociate_control_ids_value"],
- replacement_control_ids=["replacement_control_ids_value"],
- ignore_control_ids=["ignore_control_ids_value"],
- promote_control_ids=["promote_control_ids_value"],
- )
+ with (
+ mock.patch.object(type(client.transport._session), "request") as req,
+ mock.patch.object(path_template, "transcode") as transcode,
+ mock.patch.object(
+ transports.ServingConfigServiceRestInterceptor, "pre_delete_serving_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ pb_message = serving_config_service.DeleteServingConfigRequest.pb(
+ serving_config_service.DeleteServingConfigRequest()
)
- await client.update_serving_config(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 = serving_config_service.UpdateServingConfigRequest()
- 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"}
+ request = serving_config_service.DeleteServingConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
-def test_transport_kind_rest():
- transport = ServingConfigServiceClient.get_transport_class("rest")(
- credentials=ga_credentials.AnonymousCredentials()
- )
- assert transport.kind == "rest"
+ client.delete_serving_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
def test_update_serving_config_rest_bad_request(
@@ -2049,6 +5249,18 @@ def test_update_serving_config_rest_call_success(request_type):
"promote_control_ids_value1",
"promote_control_ids_value2",
],
+ "answer_generation_spec": {
+ "user_defined_classifier_spec": {
+ "enable_user_defined_classifier": True,
+ "preamble": "preamble_value",
+ "model_id": "model_id_value",
+ "task_marker": "task_marker_value",
+ "top_p": 0.546,
+ "top_k": 541,
+ "temperature": 0.1198,
+ "seed": 417,
+ }
+ },
}
# 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
@@ -2083,48 +5295,213 @@ def 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["serving_config"].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
+ # 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["serving_config"].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["serving_config"][field])):
+ del request_init["serving_config"][field][i][subfield]
+ else:
+ del request_init["serving_config"][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 = gcd_serving_config.ServingConfig(
+ name="name_value",
+ display_name="display_name_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ model_id="model_id_value",
+ diversity_level="diversity_level_value",
+ ranking_expression="ranking_expression_value",
+ filter_control_ids=["filter_control_ids_value"],
+ boost_control_ids=["boost_control_ids_value"],
+ redirect_control_ids=["redirect_control_ids_value"],
+ synonyms_control_ids=["synonyms_control_ids_value"],
+ oneway_synonyms_control_ids=["oneway_synonyms_control_ids_value"],
+ dissociate_control_ids=["dissociate_control_ids_value"],
+ replacement_control_ids=["replacement_control_ids_value"],
+ ignore_control_ids=["ignore_control_ids_value"],
+ promote_control_ids=["promote_control_ids_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 = gcd_serving_config.ServingConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_serving_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_serving_config.ServingConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.model_id == "model_id_value"
+ assert response.diversity_level == "diversity_level_value"
+ assert response.ranking_expression == "ranking_expression_value"
+ assert response.filter_control_ids == ["filter_control_ids_value"]
+ assert response.boost_control_ids == ["boost_control_ids_value"]
+ assert response.redirect_control_ids == ["redirect_control_ids_value"]
+ assert response.synonyms_control_ids == ["synonyms_control_ids_value"]
+ assert response.oneway_synonyms_control_ids == ["oneway_synonyms_control_ids_value"]
+ assert response.dissociate_control_ids == ["dissociate_control_ids_value"]
+ assert response.replacement_control_ids == ["replacement_control_ids_value"]
+ assert response.ignore_control_ids == ["ignore_control_ids_value"]
+ assert response.promote_control_ids == ["promote_control_ids_value"]
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_serving_config_rest_interceptors(null_interceptor):
+ transport = transports.ServingConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.ServingConfigServiceRestInterceptor(),
+ )
+ client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_update_serving_config"
+ ) as post,
+ mock.patch.object(
+ transports.ServingConfigServiceRestInterceptor,
+ "post_update_serving_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.ServingConfigServiceRestInterceptor, "pre_update_serving_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = serving_config_service.UpdateServingConfigRequest.pb(
+ serving_config_service.UpdateServingConfigRequest()
+ )
+ 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 = gcd_serving_config.ServingConfig.to_json(
+ gcd_serving_config.ServingConfig()
+ )
+ req.return_value.content = return_value
+
+ request = serving_config_service.UpdateServingConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcd_serving_config.ServingConfig()
+ post_with_metadata.return_value = gcd_serving_config.ServingConfig(), metadata
+
+ client.update_serving_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_get_serving_config_rest_bad_request(
+ request_type=serving_config_service.GetServingConfigRequest,
+):
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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_serving_config(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,
- }
- )
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ serving_config_service.GetServingConfigRequest,
+ dict,
+ ],
+)
+def test_get_serving_config_rest_call_success(request_type):
+ client = ServingConfigServiceClient(
+ 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["serving_config"][field])):
- del request_init["serving_config"][field][i][subfield]
- else:
- del request_init["serving_config"][field][subfield]
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/servingConfigs/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 = gcd_serving_config.ServingConfig(
+ return_value = serving_config.ServingConfig(
name="name_value",
display_name="display_name_value",
solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
@@ -2147,15 +5524,15 @@ def get_message_fields(field):
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = gcd_serving_config.ServingConfig.pb(return_value)
+ return_value = serving_config.ServingConfig.pb(return_value)
json_return_value = json_format.MessageToJson(return_value)
response_value.content = json_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_serving_config(request)
+ response = client.get_serving_config(request)
# Establish that the response is the type that we expect.
- assert isinstance(response, gcd_serving_config.ServingConfig)
+ assert isinstance(response, serving_config.ServingConfig)
assert response.name == "name_value"
assert response.display_name == "display_name_value"
assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
@@ -2174,7 +5551,7 @@ def get_message_fields(field):
@pytest.mark.parametrize("null_interceptor", [True, False])
-def test_update_serving_config_rest_interceptors(null_interceptor):
+def test_get_serving_config_rest_interceptors(null_interceptor):
transport = transports.ServingConfigServiceRestTransport(
credentials=ga_credentials.AnonymousCredentials(),
interceptor=None
@@ -2187,21 +5564,21 @@ def test_update_serving_config_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.ServingConfigServiceRestInterceptor, "post_update_serving_config"
+ transports.ServingConfigServiceRestInterceptor, "post_get_serving_config"
) as post,
mock.patch.object(
transports.ServingConfigServiceRestInterceptor,
- "post_update_serving_config_with_metadata",
+ "post_get_serving_config_with_metadata",
) as post_with_metadata,
mock.patch.object(
- transports.ServingConfigServiceRestInterceptor, "pre_update_serving_config"
+ transports.ServingConfigServiceRestInterceptor, "pre_get_serving_config"
) as pre,
):
pre.assert_not_called()
post.assert_not_called()
post_with_metadata.assert_not_called()
- pb_message = serving_config_service.UpdateServingConfigRequest.pb(
- serving_config_service.UpdateServingConfigRequest()
+ pb_message = serving_config_service.GetServingConfigRequest.pb(
+ serving_config_service.GetServingConfigRequest()
)
transcode.return_value = {
"method": "post",
@@ -2213,21 +5590,159 @@ def test_update_serving_config_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 = gcd_serving_config.ServingConfig.to_json(
- gcd_serving_config.ServingConfig()
+ return_value = serving_config.ServingConfig.to_json(
+ serving_config.ServingConfig()
)
req.return_value.content = return_value
- request = serving_config_service.UpdateServingConfigRequest()
+ request = serving_config_service.GetServingConfigRequest()
metadata = [
("key", "val"),
("cephalopod", "squid"),
]
pre.return_value = request, metadata
- post.return_value = gcd_serving_config.ServingConfig()
- post_with_metadata.return_value = gcd_serving_config.ServingConfig(), metadata
+ post.return_value = serving_config.ServingConfig()
+ post_with_metadata.return_value = serving_config.ServingConfig(), metadata
- client.update_serving_config(
+ client.get_serving_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_list_serving_configs_rest_bad_request(
+ request_type=serving_config_service.ListServingConfigsRequest,
+):
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/dataStores/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_serving_configs(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ serving_config_service.ListServingConfigsRequest,
+ dict,
+ ],
+)
+def test_list_serving_configs_rest_call_success(request_type):
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/dataStores/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 = serving_config_service.ListServingConfigsResponse(
+ 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 = serving_config_service.ListServingConfigsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_serving_configs(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, pagers.ListServingConfigsPager)
+ assert response.next_page_token == "next_page_token_value"
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_serving_configs_rest_interceptors(null_interceptor):
+ transport = transports.ServingConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.ServingConfigServiceRestInterceptor(),
+ )
+ client = ServingConfigServiceClient(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.ServingConfigServiceRestInterceptor, "post_list_serving_configs"
+ ) as post,
+ mock.patch.object(
+ transports.ServingConfigServiceRestInterceptor,
+ "post_list_serving_configs_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.ServingConfigServiceRestInterceptor, "pre_list_serving_configs"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = serving_config_service.ListServingConfigsRequest.pb(
+ serving_config_service.ListServingConfigsRequest()
+ )
+ 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 = serving_config_service.ListServingConfigsResponse.to_json(
+ serving_config_service.ListServingConfigsResponse()
+ )
+ req.return_value.content = return_value
+
+ request = serving_config_service.ListServingConfigsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = serving_config_service.ListServingConfigsResponse()
+ post_with_metadata.return_value = (
+ serving_config_service.ListServingConfigsResponse(),
+ metadata,
+ )
+
+ client.list_serving_configs(
request,
metadata=[
("key", "val"),
@@ -2434,6 +5949,48 @@ def test_initialize_client_w_rest():
assert client is not None
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_create_serving_config_empty_call_rest():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.create_serving_config), "__call__"
+ ) as call:
+ client.create_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.CreateServingConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_serving_config_empty_call_rest():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.delete_serving_config), "__call__"
+ ) as call:
+ client.delete_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.DeleteServingConfigRequest()
+ assert args[0] == request_msg
+
+
# This 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_serving_config_empty_call_rest():
@@ -2455,6 +6012,48 @@ def test_update_serving_config_empty_call_rest():
assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_serving_config_empty_call_rest():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_serving_config), "__call__"
+ ) as call:
+ client.get_serving_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.GetServingConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_serving_configs_empty_call_rest():
+ client = ServingConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_serving_configs), "__call__"
+ ) as call:
+ client.list_serving_configs(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = serving_config_service.ListServingConfigsRequest()
+ assert args[0] == request_msg
+
+
def test_transport_grpc_default():
# A client should use the gRPC transport by default.
client = ServingConfigServiceClient(
@@ -2488,7 +6087,11 @@ def test_serving_config_service_base_transport():
# Every method on the transport should just blindly
# raise NotImplementedError.
methods = (
+ "create_serving_config",
+ "delete_serving_config",
"update_serving_config",
+ "get_serving_config",
+ "list_serving_configs",
"get_operation",
"cancel_operation",
"list_operations",
@@ -2528,7 +6131,11 @@ def test_serving_config_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2554,7 +6161,11 @@ def test_serving_config_service_auth_adc():
ServingConfigServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -2574,7 +6185,11 @@ def test_serving_config_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -2627,7 +6242,11 @@ def test_serving_config_service_transport_create_channel(transport_class, grpc_h
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -2759,9 +6378,21 @@ def test_serving_config_service_client_transport_session_collision(transport_nam
credentials=creds2,
transport=transport_name,
)
+ session1 = client1.transport.create_serving_config._session
+ session2 = client2.transport.create_serving_config._session
+ assert session1 != session2
+ session1 = client1.transport.delete_serving_config._session
+ session2 = client2.transport.delete_serving_config._session
+ assert session1 != session2
session1 = client1.transport.update_serving_config._session
session2 = client2.transport.update_serving_config._session
assert session1 != session2
+ session1 = client1.transport.get_serving_config._session
+ session2 = client2.transport.get_serving_config._session
+ assert session1 != session2
+ session1 = client1.transport.list_serving_configs._session
+ session2 = client2.transport.list_serving_configs._session
+ assert session1 != session2
def test_serving_config_service_grpc_transport_channel():
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_session_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_session_service.py
index 30dfc441b50d..9080a192a9d6 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_session_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_session_service.py
@@ -39,9 +39,12 @@
HAS_GOOGLE_AUTH_AIO = False
import google.auth
+import google.protobuf.any_pb2 as any_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.rpc.status_pb2 as status_pb2 # type: ignore
+import google.type.date_pb2 as date_pb2 # type: ignore
from google.api_core import (
client_options,
gapic_v1,
@@ -67,6 +70,7 @@
answer,
assist_answer,
conversational_search_service,
+ grounded_generation_service,
safety,
session,
)
@@ -1057,7 +1061,12 @@ def test_session_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -1095,6 +1104,7 @@ def test_create_session(request_type, transport: str = "grpc"):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
response = client.create_session(request)
@@ -1112,6 +1122,10 @@ def test_create_session(request_type, transport: str = "grpc"):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_create_session_non_empty_request_with_auto_populated_field():
@@ -1127,6 +1141,7 @@ def test_create_session_non_empty_request_with_auto_populated_field():
# if they meet the requirements of AIP 4235.
request = conversational_search_service.CreateSessionRequest(
parent="parent_value",
+ session_id="session_id_value",
)
# Mock the actual call within the gRPC stub, and fake the request.
@@ -1139,6 +1154,7 @@ def test_create_session_non_empty_request_with_auto_populated_field():
_, args, _ = call.mock_calls[0]
request_msg = conversational_search_service.CreateSessionRequest(
parent="parent_value",
+ session_id="session_id_value",
)
assert args[0] == request_msg
@@ -1249,6 +1265,7 @@ async def test_create_session_async(request_type, transport: str = "grpc_asyncio
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
response = await client.create_session(request)
@@ -1267,6 +1284,10 @@ async def test_create_session_async(request_type, transport: str = "grpc_asyncio
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_create_session_field_headers():
@@ -1757,6 +1778,7 @@ def test_update_session(request_type, transport: str = "grpc"):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
response = client.update_session(request)
@@ -1774,6 +1796,10 @@ def test_update_session(request_type, transport: str = "grpc"):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_update_session_non_empty_request_with_auto_populated_field():
@@ -1907,6 +1933,7 @@ async def test_update_session_async(request_type, transport: str = "grpc_asyncio
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
response = await client.update_session(request)
@@ -1925,6 +1952,10 @@ async def test_update_session_async(request_type, transport: str = "grpc_asyncio
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_update_session_field_headers():
@@ -2103,6 +2134,7 @@ def test_get_session(request_type, transport: str = "grpc"):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
response = client.get_session(request)
@@ -2120,6 +2152,10 @@ def test_get_session(request_type, transport: str = "grpc"):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_get_session_non_empty_request_with_auto_populated_field():
@@ -2257,6 +2293,7 @@ async def test_get_session_async(request_type, transport: str = "grpc_asyncio"):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
response = await client.get_session(request)
@@ -2275,6 +2312,10 @@ async def test_get_session_async(request_type, transport: str = "grpc_asyncio"):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
def test_get_session_field_headers():
@@ -3006,6 +3047,9 @@ def test_create_session_rest_required_fields(
jsonified_request["parent"] = "parent_value"
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("sessionId",))
+
# verify required fields with non-default values are left alone
assert "parent" in jsonified_request
assert jsonified_request["parent"] == "parent_value"
@@ -4123,6 +4167,7 @@ async def test_create_session_empty_call_grpc_asyncio():
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
await client.create_session(request=None)
@@ -4176,6 +4221,7 @@ async def test_update_session_empty_call_grpc_asyncio():
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
await client.update_session(request=None)
@@ -4207,6 +4253,7 @@ async def test_get_session_empty_call_grpc_asyncio():
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
)
await client.get_session(request=None)
@@ -4415,6 +4462,7 @@ def test_create_session_rest_call_success(request_type):
"detailed_assist_answer": {
"name": "name_value",
"state": 1,
+ "connector_display_names": {},
"replies": [
{
"grounded_content": {
@@ -4428,16 +4476,26 @@ def test_create_session_rest_call_success(request_type):
"text": "text_value",
}
],
+ "visual_segments": [
+ {
+ "reference_indices": [1774, 1775],
+ "content_id": "content_id_value",
+ }
+ ],
"references": [
{
"content": "content_value",
+ "code_snippet": "code_snippet_value",
"document_metadata": {
+ "language": 1,
"document": "document_value",
"uri": "uri_value",
"title": "title_value",
"page_identifier": "page_identifier_value",
"domain": "domain_value",
+ "mime_type": "mime_type_value",
},
+ "chunk_metadata": {},
}
],
},
@@ -4459,18 +4517,64 @@ def test_create_session_rest_call_success(request_type):
"role": "role_value",
"thought": True,
},
- }
+ "citation_metadata": {
+ "citations": [
+ {
+ "start_index": 1189,
+ "end_index": 942,
+ "uri": "uri_value",
+ "title": "title_value",
+ "license_": "license__value",
+ "publication_date": {
+ "year": 433,
+ "month": 550,
+ "day": 318,
+ },
+ }
+ ]
+ },
+ },
+ "create_time": {},
}
],
"assist_skipped_reasons": [1],
+ "customer_policy_enforcement_result": {
+ "verdict": 1,
+ "policy_results": [
+ {
+ "banned_phrase_enforcement_result": {
+ "banned_phrases": [
+ "banned_phrases_value1",
+ "banned_phrases_value2",
+ ]
+ },
+ "model_armor_enforcement_result": {
+ "model_armor_violation": "model_armor_violation_value",
+ "error": {
+ "code": 411,
+ "message": "message_value",
+ "details": [
+ {
+ "type_url": "type.googleapis.com/google.protobuf.Duration",
+ "value": b"\x08\x0c\x10\xdb\x07",
+ }
+ ],
+ },
+ },
+ }
+ ],
+ "violation_source": 1,
+ },
},
"query_config": {},
+ "live": True,
}
],
"labels": ["labels_value1", "labels_value2"],
"start_time": {},
"end_time": {},
"is_pinned": True,
+ "pending_async_assist_operation_id": "pending_async_assist_operation_id_value",
}
# The version of a generated dependency at test runtime may differ from the version used during generation.
# Delete any fields which are not present in the current runtime dependency
@@ -4553,6 +4657,7 @@ def get_message_fields(field):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
# Wrap the value into a proper Response obj
@@ -4575,6 +4680,10 @@ def get_message_fields(field):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -4928,6 +5037,7 @@ def test_update_session_rest_call_success(request_type):
"detailed_assist_answer": {
"name": "name_value",
"state": 1,
+ "connector_display_names": {},
"replies": [
{
"grounded_content": {
@@ -4941,16 +5051,26 @@ def test_update_session_rest_call_success(request_type):
"text": "text_value",
}
],
+ "visual_segments": [
+ {
+ "reference_indices": [1774, 1775],
+ "content_id": "content_id_value",
+ }
+ ],
"references": [
{
"content": "content_value",
+ "code_snippet": "code_snippet_value",
"document_metadata": {
+ "language": 1,
"document": "document_value",
"uri": "uri_value",
"title": "title_value",
"page_identifier": "page_identifier_value",
"domain": "domain_value",
+ "mime_type": "mime_type_value",
},
+ "chunk_metadata": {},
}
],
},
@@ -4972,18 +5092,64 @@ def test_update_session_rest_call_success(request_type):
"role": "role_value",
"thought": True,
},
- }
+ "citation_metadata": {
+ "citations": [
+ {
+ "start_index": 1189,
+ "end_index": 942,
+ "uri": "uri_value",
+ "title": "title_value",
+ "license_": "license__value",
+ "publication_date": {
+ "year": 433,
+ "month": 550,
+ "day": 318,
+ },
+ }
+ ]
+ },
+ },
+ "create_time": {},
}
],
"assist_skipped_reasons": [1],
+ "customer_policy_enforcement_result": {
+ "verdict": 1,
+ "policy_results": [
+ {
+ "banned_phrase_enforcement_result": {
+ "banned_phrases": [
+ "banned_phrases_value1",
+ "banned_phrases_value2",
+ ]
+ },
+ "model_armor_enforcement_result": {
+ "model_armor_violation": "model_armor_violation_value",
+ "error": {
+ "code": 411,
+ "message": "message_value",
+ "details": [
+ {
+ "type_url": "type.googleapis.com/google.protobuf.Duration",
+ "value": b"\x08\x0c\x10\xdb\x07",
+ }
+ ],
+ },
+ },
+ }
+ ],
+ "violation_source": 1,
+ },
},
"query_config": {},
+ "live": True,
}
],
"labels": ["labels_value1", "labels_value2"],
"start_time": {},
"end_time": {},
"is_pinned": True,
+ "pending_async_assist_operation_id": "pending_async_assist_operation_id_value",
}
# The version of a generated dependency at test runtime may differ from the version used during generation.
# Delete any fields which are not present in the current runtime dependency
@@ -5066,6 +5232,7 @@ def get_message_fields(field):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
# Wrap the value into a proper Response obj
@@ -5088,6 +5255,10 @@ def get_message_fields(field):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -5211,6 +5382,7 @@ def test_get_session_rest_call_success(request_type):
user_pseudo_id="user_pseudo_id_value",
labels=["labels_value"],
is_pinned=True,
+ pending_async_assist_operation_id="pending_async_assist_operation_id_value",
)
# Wrap the value into a proper Response obj
@@ -5233,6 +5405,10 @@ def test_get_session_rest_call_success(request_type):
assert response.user_pseudo_id == "user_pseudo_id_value"
assert response.labels == ["labels_value"]
assert response.is_pinned is True
+ assert (
+ response.pending_async_assist_operation_id
+ == "pending_async_assist_operation_id_value"
+ )
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -5802,7 +5978,12 @@ def test_session_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5828,7 +6009,12 @@ def test_session_service_auth_adc():
SessionServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -5848,7 +6034,12 @@ def test_session_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -5901,7 +6092,12 @@ def test_session_service_transport_create_channel(transport_class, grpc_helpers)
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_site_search_engine_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_site_search_engine_service.py
index dcaee36d9c91..dfd6d8d46b01 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_site_search_engine_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_site_search_engine_service.py
@@ -1107,7 +1107,11 @@ def test_site_search_engine_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -12330,7 +12334,11 @@ def test_site_search_engine_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -12356,7 +12364,11 @@ def test_site_search_engine_service_auth_adc():
SiteSearchEngineServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -12376,7 +12388,11 @@ def test_site_search_engine_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -12431,7 +12447,11 @@ def test_site_search_engine_service_transport_create_channel(
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py
index 253dcf11fbd1..85feb9b0e2ce 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_event_service.py
@@ -45,6 +45,7 @@
import google.protobuf.duration_pb2 as duration_pb2 # type: ignore
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
import google.type.date_pb2 as date_pb2 # type: ignore
+import google.type.latlng_pb2 as latlng_pb2 # type: ignore
from google.api_core import (
client_options,
future,
@@ -70,8 +71,10 @@
)
from google.cloud.discoveryengine_v1.types import (
common,
+ feedback,
import_config,
purge_config,
+ session,
user_event,
user_event_service,
)
@@ -1090,7 +1093,12 @@ def test_user_event_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -1133,6 +1141,7 @@ def test_write_user_event(request_type, transport: str = "grpc"):
filter="filter_value",
tag_ids=["tag_ids_value"],
promotion_ids=["promotion_ids_value"],
+ entity="entity_value",
)
response = client.write_user_event(request)
@@ -1155,6 +1164,7 @@ def test_write_user_event(request_type, transport: str = "grpc"):
assert response.filter == "filter_value"
assert response.tag_ids == ["tag_ids_value"]
assert response.promotion_ids == ["promotion_ids_value"]
+ assert response.entity == "entity_value"
def test_write_user_event_non_empty_request_with_auto_populated_field():
@@ -1299,6 +1309,7 @@ async def test_write_user_event_async(request_type, transport: str = "grpc_async
filter="filter_value",
tag_ids=["tag_ids_value"],
promotion_ids=["promotion_ids_value"],
+ entity="entity_value",
)
)
response = await client.write_user_event(request)
@@ -1322,6 +1333,7 @@ async def test_write_user_event_async(request_type, transport: str = "grpc_async
assert response.filter == "filter_value"
assert response.tag_ids == ["tag_ids_value"]
assert response.promotion_ids == ["promotion_ids_value"]
+ assert response.entity == "entity_value"
def test_write_user_event_field_headers():
@@ -2888,6 +2900,7 @@ async def test_write_user_event_empty_call_grpc_asyncio():
filter="filter_value",
tag_ids=["tag_ids_value"],
promotion_ids=["promotion_ids_value"],
+ entity="entity_value",
)
)
await client.write_user_event(request=None)
@@ -3038,6 +3051,10 @@ def test_write_user_event_rest_call_success(request_type):
"user_id": "user_id_value",
"user_agent": "user_agent_value",
"time_zone": "time_zone_value",
+ "precise_location": {
+ "point": {"latitude": 0.86, "longitude": 0.971},
+ "address": "address_value",
+ },
},
"direct_user_request": True,
"session_id": "session_id_value",
@@ -3092,6 +3109,26 @@ def test_write_user_event_rest_call_success(request_type):
"media_progress_percentage": 0.2641,
},
"panels": {},
+ "feedback": {
+ "feedback_type": 1,
+ "reasons": [1],
+ "comment": "comment_value",
+ "conversation_info": {
+ "question_index": 1519,
+ "session": "session_value",
+ "query": {"text": "text_value", "query_id": "query_id_value"},
+ "assist_token": "assist_token_value",
+ "answer_query_token": "answer_query_token_value",
+ "task_name": "task_name_value",
+ "trajectory_id": "trajectory_id_value",
+ "step_seq_num": 1299,
+ },
+ "llm_model_version": "llm_model_version_value",
+ "feedback_source": 1,
+ "component_version": "component_version_value",
+ "data_terms_accepted": True,
+ },
+ "entity": "entity_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
@@ -3177,6 +3214,7 @@ def get_message_fields(field):
filter="filter_value",
tag_ids=["tag_ids_value"],
promotion_ids=["promotion_ids_value"],
+ entity="entity_value",
)
# Wrap the value into a proper Response obj
@@ -3204,6 +3242,7 @@ def get_message_fields(field):
assert response.filter == "filter_value"
assert response.tag_ids == ["tag_ids_value"]
assert response.promotion_ids == ["promotion_ids_value"]
+ assert response.entity == "entity_value"
@pytest.mark.parametrize("null_interceptor", [True, False])
@@ -4027,7 +4066,12 @@ def test_user_event_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -4053,7 +4097,12 @@ def test_user_event_service_auth_adc():
UserEventServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -4073,7 +4122,12 @@ def test_user_event_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -4126,7 +4180,12 @@ def test_user_event_service_transport_create_channel(transport_class, grpc_helpe
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_license_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_license_service.py
index 651fe99f6dc6..65ccf7654943 100644
--- a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_license_service.py
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_license_service.py
@@ -1086,7 +1086,11 @@ def test_user_license_service_client_create_channel_credentials_file(
credentials=file_creds,
credentials_file=None,
quota_project_id=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=None,
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -1150,6 +1154,7 @@ def test_list_user_licenses_non_empty_request_with_auto_populated_field():
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.
@@ -1166,6 +1171,7 @@ def test_list_user_licenses_non_empty_request_with_auto_populated_field():
parent="parent_value",
page_token="page_token_value",
filter="filter_value",
+ order_by="order_by_value",
)
assert args[0] == request_msg
@@ -1649,11 +1655,11 @@ async def test_list_user_licenses_async_pages():
@pytest.mark.parametrize(
"request_type",
[
- user_license_service.BatchUpdateUserLicensesRequest(),
+ user_license_service.ListLicenseConfigsUsageStatsRequest(),
{},
],
)
-def test_batch_update_user_licenses(request_type, transport: str = "grpc"):
+def test_list_license_configs_usage_stats(request_type, transport: str = "grpc"):
client = UserLicenseServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -1665,23 +1671,25 @@ def test_batch_update_user_licenses(request_type, transport: str = "grpc"):
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
- type(client.transport.batch_update_user_licenses), "__call__"
+ type(client.transport.list_license_configs_usage_stats), "__call__"
) as call:
# Designate an appropriate return value for the call.
- call.return_value = operations_pb2.Operation(name="operations/spam")
- response = client.batch_update_user_licenses(request)
+ call.return_value = user_license_service.ListLicenseConfigsUsageStatsResponse()
+ response = client.list_license_configs_usage_stats(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
_, args, _ = call.mock_calls[0]
- request = user_license_service.BatchUpdateUserLicensesRequest()
+ request = user_license_service.ListLicenseConfigsUsageStatsRequest()
assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, future.Future)
+ assert isinstance(
+ response, user_license_service.ListLicenseConfigsUsageStatsResponse
+ )
-def test_batch_update_user_licenses_non_empty_request_with_auto_populated_field():
+def test_list_license_configs_usage_stats_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 = UserLicenseServiceClient(
@@ -1692,27 +1700,27 @@ def test_batch_update_user_licenses_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 = user_license_service.BatchUpdateUserLicensesRequest(
+ request = user_license_service.ListLicenseConfigsUsageStatsRequest(
parent="parent_value",
)
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
- type(client.transport.batch_update_user_licenses), "__call__"
+ type(client.transport.list_license_configs_usage_stats), "__call__"
) as call:
call.return_value.name = (
"foo" # operation_request.operation in compute client(s) expect a string.
)
- client.batch_update_user_licenses(request=request)
+ client.list_license_configs_usage_stats(request=request)
call.assert_called()
_, args, _ = call.mock_calls[0]
- request_msg = user_license_service.BatchUpdateUserLicensesRequest(
+ request_msg = user_license_service.ListLicenseConfigsUsageStatsRequest(
parent="parent_value",
)
assert args[0] == request_msg
-def test_batch_update_user_licenses_use_cached_wrapped_rpc():
+def test_list_license_configs_usage_stats_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
@@ -1727,7 +1735,7 @@ def test_batch_update_user_licenses_use_cached_wrapped_rpc():
# Ensure method has been cached
assert (
- client._transport.batch_update_user_licenses
+ client._transport.list_license_configs_usage_stats
in client._transport._wrapped_methods
)
@@ -1737,20 +1745,15 @@ def test_batch_update_user_licenses_use_cached_wrapped_rpc():
"foo" # operation_request.operation in compute client(s) expect a string.
)
client._transport._wrapped_methods[
- client._transport.batch_update_user_licenses
+ client._transport.list_license_configs_usage_stats
] = mock_rpc
request = {}
- client.batch_update_user_licenses(request)
+ client.list_license_configs_usage_stats(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.batch_update_user_licenses(request)
+ client.list_license_configs_usage_stats(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
@@ -1758,7 +1761,7 @@ def test_batch_update_user_licenses_use_cached_wrapped_rpc():
@pytest.mark.asyncio
-async def test_batch_update_user_licenses_async_use_cached_wrapped_rpc(
+async def test_list_license_configs_usage_stats_async_use_cached_wrapped_rpc(
transport: str = "grpc_asyncio",
):
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
@@ -1775,7 +1778,7 @@ async def test_batch_update_user_licenses_async_use_cached_wrapped_rpc(
# Ensure method has been cached
assert (
- client._client._transport.batch_update_user_licenses
+ client._client._transport.list_license_configs_usage_stats
in client._client._transport._wrapped_methods
)
@@ -1783,21 +1786,16 @@ async def test_batch_update_user_licenses_async_use_cached_wrapped_rpc(
mock_rpc = mock.AsyncMock()
mock_rpc.return_value = mock.Mock()
client._client._transport._wrapped_methods[
- client._client._transport.batch_update_user_licenses
+ client._client._transport.list_license_configs_usage_stats
] = mock_rpc
request = {}
- await client.batch_update_user_licenses(request)
+ await client.list_license_configs_usage_stats(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.batch_update_user_licenses(request)
+ await client.list_license_configs_usage_stats(request)
# Establish that a new wrapper was not created for this call
assert wrapper_fn.call_count == 0
@@ -1808,11 +1806,11 @@ async def test_batch_update_user_licenses_async_use_cached_wrapped_rpc(
@pytest.mark.parametrize(
"request_type",
[
- user_license_service.BatchUpdateUserLicensesRequest(),
+ user_license_service.ListLicenseConfigsUsageStatsRequest(),
{},
],
)
-async def test_batch_update_user_licenses_async(
+async def test_list_license_configs_usage_stats_async(
request_type, transport: str = "grpc_asyncio"
):
client = UserLicenseServiceAsyncClient(
@@ -1826,41 +1824,43 @@ async def test_batch_update_user_licenses_async(
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
- type(client.transport.batch_update_user_licenses), "__call__"
+ type(client.transport.list_license_configs_usage_stats), "__call__"
) as call:
# Designate an appropriate return value for the call.
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/spam")
+ user_license_service.ListLicenseConfigsUsageStatsResponse()
)
- response = await client.batch_update_user_licenses(request)
+ response = await client.list_license_configs_usage_stats(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
_, args, _ = call.mock_calls[0]
- request = user_license_service.BatchUpdateUserLicensesRequest()
+ request = user_license_service.ListLicenseConfigsUsageStatsRequest()
assert args[0] == request
# Establish that the response is the type that we expect.
- assert isinstance(response, future.Future)
+ assert isinstance(
+ response, user_license_service.ListLicenseConfigsUsageStatsResponse
+ )
-def test_batch_update_user_licenses_field_headers():
+def test_list_license_configs_usage_stats_field_headers():
client = UserLicenseServiceClient(
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 = user_license_service.BatchUpdateUserLicensesRequest()
+ request = user_license_service.ListLicenseConfigsUsageStatsRequest()
request.parent = "parent_value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
- type(client.transport.batch_update_user_licenses), "__call__"
+ type(client.transport.list_license_configs_usage_stats), "__call__"
) as call:
- call.return_value = operations_pb2.Operation(name="operations/op")
- client.batch_update_user_licenses(request)
+ call.return_value = user_license_service.ListLicenseConfigsUsageStatsResponse()
+ client.list_license_configs_usage_stats(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls) == 1
@@ -1876,25 +1876,25 @@ def test_batch_update_user_licenses_field_headers():
@pytest.mark.asyncio
-async def test_batch_update_user_licenses_field_headers_async():
+async def test_list_license_configs_usage_stats_field_headers_async():
client = UserLicenseServiceAsyncClient(
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 = user_license_service.BatchUpdateUserLicensesRequest()
+ request = user_license_service.ListLicenseConfigsUsageStatsRequest()
request.parent = "parent_value"
# Mock the actual call within the gRPC stub, and fake the request.
with mock.patch.object(
- type(client.transport.batch_update_user_licenses), "__call__"
+ type(client.transport.list_license_configs_usage_stats), "__call__"
) as call:
call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
- operations_pb2.Operation(name="operations/op")
+ user_license_service.ListLicenseConfigsUsageStatsResponse()
)
- await client.batch_update_user_licenses(request)
+ await client.list_license_configs_usage_stats(request)
# Establish that the underlying gRPC stub method was called.
assert len(call.mock_calls)
@@ -1909,13 +1909,165 @@ async def test_batch_update_user_licenses_field_headers_async():
) in kw["metadata"]
-def test_list_user_licenses_rest_use_cached_wrapped_rpc():
+def test_list_license_configs_usage_stats_flattened():
+ client = UserLicenseServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs_usage_stats), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = user_license_service.ListLicenseConfigsUsageStatsResponse()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.list_license_configs_usage_stats(
+ 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_license_configs_usage_stats_flattened_error():
+ client = UserLicenseServiceClient(
+ 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_license_configs_usage_stats(
+ user_license_service.ListLicenseConfigsUsageStatsRequest(),
+ parent="parent_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_list_license_configs_usage_stats_flattened_async():
+ client = UserLicenseServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs_usage_stats), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = user_license_service.ListLicenseConfigsUsageStatsResponse()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ user_license_service.ListLicenseConfigsUsageStatsResponse()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.list_license_configs_usage_stats(
+ 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_license_configs_usage_stats_flattened_error_async():
+ client = UserLicenseServiceAsyncClient(
+ 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_license_configs_usage_stats(
+ user_license_service.ListLicenseConfigsUsageStatsRequest(),
+ parent="parent_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ user_license_service.BatchUpdateUserLicensesRequest(),
+ {},
+ ],
+)
+def test_batch_update_user_licenses(request_type, transport: str = "grpc"):
+ client = UserLicenseServiceClient(
+ 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.batch_update_user_licenses), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation(name="operations/spam")
+ response = client.batch_update_user_licenses(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = user_license_service.BatchUpdateUserLicensesRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_batch_update_user_licenses_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 = UserLicenseServiceClient(
+ 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 = user_license_service.BatchUpdateUserLicensesRequest(
+ parent="parent_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_update_user_licenses), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.batch_update_user_licenses(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_license_service.BatchUpdateUserLicensesRequest(
+ parent="parent_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_batch_update_user_licenses_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
client = UserLicenseServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
- transport="rest",
+ transport="grpc",
)
# Should wrap all calls on client creation
@@ -1924,7 +2076,8 @@ def test_list_user_licenses_rest_use_cached_wrapped_rpc():
# Ensure method has been cached
assert (
- client._transport.list_user_licenses in client._transport._wrapped_methods
+ client._transport.batch_update_user_licenses
+ in client._transport._wrapped_methods
)
# Replace cached wrapped function with mock
@@ -1932,56 +2085,253 @@ def test_list_user_licenses_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_user_licenses] = (
- mock_rpc
- )
-
+ client._transport._wrapped_methods[
+ client._transport.batch_update_user_licenses
+ ] = mock_rpc
request = {}
- client.list_user_licenses(request)
+ client.batch_update_user_licenses(request)
# Establish that the underlying gRPC stub method was called.
assert mock_rpc.call_count == 1
- client.list_user_licenses(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.batch_update_user_licenses(request)
# Establish 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_user_licenses_rest_required_fields(
- request_type=user_license_service.ListUserLicensesRequest,
+@pytest.mark.asyncio
+async def test_batch_update_user_licenses_async_use_cached_wrapped_rpc(
+ transport: str = "grpc_asyncio",
):
- transport_class = transports.UserLicenseServiceRestTransport
-
- 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
+ # Clients should use _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 = UserLicenseServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
- default_values = getattr(
- transport_class._BaseListUserLicenses,
- "_BaseListUserLicenses__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)
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
- # verify required fields with default values are now present
+ # Ensure method has been cached
+ assert (
+ client._client._transport.batch_update_user_licenses
+ in client._client._transport._wrapped_methods
+ )
- jsonified_request["parent"] = "parent_value"
+ # Replace cached wrapped function with mock
+ mock_rpc = mock.AsyncMock()
+ mock_rpc.return_value = mock.Mock()
+ client._client._transport._wrapped_methods[
+ client._client._transport.batch_update_user_licenses
+ ] = mock_rpc
+
+ request = {}
+ await client.batch_update_user_licenses(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.batch_update_user_licenses(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",
+ [
+ user_license_service.BatchUpdateUserLicensesRequest(),
+ {},
+ ],
+)
+async def test_batch_update_user_licenses_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = UserLicenseServiceAsyncClient(
+ 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.batch_update_user_licenses), "__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.batch_update_user_licenses(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = user_license_service.BatchUpdateUserLicensesRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, future.Future)
+
+
+def test_batch_update_user_licenses_field_headers():
+ client = UserLicenseServiceClient(
+ 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 = user_license_service.BatchUpdateUserLicensesRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_update_user_licenses), "__call__"
+ ) as call:
+ call.return_value = operations_pb2.Operation(name="operations/op")
+ client.batch_update_user_licenses(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_batch_update_user_licenses_field_headers_async():
+ client = UserLicenseServiceAsyncClient(
+ 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 = user_license_service.BatchUpdateUserLicensesRequest()
+
+ request.parent = "parent_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.batch_update_user_licenses), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation(name="operations/op")
+ )
+ await client.batch_update_user_licenses(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_user_licenses_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = UserLicenseServiceClient(
+ 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_user_licenses in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_user_licenses] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.list_user_licenses(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_user_licenses(request)
+
+ # Establish 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_user_licenses_rest_required_fields(
+ request_type=user_license_service.ListUserLicensesRequest,
+):
+ transport_class = transports.UserLicenseServiceRestTransport
+
+ 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._BaseListUserLicenses,
+ "_BaseListUserLicenses__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",
)
@@ -2028,14 +2378,260 @@ def test_list_user_licenses_rest_required_fields(
req.return_value = response_value
req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
- response = client.list_user_licenses(request)
+ response = client.list_user_licenses(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_user_licenses_rest_flattened():
+ client = UserLicenseServiceClient(
+ 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 = user_license_service.ListUserLicensesResponse()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "parent": "projects/sample1/locations/sample2/userStores/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 = user_license_service.ListUserLicensesResponse.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_user_licenses(**mock_args)
+
+ # Establish that the underlying call 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/*/userStores/*}/userLicenses"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_list_user_licenses_rest_flattened_error(transport: str = "rest"):
+ client = UserLicenseServiceClient(
+ 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_user_licenses(
+ user_license_service.ListUserLicensesRequest(),
+ parent="parent_value",
+ )
+
+
+def test_list_user_licenses_rest_pager(transport: str = "rest"):
+ client = UserLicenseServiceClient(
+ 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 = (
+ user_license_service.ListUserLicensesResponse(
+ user_licenses=[
+ user_license.UserLicense(),
+ user_license.UserLicense(),
+ user_license.UserLicense(),
+ ],
+ next_page_token="abc",
+ ),
+ user_license_service.ListUserLicensesResponse(
+ user_licenses=[],
+ next_page_token="def",
+ ),
+ user_license_service.ListUserLicensesResponse(
+ user_licenses=[
+ user_license.UserLicense(),
+ ],
+ next_page_token="ghi",
+ ),
+ user_license_service.ListUserLicensesResponse(
+ user_licenses=[
+ user_license.UserLicense(),
+ user_license.UserLicense(),
+ ],
+ ),
+ )
+ # Two responses for two calls
+ response = response + response
+
+ # Wrap the values into proper Response objs
+ response = tuple(
+ user_license_service.ListUserLicensesResponse.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/userStores/sample3"
+ }
+
+ pager = client.list_user_licenses(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, user_license.UserLicense) for i in results)
+
+ pages = list(client.list_user_licenses(request=sample_request).pages)
+ for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
+ assert page_.raw_page.next_page_token == token
+
+
+def test_list_license_configs_usage_stats_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = UserLicenseServiceClient(
+ 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_license_configs_usage_stats
+ in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_license_configs_usage_stats
+ ] = mock_rpc
+
+ request = {}
+ client.list_license_configs_usage_stats(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.list_license_configs_usage_stats(request)
+
+ # Establish 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_license_configs_usage_stats_rest_required_fields(
+ request_type=user_license_service.ListLicenseConfigsUsageStatsRequest,
+):
+ transport_class = transports.UserLicenseServiceRestTransport
+
+ 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._BaseListLicenseConfigsUsageStats,
+ "_BaseListLicenseConfigsUsageStats__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 = UserLicenseServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = user_license_service.ListLicenseConfigsUsageStatsResponse()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = user_license_service.ListLicenseConfigsUsageStatsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_license_configs_usage_stats(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_user_licenses_rest_flattened():
+def test_list_license_configs_usage_stats_rest_flattened():
client = UserLicenseServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport="rest",
@@ -2044,7 +2640,7 @@ def test_list_user_licenses_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 = user_license_service.ListUserLicensesResponse()
+ return_value = user_license_service.ListLicenseConfigsUsageStatsResponse()
# get arguments that satisfy an http rule for this method
sample_request = {
@@ -2061,26 +2657,28 @@ def test_list_user_licenses_rest_flattened():
response_value = Response()
response_value.status_code = 200
# Convert return value to protobuf type
- return_value = user_license_service.ListUserLicensesResponse.pb(return_value)
+ return_value = user_license_service.ListLicenseConfigsUsageStatsResponse.pb(
+ return_value
+ )
json_return_value = json_format.MessageToJson(return_value)
response_value._content = 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_user_licenses(**mock_args)
+ client.list_license_configs_usage_stats(**mock_args)
# Establish that the underlying call 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/*/userStores/*}/userLicenses"
+ "%s/v1/{parent=projects/*/locations/*/userStores/*}/licenseConfigsUsageStats"
% client.transport._host,
args[1],
)
-def test_list_user_licenses_rest_flattened_error(transport: str = "rest"):
+def test_list_license_configs_usage_stats_rest_flattened_error(transport: str = "rest"):
client = UserLicenseServiceClient(
credentials=ga_credentials.AnonymousCredentials(),
transport=transport,
@@ -2089,80 +2687,12 @@ def test_list_user_licenses_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_user_licenses(
- user_license_service.ListUserLicensesRequest(),
+ client.list_license_configs_usage_stats(
+ user_license_service.ListLicenseConfigsUsageStatsRequest(),
parent="parent_value",
)
-def test_list_user_licenses_rest_pager(transport: str = "rest"):
- client = UserLicenseServiceClient(
- 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 = (
- user_license_service.ListUserLicensesResponse(
- user_licenses=[
- user_license.UserLicense(),
- user_license.UserLicense(),
- user_license.UserLicense(),
- ],
- next_page_token="abc",
- ),
- user_license_service.ListUserLicensesResponse(
- user_licenses=[],
- next_page_token="def",
- ),
- user_license_service.ListUserLicensesResponse(
- user_licenses=[
- user_license.UserLicense(),
- ],
- next_page_token="ghi",
- ),
- user_license_service.ListUserLicensesResponse(
- user_licenses=[
- user_license.UserLicense(),
- user_license.UserLicense(),
- ],
- ),
- )
- # Two responses for two calls
- response = response + response
-
- # Wrap the values into proper Response objs
- response = tuple(
- user_license_service.ListUserLicensesResponse.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/userStores/sample3"
- }
-
- pager = client.list_user_licenses(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, user_license.UserLicense) for i in results)
-
- pages = list(client.list_user_licenses(request=sample_request).pages)
- for page_, token in zip(pages, ["abc", "def", "ghi", ""]):
- assert page_.raw_page.next_page_token == token
-
-
def test_batch_update_user_licenses_rest_use_cached_wrapped_rpc():
# Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
# instead of constructing them on each call
@@ -2409,6 +2939,28 @@ def test_list_user_licenses_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_list_license_configs_usage_stats_empty_call_grpc():
+ client = UserLicenseServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs_usage_stats), "__call__"
+ ) as call:
+ call.return_value = user_license_service.ListLicenseConfigsUsageStatsResponse()
+ client.list_license_configs_usage_stats(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_license_service.ListLicenseConfigsUsageStatsRequest()
+ assert args[0] == request_msg
+
+
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
def test_batch_update_user_licenses_empty_call_grpc():
@@ -2473,6 +3025,32 @@ async def test_list_user_licenses_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_list_license_configs_usage_stats_empty_call_grpc_asyncio():
+ client = UserLicenseServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs_usage_stats), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ user_license_service.ListLicenseConfigsUsageStatsResponse()
+ )
+ await client.list_license_configs_usage_stats(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_license_service.ListLicenseConfigsUsageStatsRequest()
+ assert args[0] == request_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
@@ -2642,6 +3220,147 @@ def test_list_user_licenses_rest_interceptors(null_interceptor):
post_with_metadata.assert_called_once()
+def test_list_license_configs_usage_stats_rest_bad_request(
+ request_type=user_license_service.ListLicenseConfigsUsageStatsRequest,
+):
+ client = UserLicenseServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/userStores/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_license_configs_usage_stats(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ user_license_service.ListLicenseConfigsUsageStatsRequest,
+ dict,
+ ],
+)
+def test_list_license_configs_usage_stats_rest_call_success(request_type):
+ client = UserLicenseServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"parent": "projects/sample1/locations/sample2/userStores/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 = user_license_service.ListLicenseConfigsUsageStatsResponse()
+
+ # 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 = user_license_service.ListLicenseConfigsUsageStatsResponse.pb(
+ return_value
+ )
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_license_configs_usage_stats(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(
+ response, user_license_service.ListLicenseConfigsUsageStatsResponse
+ )
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_list_license_configs_usage_stats_rest_interceptors(null_interceptor):
+ transport = transports.UserLicenseServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.UserLicenseServiceRestInterceptor(),
+ )
+ client = UserLicenseServiceClient(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.UserLicenseServiceRestInterceptor,
+ "post_list_license_configs_usage_stats",
+ ) as post,
+ mock.patch.object(
+ transports.UserLicenseServiceRestInterceptor,
+ "post_list_license_configs_usage_stats_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.UserLicenseServiceRestInterceptor,
+ "pre_list_license_configs_usage_stats",
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = user_license_service.ListLicenseConfigsUsageStatsRequest.pb(
+ user_license_service.ListLicenseConfigsUsageStatsRequest()
+ )
+ 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 = (
+ user_license_service.ListLicenseConfigsUsageStatsResponse.to_json(
+ user_license_service.ListLicenseConfigsUsageStatsResponse()
+ )
+ )
+ req.return_value.content = return_value
+
+ request = user_license_service.ListLicenseConfigsUsageStatsRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = user_license_service.ListLicenseConfigsUsageStatsResponse()
+ post_with_metadata.return_value = (
+ user_license_service.ListLicenseConfigsUsageStatsResponse(),
+ metadata,
+ )
+
+ client.list_license_configs_usage_stats(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
def test_batch_update_user_licenses_rest_bad_request(
request_type=user_license_service.BatchUpdateUserLicensesRequest,
):
@@ -2985,6 +3704,27 @@ def test_list_user_licenses_empty_call_rest():
assert args[0] == request_msg
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_list_license_configs_usage_stats_empty_call_rest():
+ client = UserLicenseServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.list_license_configs_usage_stats), "__call__"
+ ) as call:
+ client.list_license_configs_usage_stats(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_license_service.ListLicenseConfigsUsageStatsRequest()
+ assert args[0] == request_msg
+
+
# This test is a coverage failsafe to make sure that totally empty calls,
# i.e. request == None and no flattened fields passed, work.
def test_batch_update_user_licenses_empty_call_rest():
@@ -3057,6 +3797,7 @@ def test_user_license_service_base_transport():
# raise NotImplementedError.
methods = (
"list_user_licenses",
+ "list_license_configs_usage_stats",
"batch_update_user_licenses",
"get_operation",
"cancel_operation",
@@ -3102,7 +3843,11 @@ def test_user_license_service_base_transport_with_credentials_file():
load_creds.assert_called_once_with(
"credentials.json",
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -3128,7 +3873,11 @@ def test_user_license_service_auth_adc():
UserLicenseServiceClient()
adc.assert_called_once_with(
scopes=None,
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id=None,
)
@@ -3148,7 +3897,11 @@ def test_user_license_service_transport_auth_adc(transport_class):
transport_class(quota_project_id="octopus", scopes=["1", "2"])
adc.assert_called_once_with(
scopes=["1", "2"],
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
quota_project_id="octopus",
)
@@ -3201,7 +3954,11 @@ def test_user_license_service_transport_create_channel(transport_class, grpc_hel
credentials=creds,
credentials_file=None,
quota_project_id="octopus",
- default_scopes=("https://www.googleapis.com/auth/cloud-platform",),
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
scopes=["1", "2"],
default_host="discoveryengine.googleapis.com",
ssl_credentials=None,
@@ -3336,6 +4093,9 @@ def test_user_license_service_client_transport_session_collision(transport_name)
session1 = client1.transport.list_user_licenses._session
session2 = client2.transport.list_user_licenses._session
assert session1 != session2
+ session1 = client1.transport.list_license_configs_usage_stats._session
+ session2 = client2.transport.list_license_configs_usage_stats._session
+ assert session1 != session2
session1 = client1.transport.batch_update_user_licenses._session
session2 = client2.transport.batch_update_user_licenses._session
assert session1 != session2
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_store_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_store_service.py
new file mode 100644
index 000000000000..498eb5af2a3d
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_user_store_service.py
@@ -0,0 +1,4211 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import asyncio
+import json
+import math
+import os
+from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
+from unittest import mock
+from unittest.mock import AsyncMock
+
+import grpc
+import pytest
+from google.api_core import api_core_version
+from google.protobuf import json_format
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
+
+try:
+ from google.auth.aio import credentials as ga_credentials_async
+
+ HAS_GOOGLE_AUTH_AIO = True
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_AUTH_AIO = False
+
+import google.auth
+import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+from google.api_core import (
+ client_options,
+ gapic_v1,
+ grpc_helpers,
+ grpc_helpers_async,
+ path_template,
+)
+from google.api_core import exceptions as core_exceptions
+from google.api_core import retry as retries
+from google.auth import credentials as ga_credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.location import locations_pb2
+from google.longrunning import operations_pb2 # type: ignore
+from google.oauth2 import service_account
+
+from google.cloud.discoveryengine_v1.services.user_store_service import (
+ UserStoreServiceAsyncClient,
+ UserStoreServiceClient,
+ transports,
+)
+from google.cloud.discoveryengine_v1.types import user_store, user_store_service
+from google.cloud.discoveryengine_v1.types import user_store as gcd_user_store
+
+CRED_INFO_JSON = {
+ "credential_source": "/path/to/file",
+ "credential_type": "service account credentials",
+ "principal": "service-account@example.com",
+}
+CRED_INFO_STRING = json.dumps(CRED_INFO_JSON)
+
+
+@pytest.fixture(autouse=True)
+def disable_mtls_env():
+ with mock.patch.dict(
+ os.environ,
+ {
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false",
+ "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false",
+ },
+ ):
+ yield
+
+
+async def mock_async_gen(data, chunk_size=1):
+ for i in range(0, len(data)): # pragma: NO COVER
+ chunk = data[i : i + chunk_size]
+ yield chunk.encode("utf-8")
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
+# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
+def async_anonymous_credentials():
+ if HAS_GOOGLE_AUTH_AIO:
+ return ga_credentials_async.AnonymousCredentials()
+ return ga_credentials.AnonymousCredentials()
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+# If default endpoint template is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint template so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint_template(client):
+ return (
+ "test.{UNIVERSE_DOMAIN}"
+ if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE)
+ else client._DEFAULT_ENDPOINT_TEMPLATE
+ )
+
+
+@pytest.fixture(autouse=True)
+def set_event_loop():
+ try:
+ asyncio.get_running_loop()
+ yield
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ yield
+ finally:
+ loop.close()
+ asyncio.set_event_loop(None)
+
+
+def test__get_client_cert_source():
+ mock_provided_cert_source = mock.Mock()
+ mock_default_cert_source = mock.Mock()
+
+ assert UserStoreServiceClient._get_client_cert_source(None, False) is None
+ assert (
+ UserStoreServiceClient._get_client_cert_source(mock_provided_cert_source, False)
+ is None
+ )
+ assert (
+ UserStoreServiceClient._get_client_cert_source(mock_provided_cert_source, True)
+ == mock_provided_cert_source
+ )
+
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source", return_value=True
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_default_cert_source,
+ ):
+ assert (
+ UserStoreServiceClient._get_client_cert_source(None, True)
+ is mock_default_cert_source
+ )
+ assert (
+ UserStoreServiceClient._get_client_cert_source(
+ mock_provided_cert_source, "true"
+ )
+ is mock_provided_cert_source
+ )
+
+
+@pytest.mark.parametrize(
+ "error_code,cred_info_json,show_cred_info",
+ [
+ (401, CRED_INFO_JSON, True),
+ (403, CRED_INFO_JSON, True),
+ (404, CRED_INFO_JSON, True),
+ (500, CRED_INFO_JSON, False),
+ (401, None, False),
+ (403, None, False),
+ (404, None, False),
+ (500, None, False),
+ ],
+)
+def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info):
+ cred = mock.Mock(["get_cred_info"])
+ cred.get_cred_info = mock.Mock(return_value=cred_info_json)
+ client = UserStoreServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=["foo"])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ if show_cred_info:
+ assert error.details == ["foo", CRED_INFO_STRING]
+ else:
+ assert error.details == ["foo"]
+
+
+@pytest.mark.parametrize("error_code", [401, 403, 404, 500])
+def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code):
+ cred = mock.Mock([])
+ assert not hasattr(cred, "get_cred_info")
+ client = UserStoreServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=[])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ assert error.details == []
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (UserStoreServiceClient, "grpc"),
+ (UserStoreServiceAsyncClient, "grpc_asyncio"),
+ (UserStoreServiceClient, "rest"),
+ ],
+)
+def test_user_store_service_client_from_service_account_info(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info, transport=transport_name)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.UserStoreServiceGrpcTransport, "grpc"),
+ (transports.UserStoreServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ (transports.UserStoreServiceRestTransport, "rest"),
+ ],
+)
+def test_user_store_service_client_service_account_always_use_jwt(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=False)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (UserStoreServiceClient, "grpc"),
+ (UserStoreServiceAsyncClient, "grpc_asyncio"),
+ (UserStoreServiceClient, "rest"),
+ ],
+)
+def test_user_store_service_client_from_service_account_file(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+def test_user_store_service_client_get_transport_class():
+ transport = UserStoreServiceClient.get_transport_class()
+ available_transports = [
+ transports.UserStoreServiceGrpcTransport,
+ transports.UserStoreServiceRestTransport,
+ ]
+ assert transport in available_transports
+
+ transport = UserStoreServiceClient.get_transport_class("grpc")
+ assert transport == transports.UserStoreServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (UserStoreServiceClient, transports.UserStoreServiceGrpcTransport, "grpc"),
+ (
+ UserStoreServiceAsyncClient,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (UserStoreServiceClient, transports.UserStoreServiceRestTransport, "rest"),
+ ],
+)
+@mock.patch.object(
+ UserStoreServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(UserStoreServiceClient),
+)
+@mock.patch.object(
+ UserStoreServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(UserStoreServiceAsyncClient),
+)
+def test_user_store_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(UserStoreServiceClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(UserStoreServiceClient, "get_transport_class") as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name, client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ # Check the case quota_project_id is provided
+ options = client_options.ClientOptions(quota_project_id="octopus")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id="octopus",
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+ # Check the case api_endpoint is provided
+ options = client_options.ClientOptions(
+ api_audience="https://language.googleapis.com"
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience="https://language.googleapis.com",
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (
+ UserStoreServiceClient,
+ transports.UserStoreServiceGrpcTransport,
+ "grpc",
+ "true",
+ ),
+ (
+ UserStoreServiceAsyncClient,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (
+ UserStoreServiceClient,
+ transports.UserStoreServiceGrpcTransport,
+ "grpc",
+ "false",
+ ),
+ (
+ UserStoreServiceAsyncClient,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ (
+ UserStoreServiceClient,
+ transports.UserStoreServiceRestTransport,
+ "rest",
+ "true",
+ ),
+ (
+ UserStoreServiceClient,
+ transports.UserStoreServiceRestTransport,
+ "rest",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ UserStoreServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(UserStoreServiceClient),
+)
+@mock.patch.object(
+ UserStoreServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(UserStoreServiceAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_user_store_service_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [UserStoreServiceClient, UserStoreServiceAsyncClient]
+)
+@mock.patch.object(
+ UserStoreServiceClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(UserStoreServiceClient),
+)
+@mock.patch.object(
+ UserStoreServiceAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(UserStoreServiceAsyncClient),
+)
+def test_user_store_service_client_get_mtls_endpoint_and_cert_source(client_class):
+ mock_client_cert_source = mock.Mock()
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source == mock_client_cert_source
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported".
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset.
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None)
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None)
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty).
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "")
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "")
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_client_cert_source,
+ ):
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source()
+ )
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source == mock_client_cert_source
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [UserStoreServiceClient, UserStoreServiceAsyncClient]
+)
+@mock.patch.object(
+ UserStoreServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(UserStoreServiceClient),
+)
+@mock.patch.object(
+ UserStoreServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(UserStoreServiceAsyncClient),
+)
+def test_user_store_service_client_client_api_endpoint(client_class):
+ mock_client_cert_source = client_cert_source_callback
+ api_override = "foo.com"
+ default_universe = UserStoreServiceClient._DEFAULT_UNIVERSE
+ default_endpoint = UserStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = UserStoreServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true",
+ # use ClientOptions.api_endpoint as the api endpoint regardless.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=api_override
+ )
+ client = client_class(
+ client_options=options,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert client.api_endpoint == api_override
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == default_endpoint
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always",
+ # use the DEFAULT_MTLS_ENDPOINT as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+
+ # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default),
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist,
+ # and ClientOptions.universe_domain="bar.com",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint.
+ options = client_options.ClientOptions()
+ universe_exists = hasattr(options, "universe_domain")
+ if universe_exists:
+ options = client_options.ClientOptions(universe_domain=mock_universe)
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ else:
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == (
+ mock_endpoint if universe_exists else default_endpoint
+ )
+ assert client.universe_domain == (
+ mock_universe if universe_exists else default_universe
+ )
+
+ # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ options = client_options.ClientOptions()
+ if hasattr(options, "universe_domain"):
+ delattr(options, "universe_domain")
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == default_endpoint
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (UserStoreServiceClient, transports.UserStoreServiceGrpcTransport, "grpc"),
+ (
+ UserStoreServiceAsyncClient,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (UserStoreServiceClient, transports.UserStoreServiceRestTransport, "rest"),
+ ],
+)
+def test_user_store_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(
+ scopes=["1", "2"],
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ UserStoreServiceClient,
+ transports.UserStoreServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ UserStoreServiceAsyncClient,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ (
+ UserStoreServiceClient,
+ transports.UserStoreServiceRestTransport,
+ "rest",
+ None,
+ ),
+ ],
+)
+def test_user_store_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+def test_user_store_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.user_store_service.transports.UserStoreServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = UserStoreServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ UserStoreServiceClient,
+ transports.UserStoreServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ UserStoreServiceAsyncClient,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ ],
+)
+def test_user_store_service_client_create_channel_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # test that the credentials from file are saved and used as the credentials.
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(grpc_helpers, "create_channel") as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ file_creds = ga_credentials.AnonymousCredentials()
+ load_creds.return_value = (file_creds, None)
+ adc.return_value = (creds, None)
+ client = client_class(client_options=options, transport=transport_name)
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=file_creds,
+ credentials_file=None,
+ quota_project_id=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=None,
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ user_store_service.GetUserStoreRequest(),
+ {},
+ ],
+)
+def test_get_user_store(request_type, transport: str = "grpc"):
+ client = UserStoreServiceClient(
+ 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_user_store), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = user_store.UserStore(
+ name="name_value",
+ display_name="display_name_value",
+ default_license_config="default_license_config_value",
+ enable_license_auto_register=True,
+ enable_expired_license_auto_update=True,
+ )
+ response = client.get_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = user_store_service.GetUserStoreRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, user_store.UserStore)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.default_license_config == "default_license_config_value"
+ assert response.enable_license_auto_register is True
+ assert response.enable_expired_license_auto_update is True
+
+
+def test_get_user_store_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 = UserStoreServiceClient(
+ 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 = user_store_service.GetUserStoreRequest(
+ name="name_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_user_store), "__call__") as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_user_store(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_store_service.GetUserStoreRequest(
+ name="name_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_user_store_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = UserStoreServiceClient(
+ 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_user_store in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_user_store] = mock_rpc
+ request = {}
+ client.get_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_user_store(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_user_store_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 = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_user_store
+ 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_user_store
+ ] = mock_rpc
+
+ request = {}
+ await client.get_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_user_store(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",
+ [
+ user_store_service.GetUserStoreRequest(),
+ {},
+ ],
+)
+async def test_get_user_store_async(request_type, transport: str = "grpc_asyncio"):
+ client = UserStoreServiceAsyncClient(
+ 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_user_store), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ user_store.UserStore(
+ name="name_value",
+ display_name="display_name_value",
+ default_license_config="default_license_config_value",
+ enable_license_auto_register=True,
+ enable_expired_license_auto_update=True,
+ )
+ )
+ response = await client.get_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = user_store_service.GetUserStoreRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, user_store.UserStore)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.default_license_config == "default_license_config_value"
+ assert response.enable_license_auto_register is True
+ assert response.enable_expired_license_auto_update is True
+
+
+def test_get_user_store_field_headers():
+ client = UserStoreServiceClient(
+ 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 = user_store_service.GetUserStoreRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_user_store), "__call__") as call:
+ call.return_value = user_store.UserStore()
+ client.get_user_store(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_user_store_field_headers_async():
+ client = UserStoreServiceAsyncClient(
+ 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 = user_store_service.GetUserStoreRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_user_store), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ user_store.UserStore()
+ )
+ await client.get_user_store(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_user_store_flattened():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_user_store), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = user_store.UserStore()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_user_store(
+ 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_user_store_flattened_error():
+ client = UserStoreServiceClient(
+ 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_user_store(
+ user_store_service.GetUserStoreRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_user_store_flattened_async():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_user_store), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = user_store.UserStore()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ user_store.UserStore()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_user_store(
+ 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_user_store_flattened_error_async():
+ client = UserStoreServiceAsyncClient(
+ 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_user_store(
+ user_store_service.GetUserStoreRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ user_store_service.UpdateUserStoreRequest(),
+ {},
+ ],
+)
+def test_update_user_store(request_type, transport: str = "grpc"):
+ client = UserStoreServiceClient(
+ 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_user_store), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_user_store.UserStore(
+ name="name_value",
+ display_name="display_name_value",
+ default_license_config="default_license_config_value",
+ enable_license_auto_register=True,
+ enable_expired_license_auto_update=True,
+ )
+ response = client.update_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = user_store_service.UpdateUserStoreRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_user_store.UserStore)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.default_license_config == "default_license_config_value"
+ assert response.enable_license_auto_register is True
+ assert response.enable_expired_license_auto_update is True
+
+
+def test_update_user_store_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 = UserStoreServiceClient(
+ 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 = user_store_service.UpdateUserStoreRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_user_store), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_user_store(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_store_service.UpdateUserStoreRequest()
+ assert args[0] == request_msg
+
+
+def test_update_user_store_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = UserStoreServiceClient(
+ 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.update_user_store in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_user_store] = (
+ mock_rpc
+ )
+ request = {}
+ client.update_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_user_store(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_update_user_store_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 = UserStoreServiceAsyncClient(
+ 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.update_user_store
+ 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.update_user_store
+ ] = mock_rpc
+
+ request = {}
+ await client.update_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_user_store(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",
+ [
+ user_store_service.UpdateUserStoreRequest(),
+ {},
+ ],
+)
+async def test_update_user_store_async(request_type, transport: str = "grpc_asyncio"):
+ client = UserStoreServiceAsyncClient(
+ 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.update_user_store), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_user_store.UserStore(
+ name="name_value",
+ display_name="display_name_value",
+ default_license_config="default_license_config_value",
+ enable_license_auto_register=True,
+ enable_expired_license_auto_update=True,
+ )
+ )
+ response = await client.update_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = user_store_service.UpdateUserStoreRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_user_store.UserStore)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.default_license_config == "default_license_config_value"
+ assert response.enable_license_auto_register is True
+ assert response.enable_expired_license_auto_update is True
+
+
+def test_update_user_store_field_headers():
+ client = UserStoreServiceClient(
+ 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 = user_store_service.UpdateUserStoreRequest()
+
+ request.user_store.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_user_store), "__call__"
+ ) as call:
+ call.return_value = gcd_user_store.UserStore()
+ client.update_user_store(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",
+ "user_store.name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_user_store_field_headers_async():
+ client = UserStoreServiceAsyncClient(
+ 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 = user_store_service.UpdateUserStoreRequest()
+
+ request.user_store.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_user_store), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_user_store.UserStore()
+ )
+ await client.update_user_store(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",
+ "user_store.name=name_value",
+ ) in kw["metadata"]
+
+
+def test_update_user_store_flattened():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_user_store), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_user_store.UserStore()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_user_store(
+ user_store=gcd_user_store.UserStore(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].user_store
+ mock_val = gcd_user_store.UserStore(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+def test_update_user_store_flattened_error():
+ client = UserStoreServiceClient(
+ 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_user_store(
+ user_store_service.UpdateUserStoreRequest(),
+ user_store=gcd_user_store.UserStore(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_user_store_flattened_async():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_user_store), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_user_store.UserStore()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_user_store.UserStore()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_user_store(
+ user_store=gcd_user_store.UserStore(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].user_store
+ mock_val = gcd_user_store.UserStore(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_update_user_store_flattened_error_async():
+ client = UserStoreServiceAsyncClient(
+ 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_user_store(
+ user_store_service.UpdateUserStoreRequest(),
+ user_store=gcd_user_store.UserStore(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_get_user_store_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = UserStoreServiceClient(
+ 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_user_store in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_user_store] = mock_rpc
+
+ request = {}
+ client.get_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_user_store(request)
+
+ # Establish 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_user_store_rest_required_fields(
+ request_type=user_store_service.GetUserStoreRequest,
+):
+ transport_class = transports.UserStoreServiceRestTransport
+
+ 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._BaseGetUserStore,
+ "_BaseGetUserStore__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 = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = user_store.UserStore()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = user_store.UserStore.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_user_store(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_user_store_rest_flattened():
+ client = UserStoreServiceClient(
+ 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 = user_store.UserStore()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/userStores/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 = user_store.UserStore.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_user_store(**mock_args)
+
+ # Establish that the underlying call 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/*/userStores/*}" % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_user_store_rest_flattened_error(transport: str = "rest"):
+ client = UserStoreServiceClient(
+ 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_user_store(
+ user_store_service.GetUserStoreRequest(),
+ name="name_value",
+ )
+
+
+def test_update_user_store_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = UserStoreServiceClient(
+ 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_user_store in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_user_store] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.update_user_store(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_user_store(request)
+
+ # Establish 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_user_store_rest_required_fields(
+ request_type=user_store_service.UpdateUserStoreRequest,
+):
+ transport_class = transports.UserStoreServiceRestTransport
+
+ 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._BaseUpdateUserStore,
+ "_BaseUpdateUserStore__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(("updateMask",))
+
+ # verify required fields with non-default values are left alone
+
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_user_store.UserStore()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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
+
+ # Convert return value to protobuf type
+ return_value = gcd_user_store.UserStore.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_user_store(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_user_store_rest_flattened():
+ client = UserStoreServiceClient(
+ 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 = gcd_user_store.UserStore()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "user_store": {
+ "name": "projects/sample1/locations/sample2/userStores/sample3"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ user_store=gcd_user_store.UserStore(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
+ # Convert return value to protobuf type
+ return_value = gcd_user_store.UserStore.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_user_store(**mock_args)
+
+ # Establish that the underlying call 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/{user_store.name=projects/*/locations/*/userStores/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_update_user_store_rest_flattened_error(transport: str = "rest"):
+ client = UserStoreServiceClient(
+ 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_user_store(
+ user_store_service.UpdateUserStoreRequest(),
+ user_store=gcd_user_store.UserStore(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.UserStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.UserStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = UserStoreServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.UserStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = UserStoreServiceClient(
+ 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 = UserStoreServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.UserStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = UserStoreServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.UserStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = UserStoreServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.UserStoreServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.UserStoreServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.UserStoreServiceGrpcTransport,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ transports.UserStoreServiceRestTransport,
+ ],
+)
+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 = UserStoreServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = UserStoreServiceClient(
+ 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_get_user_store_empty_call_grpc():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_user_store), "__call__") as call:
+ call.return_value = user_store.UserStore()
+ client.get_user_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_store_service.GetUserStoreRequest()
+ assert args[0] == request_msg
+
+
+# This 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_user_store_empty_call_grpc():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_user_store), "__call__"
+ ) as call:
+ call.return_value = gcd_user_store.UserStore()
+ client.update_user_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_store_service.UpdateUserStoreRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = UserStoreServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = UserStoreServiceAsyncClient(
+ 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_get_user_store_empty_call_grpc_asyncio():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_user_store), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ user_store.UserStore(
+ name="name_value",
+ display_name="display_name_value",
+ default_license_config="default_license_config_value",
+ enable_license_auto_register=True,
+ enable_expired_license_auto_update=True,
+ )
+ )
+ await client.get_user_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_store_service.GetUserStoreRequest()
+ assert args[0] == request_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_user_store_empty_call_grpc_asyncio():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_user_store), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_user_store.UserStore(
+ name="name_value",
+ display_name="display_name_value",
+ default_license_config="default_license_config_value",
+ enable_license_auto_register=True,
+ enable_expired_license_auto_update=True,
+ )
+ )
+ await client.update_user_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_store_service.UpdateUserStoreRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = UserStoreServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_get_user_store_rest_bad_request(
+ request_type=user_store_service.GetUserStoreRequest,
+):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/userStores/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_user_store(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ user_store_service.GetUserStoreRequest,
+ dict,
+ ],
+)
+def test_get_user_store_rest_call_success(request_type):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {"name": "projects/sample1/locations/sample2/userStores/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 = user_store.UserStore(
+ name="name_value",
+ display_name="display_name_value",
+ default_license_config="default_license_config_value",
+ enable_license_auto_register=True,
+ enable_expired_license_auto_update=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 = user_store.UserStore.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_user_store(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, user_store.UserStore)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.default_license_config == "default_license_config_value"
+ assert response.enable_license_auto_register is True
+ assert response.enable_expired_license_auto_update is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_user_store_rest_interceptors(null_interceptor):
+ transport = transports.UserStoreServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.UserStoreServiceRestInterceptor(),
+ )
+ client = UserStoreServiceClient(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.UserStoreServiceRestInterceptor, "post_get_user_store"
+ ) as post,
+ mock.patch.object(
+ transports.UserStoreServiceRestInterceptor,
+ "post_get_user_store_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.UserStoreServiceRestInterceptor, "pre_get_user_store"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = user_store_service.GetUserStoreRequest.pb(
+ user_store_service.GetUserStoreRequest()
+ )
+ 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 = user_store.UserStore.to_json(user_store.UserStore())
+ req.return_value.content = return_value
+
+ request = user_store_service.GetUserStoreRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = user_store.UserStore()
+ post_with_metadata.return_value = user_store.UserStore(), metadata
+
+ client.get_user_store(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_update_user_store_rest_bad_request(
+ request_type=user_store_service.UpdateUserStoreRequest,
+):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "user_store": {"name": "projects/sample1/locations/sample2/userStores/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_user_store(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ user_store_service.UpdateUserStoreRequest,
+ dict,
+ ],
+)
+def test_update_user_store_rest_call_success(request_type):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "user_store": {"name": "projects/sample1/locations/sample2/userStores/sample3"}
+ }
+ request_init["user_store"] = {
+ "name": "projects/sample1/locations/sample2/userStores/sample3",
+ "display_name": "display_name_value",
+ "default_license_config": "default_license_config_value",
+ "enable_license_auto_register": True,
+ "enable_expired_license_auto_update": 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 = user_store_service.UpdateUserStoreRequest.meta.fields["user_store"]
+
+ 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["user_store"].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["user_store"][field])):
+ del request_init["user_store"][field][i][subfield]
+ else:
+ del request_init["user_store"][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 = gcd_user_store.UserStore(
+ name="name_value",
+ display_name="display_name_value",
+ default_license_config="default_license_config_value",
+ enable_license_auto_register=True,
+ enable_expired_license_auto_update=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 = gcd_user_store.UserStore.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_user_store(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_user_store.UserStore)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert response.default_license_config == "default_license_config_value"
+ assert response.enable_license_auto_register is True
+ assert response.enable_expired_license_auto_update is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_user_store_rest_interceptors(null_interceptor):
+ transport = transports.UserStoreServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.UserStoreServiceRestInterceptor(),
+ )
+ client = UserStoreServiceClient(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.UserStoreServiceRestInterceptor, "post_update_user_store"
+ ) as post,
+ mock.patch.object(
+ transports.UserStoreServiceRestInterceptor,
+ "post_update_user_store_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.UserStoreServiceRestInterceptor, "pre_update_user_store"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = user_store_service.UpdateUserStoreRequest.pb(
+ user_store_service.UpdateUserStoreRequest()
+ )
+ 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 = gcd_user_store.UserStore.to_json(gcd_user_store.UserStore())
+ req.return_value.content = return_value
+
+ request = user_store_service.UpdateUserStoreRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcd_user_store.UserStore()
+ post_with_metadata.return_value = gcd_user_store.UserStore(), metadata
+
+ client.update_user_store(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_cancel_operation_rest_bad_request(
+ request_type=operations_pb2.CancelOperationRequest,
+):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = "{}"
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.cancel_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_get_operation_rest_bad_request(
+ request_type=operations_pb2.GetOperationRequest,
+):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.get_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_list_operations_rest_bad_request(
+ request_type=operations_pb2.ListOperationsRequest,
+):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.list_operations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_initialize_client_w_rest():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_user_store_empty_call_rest():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(type(client.transport.get_user_store), "__call__") as call:
+ client.get_user_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_store_service.GetUserStoreRequest()
+ assert args[0] == request_msg
+
+
+# This 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_user_store_empty_call_rest():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_user_store), "__call__"
+ ) as call:
+ client.update_user_store(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = user_store_service.UpdateUserStoreRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert isinstance(
+ client.transport,
+ transports.UserStoreServiceGrpcTransport,
+ )
+
+
+def test_user_store_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
+ transport = transports.UserStoreServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_user_store_service_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.user_store_service.transports.UserStoreServiceTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.UserStoreServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "get_user_store",
+ "update_user_store",
+ "get_operation",
+ "cancel_operation",
+ "list_operations",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ with pytest.raises(NotImplementedError):
+ transport.close()
+
+ # Catch all for all remaining methods and properties
+ remainder = [
+ "kind",
+ ]
+ for r in remainder:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, r)()
+
+
+def test_user_store_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.user_store_service.transports.UserStoreServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.UserStoreServiceTransport(
+ credentials_file="credentials.json",
+ quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_user_store_service_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.user_store_service.transports.UserStoreServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.UserStoreServiceTransport()
+ adc.assert_called_once()
+
+
+def test_user_store_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ UserStoreServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.UserStoreServiceGrpcTransport,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_user_store_service_transport_auth_adc(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.UserStoreServiceGrpcTransport,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ transports.UserStoreServiceRestTransport,
+ ],
+)
+def test_user_store_service_transport_auth_gdch_credentials(transport_class):
+ host = "https://language.com"
+ api_audience_tests = [None, "https://language2.com"]
+ api_audience_expect = [host, "https://language2.com"]
+ for t, e in zip(api_audience_tests, api_audience_expect):
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ gdch_mock = mock.MagicMock()
+ type(gdch_mock).with_gdch_audience = mock.PropertyMock(
+ return_value=gdch_mock
+ )
+ adc.return_value = (gdch_mock, None)
+ transport_class(host=host, api_audience=t)
+ gdch_mock.with_gdch_audience.assert_called_once_with(e)
+
+
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.UserStoreServiceGrpcTransport, grpc_helpers),
+ (transports.UserStoreServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_user_store_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=["1", "2"],
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.UserStoreServiceGrpcTransport,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_user_store_service_grpc_transport_client_cert_source_for_mtls(transport_class):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_user_store_service_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.UserStoreServiceRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_user_store_service_host_no_port(transport_name):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_user_store_service_host_with_port(transport_name):
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com:8000"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:8000"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com:8000"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "rest",
+ ],
+)
+def test_user_store_service_client_transport_session_collision(transport_name):
+ creds1 = ga_credentials.AnonymousCredentials()
+ creds2 = ga_credentials.AnonymousCredentials()
+ client1 = UserStoreServiceClient(
+ credentials=creds1,
+ transport=transport_name,
+ )
+ client2 = UserStoreServiceClient(
+ credentials=creds2,
+ transport=transport_name,
+ )
+ session1 = client1.transport.get_user_store._session
+ session2 = client2.transport.get_user_store._session
+ assert session1 != session2
+ session1 = client1.transport.update_user_store._session
+ session2 = client2.transport.update_user_store._session
+ assert session1 != session2
+
+
+def test_user_store_service_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.UserStoreServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_user_store_service_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.UserStoreServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.filterwarnings("ignore::FutureWarning")
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.UserStoreServiceGrpcTransport,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_user_store_service_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = ga_credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.UserStoreServiceGrpcTransport,
+ transports.UserStoreServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_user_store_service_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_license_config_path():
+ project = "squid"
+ location = "clam"
+ license_config = "whelk"
+ expected = "projects/{project}/locations/{location}/licenseConfigs/{license_config}".format(
+ project=project,
+ location=location,
+ license_config=license_config,
+ )
+ actual = UserStoreServiceClient.license_config_path(
+ project, location, license_config
+ )
+ assert expected == actual
+
+
+def test_parse_license_config_path():
+ expected = {
+ "project": "octopus",
+ "location": "oyster",
+ "license_config": "nudibranch",
+ }
+ path = UserStoreServiceClient.license_config_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = UserStoreServiceClient.parse_license_config_path(path)
+ assert expected == actual
+
+
+def test_user_store_path():
+ project = "cuttlefish"
+ location = "mussel"
+ user_store = "winkle"
+ expected = "projects/{project}/locations/{location}/userStores/{user_store}".format(
+ project=project,
+ location=location,
+ user_store=user_store,
+ )
+ actual = UserStoreServiceClient.user_store_path(project, location, user_store)
+ assert expected == actual
+
+
+def test_parse_user_store_path():
+ expected = {
+ "project": "nautilus",
+ "location": "scallop",
+ "user_store": "abalone",
+ }
+ path = UserStoreServiceClient.user_store_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = UserStoreServiceClient.parse_user_store_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "squid"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = UserStoreServiceClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "clam",
+ }
+ path = UserStoreServiceClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = UserStoreServiceClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "whelk"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = UserStoreServiceClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "octopus",
+ }
+ path = UserStoreServiceClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = UserStoreServiceClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "oyster"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = UserStoreServiceClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "nudibranch",
+ }
+ path = UserStoreServiceClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = UserStoreServiceClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "cuttlefish"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = UserStoreServiceClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "mussel",
+ }
+ path = UserStoreServiceClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = UserStoreServiceClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "winkle"
+ location = "nautilus"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = UserStoreServiceClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "scallop",
+ "location": "abalone",
+ }
+ path = UserStoreServiceClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = UserStoreServiceClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.UserStoreServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.UserStoreServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = UserStoreServiceClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+def test_cancel_operation(transport: str = "grpc"):
+ client = UserStoreServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
+ client = UserStoreServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+def test_cancel_operation_field_headers():
+ client = UserStoreServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = None
+
+ client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_field_headers_async():
+ client = UserStoreServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_cancel_operation_from_dict():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_from_dict_async():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_cancel_operation_flattened():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_flattened_async():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+def test_get_operation(transport: str = "grpc"):
+ client = UserStoreServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+@pytest.mark.asyncio
+async def test_get_operation_async(transport: str = "grpc_asyncio"):
+ client = UserStoreServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_get_operation_field_headers():
+ client = UserStoreServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_operation_field_headers_async():
+ client = UserStoreServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_get_operation_from_dict():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ response = client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_from_dict_async():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_get_operation_flattened():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_flattened_async():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+def test_list_operations(transport: str = "grpc"):
+ client = UserStoreServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+ response = client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+@pytest.mark.asyncio
+async def test_list_operations_async(transport: str = "grpc_asyncio"):
+ client = UserStoreServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_list_operations_field_headers():
+ client = UserStoreServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_operations_field_headers_async():
+ client = UserStoreServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+def test_list_operations_from_dict():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ response = client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_from_dict_async():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_list_operations_flattened():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_flattened_async():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+def test_transport_close_grpc():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+@pytest.mark.asyncio
+async def test_transport_close_grpc_asyncio():
+ client = UserStoreServiceAsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_transport_close_rest():
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_session")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_client_ctx():
+ transports = [
+ "rest",
+ "grpc",
+ ]
+ for transport in transports:
+ client = UserStoreServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ # Test client calls underlying transport.
+ with mock.patch.object(type(client.transport), "close") as close:
+ close.assert_not_called()
+ with client:
+ pass
+ close.assert_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class",
+ [
+ (UserStoreServiceClient, transports.UserStoreServiceGrpcTransport),
+ (UserStoreServiceAsyncClient, transports.UserStoreServiceGrpcAsyncIOTransport),
+ ],
+)
+def test_api_key_credentials(client_class, transport_class):
+ with mock.patch.object(
+ google.auth._default, "get_api_key_credentials", create=True
+ ) as get_api_key_credentials:
+ mock_cred = mock.Mock()
+ get_api_key_credentials.return_value = mock_cred
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=mock_cred,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
diff --git a/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_widget_config_service.py b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_widget_config_service.py
new file mode 100644
index 000000000000..e83bd4aeb6e9
--- /dev/null
+++ b/packages/google-cloud-discoveryengine/tests/unit/gapic/discoveryengine_v1/test_widget_config_service.py
@@ -0,0 +1,4532 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import asyncio
+import json
+import math
+import os
+from collections.abc import AsyncIterable, Iterable, Mapping, Sequence
+from unittest import mock
+from unittest.mock import AsyncMock
+
+import grpc
+import pytest
+from google.api_core import api_core_version
+from google.protobuf import json_format
+from grpc.experimental import aio
+from proto.marshal.rules import wrappers
+from proto.marshal.rules.dates import DurationRule, TimestampRule
+from requests import PreparedRequest, Request, Response
+from requests.sessions import Session
+
+try:
+ from google.auth.aio import credentials as ga_credentials_async
+
+ HAS_GOOGLE_AUTH_AIO = True
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_AUTH_AIO = False
+
+import google.auth
+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
+from google.api_core import (
+ client_options,
+ gapic_v1,
+ grpc_helpers,
+ grpc_helpers_async,
+ path_template,
+)
+from google.api_core import exceptions as core_exceptions
+from google.api_core import retry as retries
+from google.auth import credentials as ga_credentials
+from google.auth.exceptions import MutualTLSChannelError
+from google.cloud.location import locations_pb2
+from google.longrunning import operations_pb2 # type: ignore
+from google.oauth2 import service_account
+
+from google.cloud.discoveryengine_v1.services.widget_config_service import (
+ WidgetConfigServiceAsyncClient,
+ WidgetConfigServiceClient,
+ transports,
+)
+from google.cloud.discoveryengine_v1.types import (
+ common,
+ data_connector,
+ widget_config,
+ widget_config_service,
+)
+from google.cloud.discoveryengine_v1.types import widget_config as gcd_widget_config
+
+CRED_INFO_JSON = {
+ "credential_source": "/path/to/file",
+ "credential_type": "service account credentials",
+ "principal": "service-account@example.com",
+}
+CRED_INFO_STRING = json.dumps(CRED_INFO_JSON)
+
+
+@pytest.fixture(autouse=True)
+def disable_mtls_env():
+ with mock.patch.dict(
+ os.environ,
+ {
+ "GOOGLE_API_USE_CLIENT_CERTIFICATE": "false",
+ "CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE": "false",
+ },
+ ):
+ yield
+
+
+async def mock_async_gen(data, chunk_size=1):
+ for i in range(0, len(data)): # pragma: NO COVER
+ chunk = data[i : i + chunk_size]
+ yield chunk.encode("utf-8")
+
+
+def client_cert_source_callback():
+ return b"cert bytes", b"key bytes"
+
+
+# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded.
+# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107.
+def async_anonymous_credentials():
+ if HAS_GOOGLE_AUTH_AIO:
+ return ga_credentials_async.AnonymousCredentials()
+ return ga_credentials.AnonymousCredentials()
+
+
+# If default endpoint is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint(client):
+ return (
+ "foo.googleapis.com"
+ if ("localhost" in client.DEFAULT_ENDPOINT)
+ else client.DEFAULT_ENDPOINT
+ )
+
+
+# If default endpoint template is localhost, then default mtls endpoint will be the same.
+# This method modifies the default endpoint template so the client can produce a different
+# mtls endpoint for endpoint testing purposes.
+def modify_default_endpoint_template(client):
+ return (
+ "test.{UNIVERSE_DOMAIN}"
+ if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE)
+ else client._DEFAULT_ENDPOINT_TEMPLATE
+ )
+
+
+@pytest.fixture(autouse=True)
+def set_event_loop():
+ try:
+ asyncio.get_running_loop()
+ yield
+ except RuntimeError:
+ loop = asyncio.new_event_loop()
+ asyncio.set_event_loop(loop)
+ try:
+ yield
+ finally:
+ loop.close()
+ asyncio.set_event_loop(None)
+
+
+def test__get_client_cert_source():
+ mock_provided_cert_source = mock.Mock()
+ mock_default_cert_source = mock.Mock()
+
+ assert WidgetConfigServiceClient._get_client_cert_source(None, False) is None
+ assert (
+ WidgetConfigServiceClient._get_client_cert_source(
+ mock_provided_cert_source, False
+ )
+ is None
+ )
+ assert (
+ WidgetConfigServiceClient._get_client_cert_source(
+ mock_provided_cert_source, True
+ )
+ == mock_provided_cert_source
+ )
+
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source", return_value=True
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_default_cert_source,
+ ):
+ assert (
+ WidgetConfigServiceClient._get_client_cert_source(None, True)
+ is mock_default_cert_source
+ )
+ assert (
+ WidgetConfigServiceClient._get_client_cert_source(
+ mock_provided_cert_source, "true"
+ )
+ is mock_provided_cert_source
+ )
+
+
+@pytest.mark.parametrize(
+ "error_code,cred_info_json,show_cred_info",
+ [
+ (401, CRED_INFO_JSON, True),
+ (403, CRED_INFO_JSON, True),
+ (404, CRED_INFO_JSON, True),
+ (500, CRED_INFO_JSON, False),
+ (401, None, False),
+ (403, None, False),
+ (404, None, False),
+ (500, None, False),
+ ],
+)
+def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info):
+ cred = mock.Mock(["get_cred_info"])
+ cred.get_cred_info = mock.Mock(return_value=cred_info_json)
+ client = WidgetConfigServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=["foo"])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ if show_cred_info:
+ assert error.details == ["foo", CRED_INFO_STRING]
+ else:
+ assert error.details == ["foo"]
+
+
+@pytest.mark.parametrize("error_code", [401, 403, 404, 500])
+def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code):
+ cred = mock.Mock([])
+ assert not hasattr(cred, "get_cred_info")
+ client = WidgetConfigServiceClient(credentials=cred)
+ client._transport._credentials = cred
+
+ error = core_exceptions.GoogleAPICallError("message", details=[])
+ error.code = error_code
+
+ client._add_cred_info_for_auth_errors(error)
+ assert error.details == []
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (WidgetConfigServiceClient, "grpc"),
+ (WidgetConfigServiceAsyncClient, "grpc_asyncio"),
+ (WidgetConfigServiceClient, "rest"),
+ ],
+)
+def test_widget_config_service_client_from_service_account_info(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_info"
+ ) as factory:
+ factory.return_value = creds
+ info = {"valid": True}
+ client = client_class.from_service_account_info(info, transport=transport_name)
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class,transport_name",
+ [
+ (transports.WidgetConfigServiceGrpcTransport, "grpc"),
+ (transports.WidgetConfigServiceGrpcAsyncIOTransport, "grpc_asyncio"),
+ (transports.WidgetConfigServiceRestTransport, "rest"),
+ ],
+)
+def test_widget_config_service_client_service_account_always_use_jwt(
+ transport_class, transport_name
+):
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=True)
+ use_jwt.assert_called_once_with(True)
+
+ with mock.patch.object(
+ service_account.Credentials, "with_always_use_jwt_access", create=True
+ ) as use_jwt:
+ creds = service_account.Credentials(None, None, None)
+ transport = transport_class(credentials=creds, always_use_jwt_access=False)
+ use_jwt.assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_name",
+ [
+ (WidgetConfigServiceClient, "grpc"),
+ (WidgetConfigServiceAsyncClient, "grpc_asyncio"),
+ (WidgetConfigServiceClient, "rest"),
+ ],
+)
+def test_widget_config_service_client_from_service_account_file(
+ client_class, transport_name
+):
+ creds = ga_credentials.AnonymousCredentials()
+ with mock.patch.object(
+ service_account.Credentials, "from_service_account_file"
+ ) as factory:
+ factory.return_value = creds
+ client = client_class.from_service_account_file(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ client = client_class.from_service_account_json(
+ "dummy/file/path.json", transport=transport_name
+ )
+ assert client.transport._credentials == creds
+ assert isinstance(client, client_class)
+
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+def test_widget_config_service_client_get_transport_class():
+ transport = WidgetConfigServiceClient.get_transport_class()
+ available_transports = [
+ transports.WidgetConfigServiceGrpcTransport,
+ transports.WidgetConfigServiceRestTransport,
+ ]
+ assert transport in available_transports
+
+ transport = WidgetConfigServiceClient.get_transport_class("grpc")
+ assert transport == transports.WidgetConfigServiceGrpcTransport
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ WidgetConfigServiceAsyncClient,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceRestTransport,
+ "rest",
+ ),
+ ],
+)
+@mock.patch.object(
+ WidgetConfigServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(WidgetConfigServiceClient),
+)
+@mock.patch.object(
+ WidgetConfigServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(WidgetConfigServiceAsyncClient),
+)
+def test_widget_config_service_client_client_options(
+ client_class, transport_class, transport_name
+):
+ # Check that if channel is provided we won't create a new one.
+ with mock.patch.object(WidgetConfigServiceClient, "get_transport_class") as gtc:
+ transport = transport_class(credentials=ga_credentials.AnonymousCredentials())
+ client = client_class(transport=transport)
+ gtc.assert_not_called()
+
+ # Check that if channel is provided via str we will create a new one.
+ with mock.patch.object(WidgetConfigServiceClient, "get_transport_class") as gtc:
+ client = client_class(transport=transport_name)
+ gtc.assert_called()
+
+ # Check the case api_endpoint is provided.
+ options = client_options.ClientOptions(api_endpoint="squid.clam.whelk")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name, client_options=options)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is
+ # "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client.DEFAULT_MTLS_ENDPOINT,
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client = client_class(transport=transport_name)
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+ # Check the case quota_project_id is provided
+ options = client_options.ClientOptions(quota_project_id="octopus")
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id="octopus",
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+ # Check the case api_endpoint is provided
+ options = client_options.ClientOptions(
+ api_audience="https://language.googleapis.com"
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience="https://language.googleapis.com",
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,use_client_cert_env",
+ [
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceGrpcTransport,
+ "grpc",
+ "true",
+ ),
+ (
+ WidgetConfigServiceAsyncClient,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "true",
+ ),
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceGrpcTransport,
+ "grpc",
+ "false",
+ ),
+ (
+ WidgetConfigServiceAsyncClient,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ "false",
+ ),
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceRestTransport,
+ "rest",
+ "true",
+ ),
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceRestTransport,
+ "rest",
+ "false",
+ ),
+ ],
+)
+@mock.patch.object(
+ WidgetConfigServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(WidgetConfigServiceClient),
+)
+@mock.patch.object(
+ WidgetConfigServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(WidgetConfigServiceAsyncClient),
+)
+@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"})
+def test_widget_config_service_client_mtls_env_auto(
+ client_class, transport_class, transport_name, use_client_cert_env
+):
+ # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default
+ # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists.
+
+ # Check the case client_cert_source is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=client_cert_source_callback
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+
+ if use_client_cert_env == "false":
+ expected_client_cert_source = None
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ else:
+ expected_client_cert_source = client_cert_source_callback
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case ADC client cert is provided. Whether client cert is used depends on
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE value.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=client_cert_source_callback,
+ ):
+ if use_client_cert_env == "false":
+ expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ )
+ expected_client_cert_source = None
+ else:
+ expected_host = client.DEFAULT_MTLS_ENDPOINT
+ expected_client_cert_source = client_cert_source_callback
+
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=expected_host,
+ scopes=None,
+ client_cert_source_for_mtls=expected_client_cert_source,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # Check the case client_cert_source and ADC client cert are not provided.
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env}
+ ):
+ with mock.patch.object(transport_class, "__init__") as patched:
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ patched.return_value = None
+ client = client_class(transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [WidgetConfigServiceClient, WidgetConfigServiceAsyncClient]
+)
+@mock.patch.object(
+ WidgetConfigServiceClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(WidgetConfigServiceClient),
+)
+@mock.patch.object(
+ WidgetConfigServiceAsyncClient,
+ "DEFAULT_ENDPOINT",
+ modify_default_endpoint(WidgetConfigServiceAsyncClient),
+)
+def test_widget_config_service_client_get_mtls_endpoint_and_cert_source(client_class):
+ mock_client_cert_source = mock.Mock()
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source == mock_client_cert_source
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "Unsupported".
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"}
+ ):
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ mock_client_cert_source = mock.Mock()
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source(
+ options
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is None
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset.
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None)
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", None)
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty).
+ test_cases = [
+ (
+ # With workloads present in config, mTLS is enabled.
+ {
+ "version": 1,
+ "cert_configs": {
+ "workload": {
+ "cert_path": "path/to/cert/file",
+ "key_path": "path/to/key/file",
+ }
+ },
+ },
+ mock_client_cert_source,
+ ),
+ (
+ # With workloads not present in config, mTLS is disabled.
+ {
+ "version": 1,
+ "cert_configs": {},
+ },
+ None,
+ ),
+ ]
+ if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
+ for config_data, expected_cert_source in test_cases:
+ env = os.environ.copy()
+ env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "")
+ env.pop("CLOUDSDK_CONTEXT_AWARE_USE_CLIENT_CERTIFICATE", "")
+ with mock.patch.dict(os.environ, env, clear=True):
+ config_filename = "mock_certificate_config.json"
+ config_file_content = json.dumps(config_data)
+ m = mock.mock_open(read_data=config_file_content)
+ with (
+ mock.patch("builtins.open", m),
+ mock.patch(
+ "os.path.exists",
+ side_effect=lambda path: os.path.basename(path)
+ == config_filename,
+ ),
+ ):
+ with mock.patch.dict(
+ os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename}
+ ):
+ mock_api_endpoint = "foo"
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source,
+ api_endpoint=mock_api_endpoint,
+ )
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source(options)
+ )
+ assert api_endpoint == mock_api_endpoint
+ assert cert_source is expected_cert_source
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always".
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=False,
+ ):
+ api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source()
+ assert api_endpoint == client_class.DEFAULT_ENDPOINT
+ assert cert_source is None
+
+ # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.mtls.has_default_client_cert_source",
+ return_value=True,
+ ):
+ with mock.patch(
+ "google.auth.transport.mtls.default_client_cert_source",
+ return_value=mock_client_cert_source,
+ ):
+ api_endpoint, cert_source = (
+ client_class.get_mtls_endpoint_and_cert_source()
+ )
+ assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+ assert cert_source == mock_client_cert_source
+
+ # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has
+ # unsupported value.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}):
+ with pytest.raises(MutualTLSChannelError) as excinfo:
+ client_class.get_mtls_endpoint_and_cert_source()
+
+ assert (
+ str(excinfo.value)
+ == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class", [WidgetConfigServiceClient, WidgetConfigServiceAsyncClient]
+)
+@mock.patch.object(
+ WidgetConfigServiceClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(WidgetConfigServiceClient),
+)
+@mock.patch.object(
+ WidgetConfigServiceAsyncClient,
+ "_DEFAULT_ENDPOINT_TEMPLATE",
+ modify_default_endpoint_template(WidgetConfigServiceAsyncClient),
+)
+def test_widget_config_service_client_client_api_endpoint(client_class):
+ mock_client_cert_source = client_cert_source_callback
+ api_override = "foo.com"
+ default_universe = WidgetConfigServiceClient._DEFAULT_UNIVERSE
+ default_endpoint = WidgetConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=default_universe
+ )
+ mock_universe = "bar.com"
+ mock_endpoint = WidgetConfigServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=mock_universe
+ )
+
+ # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true",
+ # use ClientOptions.api_endpoint as the api endpoint regardless.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}):
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ):
+ options = client_options.ClientOptions(
+ client_cert_source=mock_client_cert_source, api_endpoint=api_override
+ )
+ client = client_class(
+ client_options=options,
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert client.api_endpoint == api_override
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == default_endpoint
+
+ # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always",
+ # use the DEFAULT_MTLS_ENDPOINT as the api endpoint.
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}):
+ client = client_class(credentials=ga_credentials.AnonymousCredentials())
+ assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT
+
+ # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default),
+ # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist,
+ # and ClientOptions.universe_domain="bar.com",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint.
+ options = client_options.ClientOptions()
+ universe_exists = hasattr(options, "universe_domain")
+ if universe_exists:
+ options = client_options.ClientOptions(universe_domain=mock_universe)
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ else:
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == (
+ mock_endpoint if universe_exists else default_endpoint
+ )
+ assert client.universe_domain == (
+ mock_universe if universe_exists else default_universe
+ )
+
+ # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never",
+ # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint.
+ options = client_options.ClientOptions()
+ if hasattr(options, "universe_domain"):
+ delattr(options, "universe_domain")
+ with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}):
+ client = client_class(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert client.api_endpoint == default_endpoint
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name",
+ [
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceGrpcTransport,
+ "grpc",
+ ),
+ (
+ WidgetConfigServiceAsyncClient,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ ),
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceRestTransport,
+ "rest",
+ ),
+ ],
+)
+def test_widget_config_service_client_client_options_scopes(
+ client_class, transport_class, transport_name
+):
+ # Check the case scopes are provided.
+ options = client_options.ClientOptions(
+ scopes=["1", "2"],
+ )
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=["1", "2"],
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ WidgetConfigServiceAsyncClient,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceRestTransport,
+ "rest",
+ None,
+ ),
+ ],
+)
+def test_widget_config_service_client_client_options_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+def test_widget_config_service_client_client_options_from_dict():
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.widget_config_service.transports.WidgetConfigServiceGrpcTransport.__init__"
+ ) as grpc_transport:
+ grpc_transport.return_value = None
+ client = WidgetConfigServiceClient(
+ client_options={"api_endpoint": "squid.clam.whelk"}
+ )
+ grpc_transport.assert_called_once_with(
+ credentials=None,
+ credentials_file=None,
+ host="squid.clam.whelk",
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class,transport_name,grpc_helpers",
+ [
+ (
+ WidgetConfigServiceClient,
+ transports.WidgetConfigServiceGrpcTransport,
+ "grpc",
+ grpc_helpers,
+ ),
+ (
+ WidgetConfigServiceAsyncClient,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ "grpc_asyncio",
+ grpc_helpers_async,
+ ),
+ ],
+)
+def test_widget_config_service_client_create_channel_credentials_file(
+ client_class, transport_class, transport_name, grpc_helpers
+):
+ # Check the case credentials file is provided.
+ options = client_options.ClientOptions(credentials_file="credentials.json")
+
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options, transport=transport_name)
+ patched.assert_called_once_with(
+ credentials=None,
+ credentials_file="credentials.json",
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
+
+ # test that the credentials from file are saved and used as the credentials.
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(grpc_helpers, "create_channel") as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ file_creds = ga_credentials.AnonymousCredentials()
+ load_creds.return_value = (file_creds, None)
+ adc.return_value = (creds, None)
+ client = client_class(client_options=options, transport=transport_name)
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=file_creds,
+ credentials_file=None,
+ quota_project_id=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=None,
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ widget_config_service.GetWidgetConfigRequest(),
+ {},
+ ],
+)
+def test_get_widget_config(request_type, transport: str = "grpc"):
+ client = WidgetConfigServiceClient(
+ 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_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = widget_config.WidgetConfig(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_type=widget_config.WidgetConfig.DataStoreType.SITE_SEARCH,
+ config_id="config_id_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ llm_enabled=True,
+ enable_result_score=True,
+ minimum_data_term_accepted=True,
+ enable_private_knowledge_graph=True,
+ gemini_bundle=True,
+ )
+ response = client.get_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = widget_config_service.GetWidgetConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, widget_config.WidgetConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert (
+ response.data_store_type == widget_config.WidgetConfig.DataStoreType.SITE_SEARCH
+ )
+ assert response.config_id == "config_id_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.llm_enabled is True
+ assert response.enable_result_score is True
+ assert response.minimum_data_term_accepted is True
+ assert response.enable_private_knowledge_graph is True
+ assert response.gemini_bundle is True
+
+
+def test_get_widget_config_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 = WidgetConfigServiceClient(
+ 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 = widget_config_service.GetWidgetConfigRequest(
+ name="name_value",
+ language_code="language_code_value",
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_widget_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.get_widget_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = widget_config_service.GetWidgetConfigRequest(
+ name="name_value",
+ language_code="language_code_value",
+ )
+ assert args[0] == request_msg
+
+
+def test_get_widget_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = WidgetConfigServiceClient(
+ 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_widget_config in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_widget_config] = (
+ mock_rpc
+ )
+ request = {}
+ client.get_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_widget_config(request)
+
+ # Establish that a new wrapper was not created for this call
+ assert wrapper_fn.call_count == 0
+ assert mock_rpc.call_count == 2
+
+
+@pytest.mark.asyncio
+async def test_get_widget_config_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 = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport=transport,
+ )
+
+ # Should wrap all calls on client creation
+ assert wrapper_fn.call_count > 0
+ wrapper_fn.reset_mock()
+
+ # Ensure method has been cached
+ assert (
+ client._client._transport.get_widget_config
+ 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_widget_config
+ ] = mock_rpc
+
+ request = {}
+ await client.get_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.get_widget_config(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",
+ [
+ widget_config_service.GetWidgetConfigRequest(),
+ {},
+ ],
+)
+async def test_get_widget_config_async(request_type, transport: str = "grpc_asyncio"):
+ client = WidgetConfigServiceAsyncClient(
+ 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_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ widget_config.WidgetConfig(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_type=widget_config.WidgetConfig.DataStoreType.SITE_SEARCH,
+ config_id="config_id_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ llm_enabled=True,
+ enable_result_score=True,
+ minimum_data_term_accepted=True,
+ enable_private_knowledge_graph=True,
+ gemini_bundle=True,
+ )
+ )
+ response = await client.get_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = widget_config_service.GetWidgetConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, widget_config.WidgetConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert (
+ response.data_store_type == widget_config.WidgetConfig.DataStoreType.SITE_SEARCH
+ )
+ assert response.config_id == "config_id_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.llm_enabled is True
+ assert response.enable_result_score is True
+ assert response.minimum_data_term_accepted is True
+ assert response.enable_private_knowledge_graph is True
+ assert response.gemini_bundle is True
+
+
+def test_get_widget_config_field_headers():
+ client = WidgetConfigServiceClient(
+ 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 = widget_config_service.GetWidgetConfigRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_widget_config), "__call__"
+ ) as call:
+ call.return_value = widget_config.WidgetConfig()
+ client.get_widget_config(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_widget_config_field_headers_async():
+ client = WidgetConfigServiceAsyncClient(
+ 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 = widget_config_service.GetWidgetConfigRequest()
+
+ request.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_widget_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ widget_config.WidgetConfig()
+ )
+ await client.get_widget_config(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_widget_config_flattened():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = widget_config.WidgetConfig()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.get_widget_config(
+ 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_widget_config_flattened_error():
+ client = WidgetConfigServiceClient(
+ 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_widget_config(
+ widget_config_service.GetWidgetConfigRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.asyncio
+async def test_get_widget_config_flattened_async():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = widget_config.WidgetConfig()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ widget_config.WidgetConfig()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.get_widget_config(
+ 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_widget_config_flattened_error_async():
+ client = WidgetConfigServiceAsyncClient(
+ 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_widget_config(
+ widget_config_service.GetWidgetConfigRequest(),
+ name="name_value",
+ )
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ widget_config_service.UpdateWidgetConfigRequest(),
+ {},
+ ],
+)
+def test_update_widget_config(request_type, transport: str = "grpc"):
+ client = WidgetConfigServiceClient(
+ 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_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_widget_config.WidgetConfig(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_type=gcd_widget_config.WidgetConfig.DataStoreType.SITE_SEARCH,
+ config_id="config_id_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ llm_enabled=True,
+ enable_result_score=True,
+ minimum_data_term_accepted=True,
+ enable_private_knowledge_graph=True,
+ gemini_bundle=True,
+ )
+ response = client.update_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ request = widget_config_service.UpdateWidgetConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_widget_config.WidgetConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert (
+ response.data_store_type
+ == gcd_widget_config.WidgetConfig.DataStoreType.SITE_SEARCH
+ )
+ assert response.config_id == "config_id_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.llm_enabled is True
+ assert response.enable_result_score is True
+ assert response.minimum_data_term_accepted is True
+ assert response.enable_private_knowledge_graph is True
+ assert response.gemini_bundle is True
+
+
+def test_update_widget_config_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 = WidgetConfigServiceClient(
+ 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 = widget_config_service.UpdateWidgetConfigRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_widget_config), "__call__"
+ ) as call:
+ call.return_value.name = (
+ "foo" # operation_request.operation in compute client(s) expect a string.
+ )
+ client.update_widget_config(request=request)
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = widget_config_service.UpdateWidgetConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_update_widget_config_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = WidgetConfigServiceClient(
+ 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.update_widget_config in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_widget_config] = (
+ mock_rpc
+ )
+ request = {}
+ client.update_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_widget_config(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_update_widget_config_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 = WidgetConfigServiceAsyncClient(
+ 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.update_widget_config
+ 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.update_widget_config
+ ] = mock_rpc
+
+ request = {}
+ await client.update_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ await client.update_widget_config(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",
+ [
+ widget_config_service.UpdateWidgetConfigRequest(),
+ {},
+ ],
+)
+async def test_update_widget_config_async(
+ request_type, transport: str = "grpc_asyncio"
+):
+ client = WidgetConfigServiceAsyncClient(
+ 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.update_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_widget_config.WidgetConfig(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_type=gcd_widget_config.WidgetConfig.DataStoreType.SITE_SEARCH,
+ config_id="config_id_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ llm_enabled=True,
+ enable_result_score=True,
+ minimum_data_term_accepted=True,
+ enable_private_knowledge_graph=True,
+ gemini_bundle=True,
+ )
+ )
+ response = await client.update_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls)
+ _, args, _ = call.mock_calls[0]
+ request = widget_config_service.UpdateWidgetConfigRequest()
+ assert args[0] == request
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_widget_config.WidgetConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert (
+ response.data_store_type
+ == gcd_widget_config.WidgetConfig.DataStoreType.SITE_SEARCH
+ )
+ assert response.config_id == "config_id_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.llm_enabled is True
+ assert response.enable_result_score is True
+ assert response.minimum_data_term_accepted is True
+ assert response.enable_private_knowledge_graph is True
+ assert response.gemini_bundle is True
+
+
+def test_update_widget_config_field_headers():
+ client = WidgetConfigServiceClient(
+ 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 = widget_config_service.UpdateWidgetConfigRequest()
+
+ request.widget_config.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_widget_config), "__call__"
+ ) as call:
+ call.return_value = gcd_widget_config.WidgetConfig()
+ client.update_widget_config(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",
+ "widget_config.name=name_value",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_update_widget_config_field_headers_async():
+ client = WidgetConfigServiceAsyncClient(
+ 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 = widget_config_service.UpdateWidgetConfigRequest()
+
+ request.widget_config.name = "name_value"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_widget_config), "__call__"
+ ) as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_widget_config.WidgetConfig()
+ )
+ await client.update_widget_config(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",
+ "widget_config.name=name_value",
+ ) in kw["metadata"]
+
+
+def test_update_widget_config_flattened():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_widget_config.WidgetConfig()
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ client.update_widget_config(
+ widget_config=gcd_widget_config.WidgetConfig(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].widget_config
+ mock_val = gcd_widget_config.WidgetConfig(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+def test_update_widget_config_flattened_error():
+ client = WidgetConfigServiceClient(
+ 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_widget_config(
+ widget_config_service.UpdateWidgetConfigRequest(),
+ widget_config=gcd_widget_config.WidgetConfig(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+@pytest.mark.asyncio
+async def test_update_widget_config_flattened_async():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = gcd_widget_config.WidgetConfig()
+
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_widget_config.WidgetConfig()
+ )
+ # Call the method with a truthy value for each flattened field,
+ # using the keyword arguments to the method.
+ response = await client.update_widget_config(
+ widget_config=gcd_widget_config.WidgetConfig(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].widget_config
+ mock_val = gcd_widget_config.WidgetConfig(name="name_value")
+ assert arg == mock_val
+ arg = args[0].update_mask
+ mock_val = field_mask_pb2.FieldMask(paths=["paths_value"])
+ assert arg == mock_val
+
+
+@pytest.mark.asyncio
+async def test_update_widget_config_flattened_error_async():
+ client = WidgetConfigServiceAsyncClient(
+ 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_widget_config(
+ widget_config_service.UpdateWidgetConfigRequest(),
+ widget_config=gcd_widget_config.WidgetConfig(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_get_widget_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = WidgetConfigServiceClient(
+ 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_widget_config in client._transport._wrapped_methods
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_widget_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.get_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.get_widget_config(request)
+
+ # Establish 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_widget_config_rest_required_fields(
+ request_type=widget_config_service.GetWidgetConfigRequest,
+):
+ transport_class = transports.WidgetConfigServiceRestTransport
+
+ 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._BaseGetWidgetConfig,
+ "_BaseGetWidgetConfig__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(
+ (
+ "acceptCache",
+ "getWidgetConfigRequestOption",
+ "languageCode",
+ "modelInfoView",
+ )
+ )
+
+ # verify required fields with non-default values are left alone
+ assert "name" in jsonified_request
+ assert jsonified_request["name"] == "name_value"
+
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = widget_config.WidgetConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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 = widget_config.WidgetConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_widget_config(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_widget_config_rest_flattened():
+ client = WidgetConfigServiceClient(
+ 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 = widget_config.WidgetConfig()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/widgetConfigs/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 = widget_config.WidgetConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_widget_config(**mock_args)
+
+ # Establish that the underlying call 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/*/dataStores/*/widgetConfigs/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_get_widget_config_rest_flattened_error(transport: str = "rest"):
+ client = WidgetConfigServiceClient(
+ 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_widget_config(
+ widget_config_service.GetWidgetConfigRequest(),
+ name="name_value",
+ )
+
+
+def test_update_widget_config_rest_use_cached_wrapped_rpc():
+ # Clients should use _prep_wrapped_messages to create cached wrapped rpcs,
+ # instead of constructing them on each call
+ with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn:
+ client = WidgetConfigServiceClient(
+ 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_widget_config in client._transport._wrapped_methods
+ )
+
+ # Replace cached wrapped function with mock
+ mock_rpc = 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_widget_config] = (
+ mock_rpc
+ )
+
+ request = {}
+ client.update_widget_config(request)
+
+ # Establish that the underlying gRPC stub method was called.
+ assert mock_rpc.call_count == 1
+
+ client.update_widget_config(request)
+
+ # Establish 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_widget_config_rest_required_fields(
+ request_type=widget_config_service.UpdateWidgetConfigRequest,
+):
+ transport_class = transports.WidgetConfigServiceRestTransport
+
+ 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._BaseUpdateWidgetConfig,
+ "_BaseUpdateWidgetConfig__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(("updateMask",))
+
+ # verify required fields with non-default values are left alone
+
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type(**request_init)
+
+ # Designate an appropriate value for the returned response.
+ return_value = gcd_widget_config.WidgetConfig()
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # We need to mock transcode() because providing default values
+ # for required fields will fail the real version if the http_options
+ # expect actual values for those fields.
+ with mock.patch.object(path_template, "transcode") as transcode:
+ # A uri without fields and an empty body will force 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
+
+ # Convert return value to protobuf type
+ return_value = gcd_widget_config.WidgetConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+
+ response_value._content = json_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_widget_config(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_widget_config_rest_flattened():
+ client = WidgetConfigServiceClient(
+ 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 = gcd_widget_config.WidgetConfig()
+
+ # get arguments that satisfy an http rule for this method
+ sample_request = {
+ "widget_config": {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/widgetConfigs/sample4"
+ }
+ }
+
+ # get truthy value for each flattened field
+ mock_args = dict(
+ widget_config=gcd_widget_config.WidgetConfig(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
+ # Convert return value to protobuf type
+ return_value = gcd_widget_config.WidgetConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value._content = 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_widget_config(**mock_args)
+
+ # Establish that the underlying call 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/{widget_config.name=projects/*/locations/*/dataStores/*/widgetConfigs/*}"
+ % client.transport._host,
+ args[1],
+ )
+
+
+def test_update_widget_config_rest_flattened_error(transport: str = "rest"):
+ client = WidgetConfigServiceClient(
+ 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_widget_config(
+ widget_config_service.UpdateWidgetConfigRequest(),
+ widget_config=gcd_widget_config.WidgetConfig(name="name_value"),
+ update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]),
+ )
+
+
+def test_credentials_transport_error():
+ # It is an error to provide credentials and a transport instance.
+ transport = transports.WidgetConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport=transport,
+ )
+
+ # It is an error to provide a credentials file and a transport instance.
+ transport = transports.WidgetConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = WidgetConfigServiceClient(
+ client_options={"credentials_file": "credentials.json"},
+ transport=transport,
+ )
+
+ # It is an error to provide an api_key and a transport instance.
+ transport = transports.WidgetConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with pytest.raises(ValueError):
+ client = WidgetConfigServiceClient(
+ 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 = WidgetConfigServiceClient(
+ client_options=options, credentials=ga_credentials.AnonymousCredentials()
+ )
+
+ # It is an error to provide scopes and a transport instance.
+ transport = transports.WidgetConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ with pytest.raises(ValueError):
+ client = WidgetConfigServiceClient(
+ client_options={"scopes": ["1", "2"]},
+ transport=transport,
+ )
+
+
+def test_transport_instance():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.WidgetConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ client = WidgetConfigServiceClient(transport=transport)
+ assert client.transport is transport
+
+
+def test_transport_get_channel():
+ # A client may be instantiated with a custom transport instance.
+ transport = transports.WidgetConfigServiceGrpcTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+ transport = transports.WidgetConfigServiceGrpcAsyncIOTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ channel = transport.grpc_channel
+ assert channel
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.WidgetConfigServiceGrpcTransport,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ transports.WidgetConfigServiceRestTransport,
+ ],
+)
+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 = WidgetConfigServiceClient.get_transport_class("grpc")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "grpc"
+
+
+def test_initialize_client_w_grpc():
+ client = WidgetConfigServiceClient(
+ 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_get_widget_config_empty_call_grpc():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_widget_config), "__call__"
+ ) as call:
+ call.return_value = widget_config.WidgetConfig()
+ client.get_widget_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = widget_config_service.GetWidgetConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_widget_config_empty_call_grpc():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="grpc",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_widget_config), "__call__"
+ ) as call:
+ call.return_value = gcd_widget_config.WidgetConfig()
+ client.update_widget_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = widget_config_service.UpdateWidgetConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_grpc_asyncio():
+ transport = WidgetConfigServiceAsyncClient.get_transport_class("grpc_asyncio")(
+ credentials=async_anonymous_credentials()
+ )
+ assert transport.kind == "grpc_asyncio"
+
+
+def test_initialize_client_w_grpc_asyncio():
+ client = WidgetConfigServiceAsyncClient(
+ 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_get_widget_config_empty_call_grpc_asyncio():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ widget_config.WidgetConfig(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_type=widget_config.WidgetConfig.DataStoreType.SITE_SEARCH,
+ config_id="config_id_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ llm_enabled=True,
+ enable_result_score=True,
+ minimum_data_term_accepted=True,
+ enable_private_knowledge_graph=True,
+ gemini_bundle=True,
+ )
+ )
+ await client.get_widget_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = widget_config_service.GetWidgetConfigRequest()
+ assert args[0] == request_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_widget_config_empty_call_grpc_asyncio():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ transport="grpc_asyncio",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_widget_config), "__call__"
+ ) as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ gcd_widget_config.WidgetConfig(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_type=gcd_widget_config.WidgetConfig.DataStoreType.SITE_SEARCH,
+ config_id="config_id_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ llm_enabled=True,
+ enable_result_score=True,
+ minimum_data_term_accepted=True,
+ enable_private_knowledge_graph=True,
+ gemini_bundle=True,
+ )
+ )
+ await client.update_widget_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = widget_config_service.UpdateWidgetConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_kind_rest():
+ transport = WidgetConfigServiceClient.get_transport_class("rest")(
+ credentials=ga_credentials.AnonymousCredentials()
+ )
+ assert transport.kind == "rest"
+
+
+def test_get_widget_config_rest_bad_request(
+ request_type=widget_config_service.GetWidgetConfigRequest,
+):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/widgetConfigs/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_widget_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ widget_config_service.GetWidgetConfigRequest,
+ dict,
+ ],
+)
+def test_get_widget_config_rest_call_success(request_type):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/widgetConfigs/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 = widget_config.WidgetConfig(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_type=widget_config.WidgetConfig.DataStoreType.SITE_SEARCH,
+ config_id="config_id_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ llm_enabled=True,
+ enable_result_score=True,
+ minimum_data_term_accepted=True,
+ enable_private_knowledge_graph=True,
+ gemini_bundle=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 = widget_config.WidgetConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_widget_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, widget_config.WidgetConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert (
+ response.data_store_type == widget_config.WidgetConfig.DataStoreType.SITE_SEARCH
+ )
+ assert response.config_id == "config_id_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.llm_enabled is True
+ assert response.enable_result_score is True
+ assert response.minimum_data_term_accepted is True
+ assert response.enable_private_knowledge_graph is True
+ assert response.gemini_bundle is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_get_widget_config_rest_interceptors(null_interceptor):
+ transport = transports.WidgetConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.WidgetConfigServiceRestInterceptor(),
+ )
+ client = WidgetConfigServiceClient(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.WidgetConfigServiceRestInterceptor, "post_get_widget_config"
+ ) as post,
+ mock.patch.object(
+ transports.WidgetConfigServiceRestInterceptor,
+ "post_get_widget_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.WidgetConfigServiceRestInterceptor, "pre_get_widget_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = widget_config_service.GetWidgetConfigRequest.pb(
+ widget_config_service.GetWidgetConfigRequest()
+ )
+ 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 = widget_config.WidgetConfig.to_json(widget_config.WidgetConfig())
+ req.return_value.content = return_value
+
+ request = widget_config_service.GetWidgetConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = widget_config.WidgetConfig()
+ post_with_metadata.return_value = widget_config.WidgetConfig(), metadata
+
+ client.get_widget_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_update_widget_config_rest_bad_request(
+ request_type=widget_config_service.UpdateWidgetConfigRequest,
+):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ # send a request that will satisfy transcoding
+ request_init = {
+ "widget_config": {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/widgetConfigs/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_widget_config(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ widget_config_service.UpdateWidgetConfigRequest,
+ dict,
+ ],
+)
+def test_update_widget_config_rest_call_success(request_type):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+
+ # send a request that will satisfy transcoding
+ request_init = {
+ "widget_config": {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/widgetConfigs/sample4"
+ }
+ }
+ request_init["widget_config"] = {
+ "name": "projects/sample1/locations/sample2/dataStores/sample3/widgetConfigs/sample4",
+ "display_name": "display_name_value",
+ "create_time": {"seconds": 751, "nanos": 543},
+ "update_time": {},
+ "data_store_type": 1,
+ "config_id": "config_id_value",
+ "solution_type": 1,
+ "industry_vertical": 1,
+ "llm_enabled": True,
+ "enable_result_score": True,
+ "minimum_data_term_accepted": True,
+ "collection_components": [
+ {
+ "name": "name_value",
+ "id": "id_value",
+ "display_name": "display_name_value",
+ "data_store_components": [
+ {
+ "name": "name_value",
+ "id": "id_value",
+ "display_name": "display_name_value",
+ "entity_name": "entity_name_value",
+ "data_store_config_type": 1,
+ }
+ ],
+ "data_source": "data_source_value",
+ "data_source_version": 0.2031,
+ "data_source_display_name": "data_source_display_name_value",
+ "data_source_end_user_display_name": "data_source_end_user_display_name_value",
+ "connector_icon_link": "connector_icon_link_value",
+ "connector_auth_state": {
+ "auth_state": 1,
+ "authorization_uri": "authorization_uri_value",
+ "update_time": {},
+ },
+ "metadata": {
+ "title": "title_value",
+ "description": "description_value",
+ "short_description": "short_description_value",
+ "author": "author_value",
+ "note": "note_value",
+ },
+ "is_first_party": True,
+ "tag": "tag_value",
+ }
+ ],
+ "ui_settings": {
+ "interaction_type": 1,
+ "generative_answer_config": {
+ "result_count": 1319,
+ "model_version": "model_version_value",
+ "model_prompt_preamble": "model_prompt_preamble_value",
+ "max_rephrase_steps": 1933,
+ "language_code": "language_code_value",
+ "disable_related_questions": True,
+ "ignore_non_answer_seeking_query": True,
+ "ignore_adversarial_query": True,
+ "ignore_low_relevant_content": True,
+ "image_source": 1,
+ },
+ "result_description_type": 1,
+ "enable_autocomplete": True,
+ "enable_safe_search": True,
+ "enable_quality_feedback": True,
+ "enable_search_as_you_type": True,
+ "default_search_request_order_by": "default_search_request_order_by_value",
+ "data_store_ui_configs": [
+ {
+ "name": "name_value",
+ "id": "id_value",
+ "facet_field": [
+ {"field": "field_value", "display_name": "display_name_value"}
+ ],
+ "fields_ui_components_map": {},
+ }
+ ],
+ "disable_user_events_collection": True,
+ "enable_visual_content_summary": True,
+ "enable_people_search": True,
+ "enable_create_agent_button": True,
+ "features": {},
+ "model_configs": {},
+ "search_addon_spec": {
+ "semantic_add_on_disabled": True,
+ "kpi_personalization_add_on_disabled": True,
+ "generative_answer_add_on_disabled": True,
+ },
+ "onedrive_picker_enabled": True,
+ "google_drive_picker_enabled": True,
+ "model_config_info": {
+ "resolved_models": [
+ {
+ "model_id": "model_id_value",
+ "display_name": "display_name_value",
+ "icon": "icon_value",
+ "description": "description_value",
+ "is_preview": True,
+ "label": "label_value",
+ "admin_view": {
+ "admin_overridable": True,
+ "enabled_by_default": True,
+ "regions": ["regions_value1", "regions_value2"],
+ },
+ "promoted": True,
+ "icon_url": "icon_url_value",
+ "family": "family_value",
+ }
+ ],
+ "default_model_id": "default_model_id_value",
+ "auto_model_id": "auto_model_id_value",
+ },
+ "source_admin_display_name_enabled": True,
+ },
+ "access_settings": {
+ "allow_public_access": True,
+ "allowlisted_domains": [
+ "allowlisted_domains_value1",
+ "allowlisted_domains_value2",
+ ],
+ "enable_web_app": True,
+ "workforce_identity_pool_provider": "workforce_identity_pool_provider_value",
+ "language_code": "language_code_value",
+ },
+ "ui_branding": {"logo": {"url": "url_value"}},
+ "homepage_setting": {
+ "shortcuts": [
+ {
+ "title": "title_value",
+ "icon": {},
+ "destination_uri": "destination_uri_value",
+ }
+ ]
+ },
+ "assistant_settings": {
+ "web_grounding_type": 1,
+ "default_web_grounding_toggle_off": True,
+ "disable_location_context": True,
+ },
+ "customer_provided_config": {"customer_type": 1, "compliance_level": 1},
+ "enable_private_knowledge_graph": True,
+ "gemini_bundle": True,
+ "batch_auth_statuses": [
+ {
+ "placeholder": "placeholder_value",
+ "batch_authorization_group": "batch_authorization_group_value",
+ "connector_auth_state": {},
+ }
+ ],
+ "nodes": [
+ {
+ "display_name": "display_name_value",
+ "icon_url": "icon_url_value",
+ "description": "description_value",
+ "parameter_schema": {"fields": {}},
+ "output_schema": {},
+ "type_": 1,
+ }
+ ],
+ }
+ # 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 = widget_config_service.UpdateWidgetConfigRequest.meta.fields[
+ "widget_config"
+ ]
+
+ 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["widget_config"].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["widget_config"][field])):
+ del request_init["widget_config"][field][i][subfield]
+ else:
+ del request_init["widget_config"][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 = gcd_widget_config.WidgetConfig(
+ name="name_value",
+ display_name="display_name_value",
+ data_store_type=gcd_widget_config.WidgetConfig.DataStoreType.SITE_SEARCH,
+ config_id="config_id_value",
+ solution_type=common.SolutionType.SOLUTION_TYPE_RECOMMENDATION,
+ industry_vertical=common.IndustryVertical.GENERIC,
+ llm_enabled=True,
+ enable_result_score=True,
+ minimum_data_term_accepted=True,
+ enable_private_knowledge_graph=True,
+ gemini_bundle=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 = gcd_widget_config.WidgetConfig.pb(return_value)
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_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_widget_config(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, gcd_widget_config.WidgetConfig)
+ assert response.name == "name_value"
+ assert response.display_name == "display_name_value"
+ assert (
+ response.data_store_type
+ == gcd_widget_config.WidgetConfig.DataStoreType.SITE_SEARCH
+ )
+ assert response.config_id == "config_id_value"
+ assert response.solution_type == common.SolutionType.SOLUTION_TYPE_RECOMMENDATION
+ assert response.industry_vertical == common.IndustryVertical.GENERIC
+ assert response.llm_enabled is True
+ assert response.enable_result_score is True
+ assert response.minimum_data_term_accepted is True
+ assert response.enable_private_knowledge_graph is True
+ assert response.gemini_bundle is True
+
+
+@pytest.mark.parametrize("null_interceptor", [True, False])
+def test_update_widget_config_rest_interceptors(null_interceptor):
+ transport = transports.WidgetConfigServiceRestTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ interceptor=None
+ if null_interceptor
+ else transports.WidgetConfigServiceRestInterceptor(),
+ )
+ client = WidgetConfigServiceClient(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.WidgetConfigServiceRestInterceptor, "post_update_widget_config"
+ ) as post,
+ mock.patch.object(
+ transports.WidgetConfigServiceRestInterceptor,
+ "post_update_widget_config_with_metadata",
+ ) as post_with_metadata,
+ mock.patch.object(
+ transports.WidgetConfigServiceRestInterceptor, "pre_update_widget_config"
+ ) as pre,
+ ):
+ pre.assert_not_called()
+ post.assert_not_called()
+ post_with_metadata.assert_not_called()
+ pb_message = widget_config_service.UpdateWidgetConfigRequest.pb(
+ widget_config_service.UpdateWidgetConfigRequest()
+ )
+ 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 = gcd_widget_config.WidgetConfig.to_json(
+ gcd_widget_config.WidgetConfig()
+ )
+ req.return_value.content = return_value
+
+ request = widget_config_service.UpdateWidgetConfigRequest()
+ metadata = [
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ]
+ pre.return_value = request, metadata
+ post.return_value = gcd_widget_config.WidgetConfig()
+ post_with_metadata.return_value = gcd_widget_config.WidgetConfig(), metadata
+
+ client.update_widget_config(
+ request,
+ metadata=[
+ ("key", "val"),
+ ("cephalopod", "squid"),
+ ],
+ )
+
+ pre.assert_called_once()
+ post.assert_called_once()
+ post_with_metadata.assert_called_once()
+
+
+def test_cancel_operation_rest_bad_request(
+ request_type=operations_pb2.CancelOperationRequest,
+):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.cancel_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.CancelOperationRequest,
+ dict,
+ ],
+)
+def test_cancel_operation_rest(request_type):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = None
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = "{}"
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.cancel_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert response is None
+
+
+def test_get_operation_rest_bad_request(
+ request_type=operations_pb2.GetOperationRequest,
+):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict(
+ {"name": "projects/sample1/operations/sample2"}, request
+ )
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.get_operation(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.GetOperationRequest,
+ dict,
+ ],
+)
+def test_get_operation_rest(request_type):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1/operations/sample2"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.Operation()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.get_operation(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_list_operations_rest_bad_request(
+ request_type=operations_pb2.ListOperationsRequest,
+):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+ request = request_type()
+ request = json_format.ParseDict({"name": "projects/sample1"}, request)
+
+ # Mock the http request call within the method and fake a BadRequest error.
+ with (
+ mock.patch.object(Session, "request") as req,
+ pytest.raises(core_exceptions.BadRequest),
+ ):
+ # Wrap the value into a proper Response obj
+ response_value = Response()
+ json_return_value = ""
+ response_value.json = mock.Mock(return_value={})
+ response_value.status_code = 400
+ response_value.request = Request()
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+ client.list_operations(request)
+
+
+@pytest.mark.parametrize(
+ "request_type",
+ [
+ operations_pb2.ListOperationsRequest,
+ dict,
+ ],
+)
+def test_list_operations_rest(request_type):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ request_init = {"name": "projects/sample1"}
+ request = request_type(**request_init)
+ # Mock the http request call within the method and fake a response.
+ with mock.patch.object(Session, "request") as req:
+ # Designate an appropriate value for the returned response.
+ return_value = operations_pb2.ListOperationsResponse()
+
+ # Wrap the value into a proper Response obj
+ response_value = mock.Mock()
+ response_value.status_code = 200
+ json_return_value = json_format.MessageToJson(return_value)
+ response_value.content = json_return_value.encode("UTF-8")
+
+ req.return_value = response_value
+ req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"}
+
+ response = client.list_operations(request)
+
+ # Establish that the response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_initialize_client_w_rest():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ assert client is not None
+
+
+# This test is a coverage failsafe to make sure that totally empty calls,
+# i.e. request == None and no flattened fields passed, work.
+def test_get_widget_config_empty_call_rest():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.get_widget_config), "__call__"
+ ) as call:
+ client.get_widget_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = widget_config_service.GetWidgetConfigRequest()
+ assert args[0] == request_msg
+
+
+# This 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_widget_config_empty_call_rest():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ transport="rest",
+ )
+
+ # Mock the actual call, and fake the request.
+ with mock.patch.object(
+ type(client.transport.update_widget_config), "__call__"
+ ) as call:
+ client.update_widget_config(request=None)
+
+ # Establish that the underlying stub method was called.
+ call.assert_called()
+ _, args, _ = call.mock_calls[0]
+ request_msg = widget_config_service.UpdateWidgetConfigRequest()
+ assert args[0] == request_msg
+
+
+def test_transport_grpc_default():
+ # A client should use the gRPC transport by default.
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ assert isinstance(
+ client.transport,
+ transports.WidgetConfigServiceGrpcTransport,
+ )
+
+
+def test_widget_config_service_base_transport_error():
+ # Passing both a credentials object and credentials_file should raise an error
+ with pytest.raises(core_exceptions.DuplicateCredentialArgs):
+ transport = transports.WidgetConfigServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ credentials_file="credentials.json",
+ )
+
+
+def test_widget_config_service_base_transport():
+ # Instantiate the base transport.
+ with mock.patch(
+ "google.cloud.discoveryengine_v1.services.widget_config_service.transports.WidgetConfigServiceTransport.__init__"
+ ) as Transport:
+ Transport.return_value = None
+ transport = transports.WidgetConfigServiceTransport(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+
+ # Every method on the transport should just blindly
+ # raise NotImplementedError.
+ methods = (
+ "get_widget_config",
+ "update_widget_config",
+ "get_operation",
+ "cancel_operation",
+ "list_operations",
+ )
+ for method in methods:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, method)(request=object())
+
+ with pytest.raises(NotImplementedError):
+ transport.close()
+
+ # Catch all for all remaining methods and properties
+ remainder = [
+ "kind",
+ ]
+ for r in remainder:
+ with pytest.raises(NotImplementedError):
+ getattr(transport, r)()
+
+
+def test_widget_config_service_base_transport_with_credentials_file():
+ # Instantiate the base transport with a credentials file
+ with (
+ mock.patch.object(
+ google.auth, "load_credentials_from_file", autospec=True
+ ) as load_creds,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.widget_config_service.transports.WidgetConfigServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ load_creds.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.WidgetConfigServiceTransport(
+ credentials_file="credentials.json",
+ quota_project_id="octopus",
+ )
+ load_creds.assert_called_once_with(
+ "credentials.json",
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+def test_widget_config_service_base_transport_with_adc():
+ # Test the default credentials are used if credentials and credentials_file are None.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch(
+ "google.cloud.discoveryengine_v1.services.widget_config_service.transports.WidgetConfigServiceTransport._prep_wrapped_messages"
+ ) as Transport,
+ ):
+ Transport.return_value = None
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport = transports.WidgetConfigServiceTransport()
+ adc.assert_called_once()
+
+
+def test_widget_config_service_auth_adc():
+ # If no credentials are provided, we should use ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ WidgetConfigServiceClient()
+ adc.assert_called_once_with(
+ scopes=None,
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id=None,
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.WidgetConfigServiceGrpcTransport,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_widget_config_service_transport_auth_adc(transport_class):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ adc.return_value = (ga_credentials.AnonymousCredentials(), None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+ adc.assert_called_once_with(
+ scopes=["1", "2"],
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ quota_project_id="octopus",
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.WidgetConfigServiceGrpcTransport,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ transports.WidgetConfigServiceRestTransport,
+ ],
+)
+def test_widget_config_service_transport_auth_gdch_credentials(transport_class):
+ host = "https://language.com"
+ api_audience_tests = [None, "https://language2.com"]
+ api_audience_expect = [host, "https://language2.com"]
+ for t, e in zip(api_audience_tests, api_audience_expect):
+ with mock.patch.object(google.auth, "default", autospec=True) as adc:
+ gdch_mock = mock.MagicMock()
+ type(gdch_mock).with_gdch_audience = mock.PropertyMock(
+ return_value=gdch_mock
+ )
+ adc.return_value = (gdch_mock, None)
+ transport_class(host=host, api_audience=t)
+ gdch_mock.with_gdch_audience.assert_called_once_with(e)
+
+
+@pytest.mark.parametrize(
+ "transport_class,grpc_helpers",
+ [
+ (transports.WidgetConfigServiceGrpcTransport, grpc_helpers),
+ (transports.WidgetConfigServiceGrpcAsyncIOTransport, grpc_helpers_async),
+ ],
+)
+def test_widget_config_service_transport_create_channel(transport_class, grpc_helpers):
+ # If credentials and host are not provided, the transport class should use
+ # ADC credentials.
+ with (
+ mock.patch.object(google.auth, "default", autospec=True) as adc,
+ mock.patch.object(
+ grpc_helpers, "create_channel", autospec=True
+ ) as create_channel,
+ ):
+ creds = ga_credentials.AnonymousCredentials()
+ adc.return_value = (creds, None)
+ transport_class(quota_project_id="octopus", scopes=["1", "2"])
+
+ create_channel.assert_called_with(
+ "discoveryengine.googleapis.com:443",
+ credentials=creds,
+ credentials_file=None,
+ quota_project_id="octopus",
+ default_scopes=(
+ "https://www.googleapis.com/auth/cloud-platform",
+ "https://www.googleapis.com/auth/discoveryengine.assist.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.readwrite",
+ "https://www.googleapis.com/auth/discoveryengine.serving.readwrite",
+ ),
+ scopes=["1", "2"],
+ default_host="discoveryengine.googleapis.com",
+ ssl_credentials=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.WidgetConfigServiceGrpcTransport,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_widget_config_service_grpc_transport_client_cert_source_for_mtls(
+ transport_class,
+):
+ cred = ga_credentials.AnonymousCredentials()
+
+ # Check ssl_channel_credentials is used if provided.
+ with mock.patch.object(transport_class, "create_channel") as mock_create_channel:
+ mock_ssl_channel_creds = mock.Mock()
+ transport_class(
+ host="squid.clam.whelk",
+ credentials=cred,
+ ssl_channel_credentials=mock_ssl_channel_creds,
+ )
+ mock_create_channel.assert_called_once_with(
+ "squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_channel_creds,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+
+ # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls
+ # is used.
+ with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()):
+ with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred:
+ transport_class(
+ credentials=cred,
+ client_cert_source_for_mtls=client_cert_source_callback,
+ )
+ expected_cert, expected_key = client_cert_source_callback()
+ mock_ssl_cred.assert_called_once_with(
+ certificate_chain=expected_cert, private_key=expected_key
+ )
+
+
+def test_widget_config_service_http_transport_client_cert_source_for_mtls():
+ cred = ga_credentials.AnonymousCredentials()
+ with mock.patch(
+ "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel"
+ ) as mock_configure_mtls_channel:
+ transports.WidgetConfigServiceRestTransport(
+ credentials=cred, client_cert_source_for_mtls=client_cert_source_callback
+ )
+ mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback)
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_widget_config_service_host_no_port(transport_name):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:443"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "grpc",
+ "grpc_asyncio",
+ "rest",
+ ],
+)
+def test_widget_config_service_host_with_port(transport_name):
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_options=client_options.ClientOptions(
+ api_endpoint="discoveryengine.googleapis.com:8000"
+ ),
+ transport=transport_name,
+ )
+ assert client.transport._host == (
+ "discoveryengine.googleapis.com:8000"
+ if transport_name in ["grpc", "grpc_asyncio"]
+ else "https://discoveryengine.googleapis.com:8000"
+ )
+
+
+@pytest.mark.parametrize(
+ "transport_name",
+ [
+ "rest",
+ ],
+)
+def test_widget_config_service_client_transport_session_collision(transport_name):
+ creds1 = ga_credentials.AnonymousCredentials()
+ creds2 = ga_credentials.AnonymousCredentials()
+ client1 = WidgetConfigServiceClient(
+ credentials=creds1,
+ transport=transport_name,
+ )
+ client2 = WidgetConfigServiceClient(
+ credentials=creds2,
+ transport=transport_name,
+ )
+ session1 = client1.transport.get_widget_config._session
+ session2 = client2.transport.get_widget_config._session
+ assert session1 != session2
+ session1 = client1.transport.update_widget_config._session
+ session2 = client2.transport.update_widget_config._session
+ assert session1 != session2
+
+
+def test_widget_config_service_grpc_transport_channel():
+ channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.WidgetConfigServiceGrpcTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+def test_widget_config_service_grpc_asyncio_transport_channel():
+ channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials())
+
+ # Check that channel is used if provided.
+ transport = transports.WidgetConfigServiceGrpcAsyncIOTransport(
+ host="squid.clam.whelk",
+ channel=channel,
+ )
+ assert transport.grpc_channel == channel
+ assert transport._host == "squid.clam.whelk:443"
+ assert transport._ssl_channel_credentials == None
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.filterwarnings("ignore::FutureWarning")
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.WidgetConfigServiceGrpcTransport,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_widget_config_service_transport_channel_mtls_with_client_cert_source(
+ transport_class,
+):
+ with mock.patch(
+ "grpc.ssl_channel_credentials", autospec=True
+ ) as grpc_ssl_channel_cred:
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_ssl_cred = mock.Mock()
+ grpc_ssl_channel_cred.return_value = mock_ssl_cred
+
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+
+ cred = ga_credentials.AnonymousCredentials()
+ with pytest.warns(DeprecationWarning):
+ with mock.patch.object(google.auth, "default") as adc:
+ adc.return_value = (cred, None)
+ transport = transport_class(
+ host="squid.clam.whelk",
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=client_cert_source_callback,
+ )
+ adc.assert_called_once()
+
+ grpc_ssl_channel_cred.assert_called_once_with(
+ certificate_chain=b"cert bytes", private_key=b"key bytes"
+ )
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+ assert transport._ssl_channel_credentials == mock_ssl_cred
+
+
+# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are
+# removed from grpc/grpc_asyncio transport constructor.
+@pytest.mark.parametrize(
+ "transport_class",
+ [
+ transports.WidgetConfigServiceGrpcTransport,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ ],
+)
+def test_widget_config_service_transport_channel_mtls_with_adc(transport_class):
+ mock_ssl_cred = mock.Mock()
+ with mock.patch.multiple(
+ "google.auth.transport.grpc.SslCredentials",
+ __init__=mock.Mock(return_value=None),
+ ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred),
+ ):
+ with mock.patch.object(
+ transport_class, "create_channel"
+ ) as grpc_create_channel:
+ mock_grpc_channel = mock.Mock()
+ grpc_create_channel.return_value = mock_grpc_channel
+ mock_cred = mock.Mock()
+
+ with pytest.warns(DeprecationWarning):
+ transport = transport_class(
+ host="squid.clam.whelk",
+ credentials=mock_cred,
+ api_mtls_endpoint="mtls.squid.clam.whelk",
+ client_cert_source=None,
+ )
+
+ grpc_create_channel.assert_called_once_with(
+ "mtls.squid.clam.whelk:443",
+ credentials=mock_cred,
+ credentials_file=None,
+ scopes=None,
+ ssl_credentials=mock_ssl_cred,
+ quota_project_id=None,
+ options=[
+ ("grpc.max_send_message_length", -1),
+ ("grpc.max_receive_message_length", -1),
+ ],
+ )
+ assert transport.grpc_channel == mock_grpc_channel
+
+
+def test_widget_config_path():
+ project = "squid"
+ location = "clam"
+ data_store = "whelk"
+ widget_config = "octopus"
+ expected = "projects/{project}/locations/{location}/dataStores/{data_store}/widgetConfigs/{widget_config}".format(
+ project=project,
+ location=location,
+ data_store=data_store,
+ widget_config=widget_config,
+ )
+ actual = WidgetConfigServiceClient.widget_config_path(
+ project, location, data_store, widget_config
+ )
+ assert expected == actual
+
+
+def test_parse_widget_config_path():
+ expected = {
+ "project": "oyster",
+ "location": "nudibranch",
+ "data_store": "cuttlefish",
+ "widget_config": "mussel",
+ }
+ path = WidgetConfigServiceClient.widget_config_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WidgetConfigServiceClient.parse_widget_config_path(path)
+ assert expected == actual
+
+
+def test_common_billing_account_path():
+ billing_account = "winkle"
+ expected = "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+ actual = WidgetConfigServiceClient.common_billing_account_path(billing_account)
+ assert expected == actual
+
+
+def test_parse_common_billing_account_path():
+ expected = {
+ "billing_account": "nautilus",
+ }
+ path = WidgetConfigServiceClient.common_billing_account_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WidgetConfigServiceClient.parse_common_billing_account_path(path)
+ assert expected == actual
+
+
+def test_common_folder_path():
+ folder = "scallop"
+ expected = "folders/{folder}".format(
+ folder=folder,
+ )
+ actual = WidgetConfigServiceClient.common_folder_path(folder)
+ assert expected == actual
+
+
+def test_parse_common_folder_path():
+ expected = {
+ "folder": "abalone",
+ }
+ path = WidgetConfigServiceClient.common_folder_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WidgetConfigServiceClient.parse_common_folder_path(path)
+ assert expected == actual
+
+
+def test_common_organization_path():
+ organization = "squid"
+ expected = "organizations/{organization}".format(
+ organization=organization,
+ )
+ actual = WidgetConfigServiceClient.common_organization_path(organization)
+ assert expected == actual
+
+
+def test_parse_common_organization_path():
+ expected = {
+ "organization": "clam",
+ }
+ path = WidgetConfigServiceClient.common_organization_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WidgetConfigServiceClient.parse_common_organization_path(path)
+ assert expected == actual
+
+
+def test_common_project_path():
+ project = "whelk"
+ expected = "projects/{project}".format(
+ project=project,
+ )
+ actual = WidgetConfigServiceClient.common_project_path(project)
+ assert expected == actual
+
+
+def test_parse_common_project_path():
+ expected = {
+ "project": "octopus",
+ }
+ path = WidgetConfigServiceClient.common_project_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WidgetConfigServiceClient.parse_common_project_path(path)
+ assert expected == actual
+
+
+def test_common_location_path():
+ project = "oyster"
+ location = "nudibranch"
+ expected = "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+ actual = WidgetConfigServiceClient.common_location_path(project, location)
+ assert expected == actual
+
+
+def test_parse_common_location_path():
+ expected = {
+ "project": "cuttlefish",
+ "location": "mussel",
+ }
+ path = WidgetConfigServiceClient.common_location_path(**expected)
+
+ # Check that the path construction is reversible.
+ actual = WidgetConfigServiceClient.parse_common_location_path(path)
+ assert expected == actual
+
+
+def test_client_with_default_client_info():
+ client_info = gapic_v1.client_info.ClientInfo()
+
+ with mock.patch.object(
+ transports.WidgetConfigServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+ with mock.patch.object(
+ transports.WidgetConfigServiceTransport, "_prep_wrapped_messages"
+ ) as prep:
+ transport_class = WidgetConfigServiceClient.get_transport_class()
+ transport = transport_class(
+ credentials=ga_credentials.AnonymousCredentials(),
+ client_info=client_info,
+ )
+ prep.assert_called_once_with(client_info)
+
+
+def test_cancel_operation(transport: str = "grpc"):
+ client = WidgetConfigServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+ response = client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_async(transport: str = "grpc_asyncio"):
+ client = WidgetConfigServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(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 response is the type that we expect.
+ assert response is None
+
+
+def test_cancel_operation_field_headers():
+ client = WidgetConfigServiceClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = None
+
+ client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_field_headers_async():
+ client = WidgetConfigServiceAsyncClient(
+ 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 = operations_pb2.CancelOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_cancel_operation_from_dict():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ response = client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_from_dict_async():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ response = await client.cancel_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_cancel_operation_flattened():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = None
+
+ client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_cancel_operation_flattened_async():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None)
+ await client.cancel_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.CancelOperationRequest()
+
+
+def test_get_operation(transport: str = "grpc"):
+ client = WidgetConfigServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+ response = client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+@pytest.mark.asyncio
+async def test_get_operation_async(transport: str = "grpc_asyncio"):
+ client = WidgetConfigServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.Operation)
+
+
+def test_get_operation_field_headers():
+ client = WidgetConfigServiceClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_get_operation_field_headers_async():
+ client = WidgetConfigServiceAsyncClient(
+ 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 = operations_pb2.GetOperationRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation(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=locations",
+ ) in kw["metadata"]
+
+
+def test_get_operation_from_dict():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ response = client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_from_dict_async():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ response = await client.get_operation(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_get_operation_flattened():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.Operation()
+
+ client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+@pytest.mark.asyncio
+async def test_get_operation_flattened_async():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.get_operation), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.Operation()
+ )
+ await client.get_operation()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.GetOperationRequest()
+
+
+def test_list_operations(transport: str = "grpc"):
+ client = WidgetConfigServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+ response = client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+@pytest.mark.asyncio
+async def test_list_operations_async(transport: str = "grpc_asyncio"):
+ client = WidgetConfigServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(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 response is the type that we expect.
+ assert isinstance(response, operations_pb2.ListOperationsResponse)
+
+
+def test_list_operations_field_headers():
+ client = WidgetConfigServiceClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+@pytest.mark.asyncio
+async def test_list_operations_field_headers_async():
+ client = WidgetConfigServiceAsyncClient(
+ 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 = operations_pb2.ListOperationsRequest()
+ request.name = "locations"
+
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations(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=locations",
+ ) in kw["metadata"]
+
+
+def test_list_operations_from_dict():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ response = client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_from_dict_async():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ response = await client.list_operations(
+ request={
+ "name": "locations",
+ }
+ )
+ call.assert_called()
+
+
+def test_list_operations_flattened():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = operations_pb2.ListOperationsResponse()
+
+ client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+@pytest.mark.asyncio
+async def test_list_operations_flattened_async():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(),
+ )
+ # Mock the actual call within the gRPC stub, and fake the request.
+ with mock.patch.object(type(client.transport.list_operations), "__call__") as call:
+ # Designate an appropriate return value for the call.
+ call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(
+ operations_pb2.ListOperationsResponse()
+ )
+ await client.list_operations()
+ # Establish that the underlying gRPC stub method was called.
+ assert len(call.mock_calls) == 1
+ _, args, _ = call.mock_calls[0]
+ assert args[0] == operations_pb2.ListOperationsRequest()
+
+
+def test_transport_close_grpc():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="grpc"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+@pytest.mark.asyncio
+async def test_transport_close_grpc_asyncio():
+ client = WidgetConfigServiceAsyncClient(
+ credentials=async_anonymous_credentials(), transport="grpc_asyncio"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_grpc_channel")), "close"
+ ) as close:
+ async with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_transport_close_rest():
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport="rest"
+ )
+ with mock.patch.object(
+ type(getattr(client.transport, "_session")), "close"
+ ) as close:
+ with client:
+ close.assert_not_called()
+ close.assert_called_once()
+
+
+def test_client_ctx():
+ transports = [
+ "rest",
+ "grpc",
+ ]
+ for transport in transports:
+ client = WidgetConfigServiceClient(
+ credentials=ga_credentials.AnonymousCredentials(), transport=transport
+ )
+ # Test client calls underlying transport.
+ with mock.patch.object(type(client.transport), "close") as close:
+ close.assert_not_called()
+ with client:
+ pass
+ close.assert_called()
+
+
+@pytest.mark.parametrize(
+ "client_class,transport_class",
+ [
+ (WidgetConfigServiceClient, transports.WidgetConfigServiceGrpcTransport),
+ (
+ WidgetConfigServiceAsyncClient,
+ transports.WidgetConfigServiceGrpcAsyncIOTransport,
+ ),
+ ],
+)
+def test_api_key_credentials(client_class, transport_class):
+ with mock.patch.object(
+ google.auth._default, "get_api_key_credentials", create=True
+ ) as get_api_key_credentials:
+ mock_cred = mock.Mock()
+ get_api_key_credentials.return_value = mock_cred
+ options = client_options.ClientOptions()
+ options.api_key = "api_key"
+ with mock.patch.object(transport_class, "__init__") as patched:
+ patched.return_value = None
+ client = client_class(client_options=options)
+ patched.assert_called_once_with(
+ credentials=mock_cred,
+ credentials_file=None,
+ host=client._DEFAULT_ENDPOINT_TEMPLATE.format(
+ UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE
+ ),
+ scopes=None,
+ client_cert_source_for_mtls=None,
+ quota_project_id=None,
+ client_info=transports.base.DEFAULT_CLIENT_INFO,
+ always_use_jwt_access=True,
+ api_audience=None,
+ )
diff --git a/packages/google-cloud-iam/google/cloud/iam_admin/__init__.py b/packages/google-cloud-iam/google/cloud/iam_admin/__init__.py
index b470fe0845c9..81111b85fd88 100644
--- a/packages/google-cloud-iam/google/cloud/iam_admin/__init__.py
+++ b/packages/google-cloud-iam/google/cloud/iam_admin/__init__.py
@@ -70,6 +70,9 @@
UpdateRoleRequest,
UploadServiceAccountKeyRequest,
)
+from google.cloud.iam_admin_v1.types.workforce_pool_platform_logs import (
+ WorkforcePoolAttributeSyncEventLog,
+)
__all__ = (
"IAMClient",
@@ -122,4 +125,5 @@
"ServiceAccountKeyOrigin",
"ServiceAccountPrivateKeyType",
"ServiceAccountPublicKeyType",
+ "WorkforcePoolAttributeSyncEventLog",
)
diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/__init__.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/__init__.py
index f8b4d50820eb..8424c878039a 100644
--- a/packages/google-cloud-iam/google/cloud/iam_admin_v1/__init__.py
+++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/__init__.py
@@ -29,6 +29,7 @@
"google.cloud.iam_admin_v1.services.iam",
"google.cloud.iam_admin_v1.types.audit_data",
"google.cloud.iam_admin_v1.types.iam",
+ "google.cloud.iam_admin_v1.types.workforce_pool_platform_logs",
}
@@ -83,6 +84,7 @@
UpdateRoleRequest,
UploadServiceAccountKeyRequest,
)
+from .types.workforce_pool_platform_logs import WorkforcePoolAttributeSyncEventLog
__all__ = (
"IAMAsyncClient",
@@ -135,6 +137,7 @@
"UndeleteServiceAccountResponse",
"UpdateRoleRequest",
"UploadServiceAccountKeyRequest",
+ "WorkforcePoolAttributeSyncEventLog",
)
api_core.check_python_version("google.cloud.iam_admin_v1")
diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/__init__.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/__init__.py
index 8d51b309e13b..750858a86eb6 100644
--- a/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/__init__.py
+++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/__init__.py
@@ -65,6 +65,9 @@
UpdateRoleRequest,
UploadServiceAccountKeyRequest,
)
+from .workforce_pool_platform_logs import (
+ WorkforcePoolAttributeSyncEventLog,
+)
__all__ = (
"AuditData",
@@ -115,4 +118,5 @@
"ServiceAccountKeyOrigin",
"ServiceAccountPrivateKeyType",
"ServiceAccountPublicKeyType",
+ "WorkforcePoolAttributeSyncEventLog",
)
diff --git a/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/workforce_pool_platform_logs.py b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/workforce_pool_platform_logs.py
new file mode 100644
index 000000000000..1e2aed8cd6a2
--- /dev/null
+++ b/packages/google-cloud-iam/google/cloud/iam_admin_v1/types/workforce_pool_platform_logs.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT 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.iam.admin.v1",
+ manifest={
+ "WorkforcePoolAttributeSyncEventLog",
+ },
+)
+
+
+class WorkforcePoolAttributeSyncEventLog(proto.Message):
+ r"""Log payload for Workforce Pool Provider background user
+ attribute sync events.
+
+ Attributes:
+ subject (str):
+ The raw subject identifier of the user whose
+ attributes are being synced. This identifies the
+ specific user within the workforce pool.
+ failure_reason (str):
+ A machine-readable code indicating the reason for failure.
+ Only populated when ``severity`` is ``ERROR``.
+
+ Possible values include, but are not limited to:
+
+ - ``PROVIDER_NOT_FOUND``: The user was not found in the
+ identity provider.
+ - ``IDP_UNREACHABLE``: The identity provider could not be
+ reached.
+ - ``ATTRIBUTE_MAPPING_ERROR``: The attribute mapping
+ configuration is invalid.
+ - ``INTERNAL_ERROR``: An internal error occurred during
+ attribute synchronization.
+ message (str):
+ Human-readable details describing the
+ attribute sync result. For successful syncs,
+ this contains the updated user attributes if
+ detailed audit logging is enabled. For failures,
+ this describes the cause of the failure.
+ """
+
+ subject: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ failure_reason: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ message: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+
+__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py
index bf67b434cf80..3c5ecf10232f 100644
--- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py
+++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py
@@ -71,6 +71,7 @@
GetTokenAuthUserRequest,
Instance,
InstanceAclPolicyAttachment,
+ IpVersion,
ListAclPoliciesRequest,
ListAclPoliciesResponse,
ListAclPolicyRevisionsRequest,
@@ -146,6 +147,7 @@
"GetTokenAuthUserRequest",
"Instance",
"InstanceAclPolicyAttachment",
+ "IpVersion",
"ListAclPoliciesRequest",
"ListAclPoliciesResponse",
"ListAclPolicyRevisionsRequest",
diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/__init__.py
index 11e173578fef..5b7ef75dc882 100644
--- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/__init__.py
+++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/__init__.py
@@ -52,6 +52,7 @@
GetTokenAuthUserRequest,
Instance,
InstanceAclPolicyAttachment,
+ IpVersion,
ListAclPoliciesRequest,
ListAclPoliciesResponse,
ListAclPolicyRevisionsRequest,
@@ -158,5 +159,6 @@
"WeeklyMaintenanceWindow",
"ZoneDistributionConfig",
"ConnectionType",
+ "IpVersion",
"PscConnectionStatus",
)
diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/memorystore.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/memorystore.py
index e2f1afa1d804..404ffa17313a 100644
--- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/memorystore.py
+++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/memorystore.py
@@ -29,6 +29,7 @@
manifest={
"PscConnectionStatus",
"ConnectionType",
+ "IpVersion",
"Instance",
"AclPolicyInfo",
"StartMigrationRequest",
@@ -142,6 +143,24 @@ class ConnectionType(proto.Enum):
CONNECTION_TYPE_READER = 3
+class IpVersion(proto.Enum):
+ r"""IP version for PSC consumer endpoints.
+
+ Values:
+ IP_VERSION_UNSPECIFIED (0):
+ Not specified. Defaults to IPV4 on
+ CreateInstance.
+ IPV4 (1):
+ IPv4 address family.
+ IPV6 (2):
+ IPv6 address family.
+ """
+
+ IP_VERSION_UNSPECIFIED = 0
+ IPV4 = 1
+ IPV6 = 2
+
+
class Instance(proto.Message):
r"""A Memorystore instance.
@@ -2082,6 +2101,10 @@ class PscAutoConnection(proto.Message):
status.
connection_type (google.cloud.memorystore_v1beta.types.ConnectionType):
Output only. Type of the PSC connection.
+ ip_version (google.cloud.memorystore_v1beta.types.IpVersion):
+ Optional. Immutable. The IP version used for
+ the PSC auto-created endpoint. If not specified,
+ defaults to IPV4.
"""
port: int = proto.Field(
@@ -2123,6 +2146,11 @@ class PscAutoConnection(proto.Message):
number=8,
enum="ConnectionType",
)
+ ip_version: "IpVersion" = proto.Field(
+ proto.ENUM,
+ number=10,
+ enum="IpVersion",
+ )
class PscConnection(proto.Message):
diff --git a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1beta/test_memorystore.py b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1beta/test_memorystore.py
index c1d5640d2318..2500d5b20385 100644
--- a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1beta/test_memorystore.py
+++ b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1beta/test_memorystore.py
@@ -22076,6 +22076,7 @@ def test_create_instance_rest_call_success(request_type):
"service_attachment": "service_attachment_value",
"psc_connection_status": 1,
"connection_type": 1,
+ "ip_version": 1,
}
],
"psc_attachment_details": [
@@ -22642,6 +22643,7 @@ def test_update_instance_rest_call_success(request_type):
"service_attachment": "service_attachment_value",
"psc_connection_status": 1,
"connection_type": 1,
+ "ip_version": 1,
}
],
"psc_attachment_details": [
diff --git a/packages/google-cloud-modelarmor/google/cloud/modelarmor/__init__.py b/packages/google-cloud-modelarmor/google/cloud/modelarmor/__init__.py
index 2f06fd0312f6..7b31203e7cc9 100644
--- a/packages/google-cloud-modelarmor/google/cloud/modelarmor/__init__.py
+++ b/packages/google-cloud-modelarmor/google/cloud/modelarmor/__init__.py
@@ -27,6 +27,7 @@
ByteDataItem,
CreateTemplateRequest,
CsamFilterResult,
+ CsamFilterSettings,
DataItem,
DeleteTemplateRequest,
DetectionConfidenceLevel,
@@ -95,6 +96,7 @@
"ByteDataItem",
"CreateTemplateRequest",
"CsamFilterResult",
+ "CsamFilterSettings",
"DataItem",
"DeleteTemplateRequest",
"Dictionary",
diff --git a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/__init__.py b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/__init__.py
index 30c1121f2011..e3f01824053a 100644
--- a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/__init__.py
+++ b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/__init__.py
@@ -37,6 +37,7 @@
ByteDataItem,
CreateTemplateRequest,
CsamFilterResult,
+ CsamFilterSettings,
DataItem,
DeleteTemplateRequest,
DetectionConfidenceLevel,
@@ -104,6 +105,7 @@
"ByteDataItem",
"CreateTemplateRequest",
"CsamFilterResult",
+ "CsamFilterSettings",
"DataItem",
"DeleteTemplateRequest",
"DetectionConfidenceLevel",
diff --git a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/__init__.py b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/__init__.py
index fa0481b021d1..817043a6e210 100644
--- a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/__init__.py
+++ b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/__init__.py
@@ -18,6 +18,7 @@
ByteDataItem,
CreateTemplateRequest,
CsamFilterResult,
+ CsamFilterSettings,
DataItem,
DeleteTemplateRequest,
DetectionConfidenceLevel,
@@ -84,6 +85,7 @@
"ByteDataItem",
"CreateTemplateRequest",
"CsamFilterResult",
+ "CsamFilterSettings",
"DataItem",
"DeleteTemplateRequest",
"Dictionary",
diff --git a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py
index 998d7895b78c..93b709a94223 100644
--- a/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py
+++ b/packages/google-cloud-modelarmor/google/cloud/modelarmor_v1/types/service.py
@@ -50,6 +50,7 @@
"GetFloorSettingRequest",
"UpdateFloorSettingRequest",
"FilterConfig",
+ "CsamFilterSettings",
"PiAndJailbreakFilterSettings",
"MaliciousUriFilterSettings",
"RaiFilterSettings",
@@ -1100,7 +1101,10 @@ class FilterConfig(proto.Message):
filter_rule_settings (google.cloud.modelarmor_v1.types.FilterRuleSettings):
Optional. Settings for customizing filter
rules. Note: This field is not supported in
- FloorSetting and Streaming Sanitization APIs.
+ FloorSetting.
+ csam_filter_settings (google.cloud.modelarmor_v1.types.CsamFilterSettings):
+ Optional. Child sexual abuse material (CSAM)
+ filter settings.
"""
rai_settings: "RaiFilterSettings" = proto.Field(
@@ -1128,6 +1132,62 @@ class FilterConfig(proto.Message):
number=7,
message="FilterRuleSettings",
)
+ csam_filter_settings: "CsamFilterSettings" = proto.Field(
+ proto.MESSAGE,
+ number=9,
+ message="CsamFilterSettings",
+ )
+
+
+class CsamFilterSettings(proto.Message):
+ r"""Child sexual abuse material (CSAM) filter settings.
+
+ Attributes:
+ filter_enforcement (google.cloud.modelarmor_v1.types.CsamFilterSettings.CsamFilterEnforcement):
+ Optional. Specifies whether the CSAM filter
+ is enabled or disabled.
+ confidence_level (google.cloud.modelarmor_v1.types.DetectionConfidenceLevel):
+ Optional. Confidence level for this CSAM
+ filter. This field is used to determine the
+ threshold for the filter. If detection
+ confidence is greater than or equal to the
+ specified level, a positive match is reported.
+ Confidence level will only be used if the filter
+ is enabled.
+ """
+
+ class CsamFilterEnforcement(proto.Enum):
+ r"""Option to specify the enforcement state for the CSAM filter.
+
+ Values:
+ CSAM_FILTER_ENFORCEMENT_UNSPECIFIED (0):
+ Unused. Default value. If unspecified,
+ defaults to ENABLED (with HIGH confidence),
+ except for Data Residency (DRZ) compliant
+ resources in regions where CSAM detection is
+ unsupported, where it defaults to DISABLED.
+ ENABLED (1):
+ Enables CSAM detection filtering for user
+ prompts and model responses.
+ DISABLED (2):
+ Disables CSAM detection filtering for user
+ prompts and model responses.
+ """
+
+ CSAM_FILTER_ENFORCEMENT_UNSPECIFIED = 0
+ ENABLED = 1
+ DISABLED = 2
+
+ filter_enforcement: CsamFilterEnforcement = proto.Field(
+ proto.ENUM,
+ number=1,
+ enum=CsamFilterEnforcement,
+ )
+ confidence_level: "DetectionConfidenceLevel" = proto.Field(
+ proto.ENUM,
+ number=2,
+ enum="DetectionConfidenceLevel",
+ )
class PiAndJailbreakFilterSettings(proto.Message):
diff --git a/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py b/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py
index 02c9d270b962..06594e37851b 100644
--- a/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py
+++ b/packages/google-cloud-modelarmor/tests/unit/gapic/modelarmor_v1/test_model_armor.py
@@ -6884,6 +6884,7 @@ def test_create_template_rest_call_success(request_type):
}
]
},
+ "csam_filter_settings": {"filter_enforcement": 1, "confidence_level": 1},
},
"template_metadata": {
"ignore_partial_invocation_failures": True,
@@ -7138,6 +7139,7 @@ def test_update_template_rest_call_success(request_type):
}
]
},
+ "csam_filter_settings": {"filter_enforcement": 1, "confidence_level": 1},
},
"template_metadata": {
"ignore_partial_invocation_failures": True,
@@ -7633,6 +7635,7 @@ def test_update_floor_setting_rest_call_success(request_type):
}
]
},
+ "csam_filter_settings": {"filter_enforcement": 1, "confidence_level": 1},
},
"enable_floor_setting_enforcement": True,
"integrated_services": [1],
diff --git a/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py b/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py
index 9682272c5726..9cf11f604c23 100644
--- a/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py
+++ b/packages/google-cloud-network-management/google/cloud/network_management_v1/types/connectivity_test.py
@@ -252,6 +252,11 @@ class Endpoint(proto.Message):
Connection `__
name format:
projects/{project}/locations/{location}/privateConnections/{privateConnection}.
+ datastream_private_connection (str):
+ A `Datastream Private
+ Connection `__
+ name format:
+ projects/{project}/locations/{location}/privateConnections/{privateConnection}.
cloud_function (google.cloud.network_management_v1.types.Endpoint.CloudFunctionEndpoint):
A `Cloud Function `__.
Applicable only to source endpoint.
@@ -467,6 +472,10 @@ class CloudRunRevisionEndpoint(proto.Message):
proto.STRING,
number=22,
)
+ datastream_private_connection: str = proto.Field(
+ proto.STRING,
+ number=23,
+ )
cloud_function: CloudFunctionEndpoint = proto.Field(
proto.MESSAGE,
number=10,
diff --git a/packages/google-cloud-network-management/google/cloud/network_management_v1/types/trace.py b/packages/google-cloud-network-management/google/cloud/network_management_v1/types/trace.py
index 3d92f8254d67..86450c1a7119 100644
--- a/packages/google-cloud-network-management/google/cloud/network_management_v1/types/trace.py
+++ b/packages/google-cloud-network-management/google/cloud/network_management_v1/types/trace.py
@@ -376,6 +376,11 @@ class Step(proto.Message):
Display information of a DMS Private
Connection.
+ This field is a member of `oneof`_ ``step_info``.
+ datastream_private_connection (google.cloud.network_management_v1.types.PrivateConnectionInfo):
+ Display information of a Datastream Private
+ Connection.
+
This field is a member of `oneof`_ ``step_info``.
"""
@@ -454,6 +459,9 @@ class State(proto.Enum):
START_FROM_DMS_PRIVATE_CONNECTION (48):
Initial state: packet originating from a DMS
Private Connection.
+ START_FROM_DATASTREAM_PRIVATE_CONNECTION (49):
+ Initial state: packet originating from a
+ Datastream Private Connection.
APPLY_INGRESS_FIREWALL_RULE (4):
Config checking state: verify ingress
firewall rule.
@@ -567,6 +575,7 @@ class State(proto.Enum):
START_FROM_PSC_PUBLISHED_SERVICE = 30
START_FROM_SERVERLESS_NEG = 31
START_FROM_DMS_PRIVATE_CONNECTION = 48
+ START_FROM_DATASTREAM_PRIVATE_CONNECTION = 49
APPLY_INGRESS_FIREWALL_RULE = 4
APPLY_EGRESS_FIREWALL_RULE = 5
APPLY_ROUTE = 6
@@ -843,6 +852,12 @@ class State(proto.Enum):
oneof="step_info",
message="PrivateConnectionInfo",
)
+ datastream_private_connection: "PrivateConnectionInfo" = proto.Field(
+ proto.MESSAGE,
+ number=44,
+ oneof="step_info",
+ message="PrivateConnectionInfo",
+ )
class InstanceInfo(proto.Message):
@@ -2198,6 +2213,9 @@ class Target(proto.Enum):
DMS_PRIVATE_CONNECTION (21):
Target is a DMS Private Connection. Used only
for return traces.
+ DATASTREAM_PRIVATE_CONNECTION (22):
+ Target is a Datastream Private Connection.
+ Used only for return traces.
"""
TARGET_UNSPECIFIED = 0
@@ -2221,6 +2239,7 @@ class Target(proto.Enum):
GKE_POD = 19
CLOUD_RUN_JOB = 20
DMS_PRIVATE_CONNECTION = 21
+ DATASTREAM_PRIVATE_CONNECTION = 22
class GoogleServiceType(proto.Enum):
r"""Recognized type of a Google Service.
@@ -2783,6 +2802,9 @@ class Cause(proto.Enum):
DROPPED_INSIDE_DMS_PRIVATE_CONNECTION (114):
Packet was dropped inside DMS Private
Connection.
+ DROPPED_INSIDE_DATASTREAM_PRIVATE_CONNECTION (115):
+ Packet was dropped inside Datastream Private
+ Connection.
GOOGLE_MANAGED_SERVICE_NO_PEERING (20):
Packet was dropped because there is no
peering between the originating network and the
@@ -3089,6 +3111,7 @@ class Cause(proto.Enum):
DROPPED_INSIDE_GKE_SERVICE = 18
DROPPED_INSIDE_CLOUD_SQL_SERVICE = 19
DROPPED_INSIDE_DMS_PRIVATE_CONNECTION = 114
+ DROPPED_INSIDE_DATASTREAM_PRIVATE_CONNECTION = 115
GOOGLE_MANAGED_SERVICE_NO_PEERING = 20
GOOGLE_MANAGED_SERVICE_NO_PSC_ENDPOINT = 38
GKE_PSC_ENDPOINT_MISSING = 36
diff --git a/packages/google-cloud-network-management/tests/unit/gapic/network_management_v1/test_reachability_service.py b/packages/google-cloud-network-management/tests/unit/gapic/network_management_v1/test_reachability_service.py
index 89ef3cdc0632..9dc6670938bc 100644
--- a/packages/google-cloud-network-management/tests/unit/gapic/network_management_v1/test_reachability_service.py
+++ b/packages/google-cloud-network-management/tests/unit/gapic/network_management_v1/test_reachability_service.py
@@ -5253,6 +5253,7 @@ def test_create_connectivity_test_rest_call_success(request_type):
"redis_cluster": "redis_cluster_value",
"gke_pod": "gke_pod_value",
"dms_private_connection": "dms_private_connection_value",
+ "datastream_private_connection": "datastream_private_connection_value",
"cloud_function": {"uri": "uri_value"},
"app_engine_version": {"uri": "uri_value"},
"cloud_run_revision": {
@@ -5616,6 +5617,7 @@ def test_create_connectivity_test_rest_call_success(request_type):
"security_profile_group_uri": "security_profile_group_uri_value"
},
"dms_private_connection": {"uri": "uri_value"},
+ "datastream_private_connection": {},
}
],
"forward_trace_id": 1679,
@@ -5873,6 +5875,7 @@ def test_update_connectivity_test_rest_call_success(request_type):
"redis_cluster": "redis_cluster_value",
"gke_pod": "gke_pod_value",
"dms_private_connection": "dms_private_connection_value",
+ "datastream_private_connection": "datastream_private_connection_value",
"cloud_function": {"uri": "uri_value"},
"app_engine_version": {"uri": "uri_value"},
"cloud_run_revision": {
@@ -6236,6 +6239,7 @@ def test_update_connectivity_test_rest_call_success(request_type):
"security_profile_group_uri": "security_profile_group_uri_value"
},
"dms_private_connection": {"uri": "uri_value"},
+ "datastream_private_connection": {},
}
],
"forward_trace_id": 1679,
diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager/__init__.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager/__init__.py
index b26369987dca..8f3c3c36815c 100644
--- a/packages/google-cloud-secret-manager/google/cloud/secretmanager/__init__.py
+++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager/__init__.py
@@ -25,6 +25,7 @@
SecretManagerServiceClient,
)
from google.cloud.secretmanager_v1.types.resources import (
+ CloudSqlSingleUserCredentials,
CustomerManagedEncryption,
CustomerManagedEncryptionStatus,
Replication,
@@ -58,6 +59,7 @@
__all__ = (
"SecretManagerServiceClient",
"SecretManagerServiceAsyncClient",
+ "CloudSqlSingleUserCredentials",
"CustomerManagedEncryption",
"CustomerManagedEncryptionStatus",
"Replication",
diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/__init__.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/__init__.py
index f53329530e25..ee6bee3ce864 100644
--- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/__init__.py
+++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/__init__.py
@@ -37,6 +37,7 @@
SecretManagerServiceClient,
)
from .types.resources import (
+ CloudSqlSingleUserCredentials,
CustomerManagedEncryption,
CustomerManagedEncryptionStatus,
Replication,
@@ -72,6 +73,7 @@
"AccessSecretVersionRequest",
"AccessSecretVersionResponse",
"AddSecretVersionRequest",
+ "CloudSqlSingleUserCredentials",
"CreateSecretRequest",
"CustomerManagedEncryption",
"CustomerManagedEncryptionStatus",
diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py
index a8ce1fb2b56f..28b442f76496 100644
--- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py
+++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py
@@ -2152,7 +2152,7 @@ async def enable_managed_rotation(
*,
parent: Optional[str] = None,
cloud_sql_single_user_credentials: Optional[
- service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials
+ resources.CloudSqlSingleUserCredentials
] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
@@ -2180,7 +2180,7 @@ async def sample_enable_managed_rotation():
client = secretmanager_v1.SecretManagerServiceAsyncClient()
# Initialize request argument(s)
- cloud_sql_single_user_credentials = secretmanager_v1.CloudSQLSingleUserCredentials()
+ cloud_sql_single_user_credentials = secretmanager_v1.CloudSqlSingleUserCredentials()
cloud_sql_single_user_credentials.instance_id = "instance_id_value"
cloud_sql_single_user_credentials.username = "username_value"
@@ -2210,7 +2210,7 @@ async def sample_enable_managed_rotation():
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- cloud_sql_single_user_credentials (:class:`google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials`):
+ cloud_sql_single_user_credentials (:class:`google.cloud.secretmanager_v1.types.CloudSqlSingleUserCredentials`):
Credentials required for Cloud SQL DB
for Single user Managed Rotation.
diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/client.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/client.py
index 1fce45758368..d3b90decfc34 100644
--- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/client.py
+++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/client.py
@@ -2437,7 +2437,7 @@ def enable_managed_rotation(
*,
parent: Optional[str] = None,
cloud_sql_single_user_credentials: Optional[
- service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials
+ resources.CloudSqlSingleUserCredentials
] = None,
retry: OptionalRetry = gapic_v1.method.DEFAULT,
timeout: Union[float, object] = gapic_v1.method.DEFAULT,
@@ -2465,7 +2465,7 @@ def sample_enable_managed_rotation():
client = secretmanager_v1.SecretManagerServiceClient()
# Initialize request argument(s)
- cloud_sql_single_user_credentials = secretmanager_v1.CloudSQLSingleUserCredentials()
+ cloud_sql_single_user_credentials = secretmanager_v1.CloudSqlSingleUserCredentials()
cloud_sql_single_user_credentials.instance_id = "instance_id_value"
cloud_sql_single_user_credentials.username = "username_value"
@@ -2495,7 +2495,7 @@ def sample_enable_managed_rotation():
This corresponds to the ``parent`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
- cloud_sql_single_user_credentials (google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials):
+ cloud_sql_single_user_credentials (google.cloud.secretmanager_v1.types.CloudSqlSingleUserCredentials):
Credentials required for Cloud SQL DB
for Single user Managed Rotation.
diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py
index 56f5387d9beb..2cab6dc89fb1 100644
--- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py
+++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py
@@ -231,12 +231,12 @@ def _prep_wrapped_messages(self, client_info):
),
self.enable_managed_rotation: gapic_v1.method.wrap_method(
self.enable_managed_rotation,
- default_timeout=None,
+ default_timeout=60.0,
client_info=client_info,
),
self.rotate_secret: gapic_v1.method.wrap_method(
self.rotate_secret,
- default_timeout=None,
+ default_timeout=60.0,
client_info=client_info,
),
self.get_location: gapic_v1.method.wrap_method(
diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py
index fb45b3337f4d..2488c53cc589 100644
--- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py
@@ -960,12 +960,12 @@ def _prep_wrapped_messages(self, client_info):
),
self.enable_managed_rotation: self._wrap_method(
self.enable_managed_rotation,
- default_timeout=None,
+ default_timeout=60.0,
client_info=client_info,
),
self.rotate_secret: self._wrap_method(
self.rotate_secret,
- default_timeout=None,
+ default_timeout=60.0,
client_info=client_info,
),
self.get_location: self._wrap_method(
diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/__init__.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/__init__.py
index 49146e3f6fef..c39651bcb159 100644
--- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/__init__.py
+++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/__init__.py
@@ -14,6 +14,7 @@
# limitations under the License.
#
from .resources import (
+ CloudSqlSingleUserCredentials,
CustomerManagedEncryption,
CustomerManagedEncryptionStatus,
Replication,
@@ -45,6 +46,7 @@
)
__all__ = (
+ "CloudSqlSingleUserCredentials",
"CustomerManagedEncryption",
"CustomerManagedEncryptionStatus",
"Replication",
diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/resources.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/resources.py
index a5b8abee7a51..3f7ee7a251cf 100644
--- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/resources.py
+++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/resources.py
@@ -35,6 +35,7 @@
"Topic",
"Rotation",
"SecretPayload",
+ "CloudSqlSingleUserCredentials",
},
)
@@ -885,4 +886,34 @@ class SecretPayload(proto.Message):
)
+class CloudSqlSingleUserCredentials(proto.Message):
+ r"""These are the credentials required for Cloud SQL DB for
+ Single user Managed Rotation.
+
+ Attributes:
+ instance_id (str):
+ Required. Instance ID of the Cloud SQL
+ instance.
+ username (str):
+ Required. Username of the Cloud SQL instance.
+ password (str):
+ Optional. Password of the Cloud SQL instance.
+ If this is not provided, a random password will
+ be generated.
+ """
+
+ instance_id: str = proto.Field(
+ proto.STRING,
+ number=1,
+ )
+ username: str = proto.Field(
+ proto.STRING,
+ number=2,
+ )
+ password: str = proto.Field(
+ proto.STRING,
+ number=3,
+ )
+
+
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/service.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/service.py
index 717dc0559ebf..46bb8f20fbb5 100644
--- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/service.py
+++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/service.py
@@ -209,51 +209,24 @@ class EnableManagedRotationRequest(proto.Message):
[SecretVersion][google.cloud.secretmanager.v1.SecretVersion]
in the format ``projects/*/secrets/*`` or
``projects/*/locations/*/secrets/*``.
- cloud_sql_single_user_credentials (google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials):
+ cloud_sql_single_user_credentials (google.cloud.secretmanager_v1.types.CloudSqlSingleUserCredentials):
Credentials required for Cloud SQL DB for
Single user Managed Rotation.
- This field is a member of `oneof`_ ``credentials``.
+ This field is a member of `oneof`_ ``credential``.
"""
- class CloudSQLSingleUserCredentials(proto.Message):
- r"""These are the credentials required for Cloud SQL DB for
- Single user Managed Rotation.
-
- Attributes:
- instance_id (str):
- Required. Instance ID of the Cloud SQL
- instance.
- username (str):
- Required. Username of the Cloud SQL instance.
- password (str):
- Optional. Password of the Cloud SQL instance.
- If this is not provided, a random password will
- be generated.
- """
-
- instance_id: str = proto.Field(
- proto.STRING,
- number=1,
- )
- username: str = proto.Field(
- proto.STRING,
- number=2,
- )
- password: str = proto.Field(
- proto.STRING,
- number=3,
- )
-
parent: str = proto.Field(
proto.STRING,
number=1,
)
- cloud_sql_single_user_credentials: CloudSQLSingleUserCredentials = proto.Field(
- proto.MESSAGE,
- number=2,
- oneof="credentials",
- message=CloudSQLSingleUserCredentials,
+ cloud_sql_single_user_credentials: resources.CloudSqlSingleUserCredentials = (
+ proto.Field(
+ proto.MESSAGE,
+ number=2,
+ oneof="credential",
+ message=resources.CloudSqlSingleUserCredentials,
+ )
)
diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_async.py b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_async.py
index 0fe0148061bd..989ced7d0ce6 100644
--- a/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_async.py
+++ b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_async.py
@@ -39,7 +39,7 @@ async def sample_enable_managed_rotation():
client = secretmanager_v1.SecretManagerServiceAsyncClient()
# Initialize request argument(s)
- cloud_sql_single_user_credentials = secretmanager_v1.CloudSQLSingleUserCredentials()
+ cloud_sql_single_user_credentials = secretmanager_v1.CloudSqlSingleUserCredentials()
cloud_sql_single_user_credentials.instance_id = "instance_id_value"
cloud_sql_single_user_credentials.username = "username_value"
diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_sync.py b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_sync.py
index d8a702d5cfaf..d61b56aea3c8 100644
--- a/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_sync.py
+++ b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_sync.py
@@ -39,7 +39,7 @@ def sample_enable_managed_rotation():
client = secretmanager_v1.SecretManagerServiceClient()
# Initialize request argument(s)
- cloud_sql_single_user_credentials = secretmanager_v1.CloudSQLSingleUserCredentials()
+ cloud_sql_single_user_credentials = secretmanager_v1.CloudSqlSingleUserCredentials()
cloud_sql_single_user_credentials.instance_id = "instance_id_value"
cloud_sql_single_user_credentials.username = "username_value"
diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json b/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json
index be53dd3c80eb..43da0f77d690 100644
--- a/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json
+++ b/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json
@@ -1023,7 +1023,7 @@
},
{
"name": "cloud_sql_single_user_credentials",
- "type": "google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials"
+ "type": "google.cloud.secretmanager_v1.types.CloudSqlSingleUserCredentials"
},
{
"name": "retry",
@@ -1107,7 +1107,7 @@
},
{
"name": "cloud_sql_single_user_credentials",
- "type": "google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials"
+ "type": "google.cloud.secretmanager_v1.types.CloudSqlSingleUserCredentials"
},
{
"name": "retry",
diff --git a/packages/google-cloud-secret-manager/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py b/packages/google-cloud-secret-manager/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py
index 01d17df2d37e..3760ea5ab4fb 100644
--- a/packages/google-cloud-secret-manager/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py
+++ b/packages/google-cloud-secret-manager/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py
@@ -6748,7 +6748,7 @@ def test_enable_managed_rotation_flattened():
# using the keyword arguments to the method.
client.enable_managed_rotation(
parent="parent_value",
- cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials(
+ cloud_sql_single_user_credentials=resources.CloudSqlSingleUserCredentials(
instance_id="instance_id_value"
),
)
@@ -6760,11 +6760,10 @@ def test_enable_managed_rotation_flattened():
arg = args[0].parent
mock_val = "parent_value"
assert arg == mock_val
- assert (
- args[0].cloud_sql_single_user_credentials
- == service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials(
- instance_id="instance_id_value"
- )
+ assert args[
+ 0
+ ].cloud_sql_single_user_credentials == resources.CloudSqlSingleUserCredentials(
+ instance_id="instance_id_value"
)
@@ -6779,7 +6778,7 @@ def test_enable_managed_rotation_flattened_error():
client.enable_managed_rotation(
service.EnableManagedRotationRequest(),
parent="parent_value",
- cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials(
+ cloud_sql_single_user_credentials=resources.CloudSqlSingleUserCredentials(
instance_id="instance_id_value"
),
)
@@ -6805,7 +6804,7 @@ async def test_enable_managed_rotation_flattened_async():
# using the keyword arguments to the method.
response = await client.enable_managed_rotation(
parent="parent_value",
- cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials(
+ cloud_sql_single_user_credentials=resources.CloudSqlSingleUserCredentials(
instance_id="instance_id_value"
),
)
@@ -6817,11 +6816,10 @@ async def test_enable_managed_rotation_flattened_async():
arg = args[0].parent
mock_val = "parent_value"
assert arg == mock_val
- assert (
- args[0].cloud_sql_single_user_credentials
- == service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials(
- instance_id="instance_id_value"
- )
+ assert args[
+ 0
+ ].cloud_sql_single_user_credentials == resources.CloudSqlSingleUserCredentials(
+ instance_id="instance_id_value"
)
@@ -6837,7 +6835,7 @@ async def test_enable_managed_rotation_flattened_error_async():
await client.enable_managed_rotation(
service.EnableManagedRotationRequest(),
parent="parent_value",
- cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials(
+ cloud_sql_single_user_credentials=resources.CloudSqlSingleUserCredentials(
instance_id="instance_id_value"
),
)
@@ -9902,7 +9900,7 @@ def test_enable_managed_rotation_rest_flattened_error(transport: str = "rest"):
client.enable_managed_rotation(
service.EnableManagedRotationRequest(),
parent="parent_value",
- cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials(
+ cloud_sql_single_user_credentials=resources.CloudSqlSingleUserCredentials(
instance_id="instance_id_value"
),
)
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/async_client.py
index 129f18d56229..89ed58919711 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/async_client.py
@@ -74,7 +74,9 @@
class SqlBackupsServiceAsyncClient:
- """"""
+ """Service for managing database backups for Cloud SQL
+ instances.
+ """
_client: SqlBackupsServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/client.py
index 855944baefc5..b46d4f40b5d0 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/client.py
@@ -123,7 +123,9 @@ def get_transport_class(
class SqlBackupsServiceClient(metaclass=SqlBackupsServiceClientMeta):
- """"""
+ """Service for managing database backups for Cloud SQL
+ instances.
+ """
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/transports/grpc.py
index c1aed13a2570..e3ad4695b854 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/transports/grpc.py
@@ -112,6 +112,9 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlBackupsServiceGrpcTransport(SqlBackupsServiceTransport):
"""gRPC backend transport for SqlBackupsService.
+ Service for managing database backups for Cloud SQL
+ instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/transports/grpc_asyncio.py
index 3496be3e17e1..4697d81093e7 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_backups_service/transports/grpc_asyncio.py
@@ -118,6 +118,9 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlBackupsServiceGrpcAsyncIOTransport(SqlBackupsServiceTransport):
"""gRPC AsyncIO backend transport for SqlBackupsService.
+ Service for managing database backups for Cloud SQL
+ instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/async_client.py
index 6e76212204e7..f0ff86b6ca1c 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/async_client.py
@@ -68,7 +68,7 @@
class SqlInstancesServiceAsyncClient:
- """"""
+ """Service to manage Cloud SQL instances."""
_client: SqlInstancesServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/client.py
index cb190ffcab77..3a14a927e928 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/client.py
@@ -117,7 +117,7 @@ def get_transport_class(
class SqlInstancesServiceClient(metaclass=SqlInstancesServiceClientMeta):
- """"""
+ """Service to manage Cloud SQL instances."""
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/transports/grpc.py
index 1bfdcf858808..92cb3f30c3f4 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/transports/grpc.py
@@ -112,6 +112,8 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlInstancesServiceGrpcTransport(SqlInstancesServiceTransport):
"""gRPC backend transport for SqlInstancesService.
+ Service to manage Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/transports/grpc_asyncio.py
index ce04a9084b89..af954bbd11e3 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1/services/sql_instances_service/transports/grpc_asyncio.py
@@ -118,6 +118,8 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlInstancesServiceGrpcAsyncIOTransport(SqlInstancesServiceTransport):
"""gRPC AsyncIO backend transport for SqlInstancesService.
+ Service to manage Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/async_client.py
index 66dc41748eba..4bd0abc6db4f 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/async_client.py
@@ -66,7 +66,7 @@
class SqlBackupRunsServiceAsyncClient:
- """"""
+ """Service for managing database backups."""
_client: SqlBackupRunsServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/client.py
index c224979a5bd1..ffc5d3166459 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/client.py
@@ -117,7 +117,7 @@ def get_transport_class(
class SqlBackupRunsServiceClient(metaclass=SqlBackupRunsServiceClientMeta):
- """"""
+ """Service for managing database backups."""
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/grpc.py
index 435fa2e05631..bf5c71499ae3 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/grpc.py
@@ -112,6 +112,8 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlBackupRunsServiceGrpcTransport(SqlBackupRunsServiceTransport):
"""gRPC backend transport for SqlBackupRunsService.
+ Service for managing database backups.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/grpc_asyncio.py
index dc33d35640b1..ee2098878a91 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/grpc_asyncio.py
@@ -118,6 +118,8 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlBackupRunsServiceGrpcAsyncIOTransport(SqlBackupRunsServiceTransport):
"""gRPC AsyncIO backend transport for SqlBackupRunsService.
+ Service for managing database backups.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/rest.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/rest.py
index 4f580d55e88d..56703a8fac80 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/rest.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backup_runs_service/transports/rest.py
@@ -318,6 +318,8 @@ class SqlBackupRunsServiceRestStub:
class SqlBackupRunsServiceRestTransport(_BaseSqlBackupRunsServiceRestTransport):
"""REST backend synchronous transport for SqlBackupRunsService.
+ Service for managing database backups.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/async_client.py
index 4859266323c6..62b39dbb9122 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/async_client.py
@@ -69,7 +69,9 @@
class SqlBackupsServiceAsyncClient:
- """"""
+ """Service for managing database backups for Cloud SQL
+ instances.
+ """
_client: SqlBackupsServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/client.py
index e1bd7ae79f0c..15dc50ea9d4e 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/client.py
@@ -120,7 +120,9 @@ def get_transport_class(
class SqlBackupsServiceClient(metaclass=SqlBackupsServiceClientMeta):
- """"""
+ """Service for managing database backups for Cloud SQL
+ instances.
+ """
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/grpc.py
index 7cce5ae3b5c8..43b248160239 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/grpc.py
@@ -112,6 +112,9 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlBackupsServiceGrpcTransport(SqlBackupsServiceTransport):
"""gRPC backend transport for SqlBackupsService.
+ Service for managing database backups for Cloud SQL
+ instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/grpc_asyncio.py
index 4a7f14d4cdb8..838a6a60287c 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/grpc_asyncio.py
@@ -118,6 +118,9 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlBackupsServiceGrpcAsyncIOTransport(SqlBackupsServiceTransport):
"""gRPC AsyncIO backend transport for SqlBackupsService.
+ Service for managing database backups for Cloud SQL
+ instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/rest.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/rest.py
index 55f4c243408a..5decae878dde 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/rest.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_backups_service/transports/rest.py
@@ -361,6 +361,9 @@ class SqlBackupsServiceRestStub:
class SqlBackupsServiceRestTransport(_BaseSqlBackupsServiceRestTransport):
"""REST backend synchronous transport for SqlBackupsService.
+ Service for managing database backups for Cloud SQL
+ instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/async_client.py
index 0b3126fd8f59..f548480d0fb3 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/async_client.py
@@ -65,7 +65,7 @@
class SqlDatabasesServiceAsyncClient:
- """"""
+ """Service to manage databases."""
_client: SqlDatabasesServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/client.py
index 6027238560a4..afda780e83e7 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/client.py
@@ -116,7 +116,7 @@ def get_transport_class(
class SqlDatabasesServiceClient(metaclass=SqlDatabasesServiceClientMeta):
- """"""
+ """Service to manage databases."""
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/grpc.py
index 7e0378794ad2..9877e07c6926 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/grpc.py
@@ -112,6 +112,8 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlDatabasesServiceGrpcTransport(SqlDatabasesServiceTransport):
"""gRPC backend transport for SqlDatabasesService.
+ Service to manage databases.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/grpc_asyncio.py
index 78177d2961b1..f02b4683378b 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/grpc_asyncio.py
@@ -118,6 +118,8 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlDatabasesServiceGrpcAsyncIOTransport(SqlDatabasesServiceTransport):
"""gRPC AsyncIO backend transport for SqlDatabasesService.
+ Service to manage databases.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/rest.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/rest.py
index d34344a50180..87d13e76c6a0 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/rest.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_databases_service/transports/rest.py
@@ -430,6 +430,8 @@ class SqlDatabasesServiceRestStub:
class SqlDatabasesServiceRestTransport(_BaseSqlDatabasesServiceRestTransport):
"""REST backend synchronous transport for SqlDatabasesService.
+ Service to manage databases.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/async_client.py
index e872e049d136..f0fa8a47a4fd 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/async_client.py
@@ -64,7 +64,7 @@
class SqlFlagsServiceAsyncClient:
- """"""
+ """Service to manage database flags for Cloud SQL instances."""
_client: SqlFlagsServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/client.py
index 0120e13e8437..1c01cc5b51fa 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/client.py
@@ -115,7 +115,7 @@ def get_transport_class(
class SqlFlagsServiceClient(metaclass=SqlFlagsServiceClientMeta):
- """"""
+ """Service to manage database flags for Cloud SQL instances."""
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/grpc.py
index 29f27f307a71..daf76ac1f95c 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/grpc.py
@@ -112,6 +112,8 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlFlagsServiceGrpcTransport(SqlFlagsServiceTransport):
"""gRPC backend transport for SqlFlagsService.
+ Service to manage database flags for Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/grpc_asyncio.py
index 076de0ff84e0..72d45f571a04 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/grpc_asyncio.py
@@ -118,6 +118,8 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlFlagsServiceGrpcAsyncIOTransport(SqlFlagsServiceTransport):
"""gRPC AsyncIO backend transport for SqlFlagsService.
+ Service to manage database flags for Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/rest.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/rest.py
index eb03db907c88..5fdca1565092 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/rest.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_flags_service/transports/rest.py
@@ -147,6 +147,8 @@ class SqlFlagsServiceRestStub:
class SqlFlagsServiceRestTransport(_BaseSqlFlagsServiceRestTransport):
"""REST backend synchronous transport for SqlFlagsService.
+ Service to manage database flags for Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/async_client.py
index 08f555b982cc..ecefb65bb827 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/async_client.py
@@ -68,7 +68,7 @@
class SqlInstancesServiceAsyncClient:
- """"""
+ """Service to manage Cloud SQL instances."""
_client: SqlInstancesServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/client.py
index 38b0fa8dc465..5389e6e10c1c 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/client.py
@@ -119,7 +119,7 @@ def get_transport_class(
class SqlInstancesServiceClient(metaclass=SqlInstancesServiceClientMeta):
- """"""
+ """Service to manage Cloud SQL instances."""
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/grpc.py
index 4927a095aec2..4ee15b5ab6fa 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/grpc.py
@@ -112,6 +112,8 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlInstancesServiceGrpcTransport(SqlInstancesServiceTransport):
"""gRPC backend transport for SqlInstancesService.
+ Service to manage Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/grpc_asyncio.py
index 2a461414073d..b48a919e1e78 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/grpc_asyncio.py
@@ -118,6 +118,8 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlInstancesServiceGrpcAsyncIOTransport(SqlInstancesServiceTransport):
"""gRPC AsyncIO backend transport for SqlInstancesService.
+ Service to manage Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/rest.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/rest.py
index b9df8399ae27..51bb2aead03f 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/rest.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_instances_service/transports/rest.py
@@ -2560,6 +2560,8 @@ class SqlInstancesServiceRestStub:
class SqlInstancesServiceRestTransport(_BaseSqlInstancesServiceRestTransport):
"""REST backend synchronous transport for SqlInstancesService.
+ Service to manage Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/async_client.py
index 8e1235424fea..5d21c8b62a5c 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/async_client.py
@@ -66,7 +66,7 @@
class SqlOperationsServiceAsyncClient:
- """"""
+ """Service to fetch operations for database instances."""
_client: SqlOperationsServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/client.py
index fec2a8d13fd3..1e7af27f07e2 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/client.py
@@ -117,7 +117,7 @@ def get_transport_class(
class SqlOperationsServiceClient(metaclass=SqlOperationsServiceClientMeta):
- """"""
+ """Service to fetch operations for database instances."""
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/grpc.py
index d46797887ca3..f01eda553158 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/grpc.py
@@ -113,6 +113,8 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlOperationsServiceGrpcTransport(SqlOperationsServiceTransport):
"""gRPC backend transport for SqlOperationsService.
+ Service to fetch operations for database instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/grpc_asyncio.py
index 3164c94236be..3707e1bfb18c 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/grpc_asyncio.py
@@ -119,6 +119,8 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlOperationsServiceGrpcAsyncIOTransport(SqlOperationsServiceTransport):
"""gRPC AsyncIO backend transport for SqlOperationsService.
+ Service to fetch operations for database instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/rest.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/rest.py
index 388ca6b21dd2..90c69a870291 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/rest.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_operations_service/transports/rest.py
@@ -225,6 +225,8 @@ class SqlOperationsServiceRestStub:
class SqlOperationsServiceRestTransport(_BaseSqlOperationsServiceRestTransport):
"""REST backend synchronous transport for SqlOperationsService.
+ Service to fetch operations for database instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/async_client.py
index 52d38b94f812..a4062c62fb53 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/async_client.py
@@ -65,7 +65,7 @@
class SqlSslCertsServiceAsyncClient:
- """"""
+ """Service to manage SSL certs for Cloud SQL instances."""
_client: SqlSslCertsServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/client.py
index c90cd9ed9edc..424119339633 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/client.py
@@ -116,7 +116,7 @@ def get_transport_class(
class SqlSslCertsServiceClient(metaclass=SqlSslCertsServiceClientMeta):
- """"""
+ """Service to manage SSL certs for Cloud SQL instances."""
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/grpc.py
index 6048611eb505..9ed849977a1e 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/grpc.py
@@ -112,6 +112,8 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlSslCertsServiceGrpcTransport(SqlSslCertsServiceTransport):
"""gRPC backend transport for SqlSslCertsService.
+ Service to manage SSL certs for Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/grpc_asyncio.py
index 29f952fd9ac1..4dfe0686bed0 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/grpc_asyncio.py
@@ -118,6 +118,8 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlSslCertsServiceGrpcAsyncIOTransport(SqlSslCertsServiceTransport):
"""gRPC AsyncIO backend transport for SqlSslCertsService.
+ Service to manage SSL certs for Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/rest.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/rest.py
index aa478b6c19d1..5650a4dd994d 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/rest.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_ssl_certs_service/transports/rest.py
@@ -321,6 +321,8 @@ class SqlSslCertsServiceRestStub:
class SqlSslCertsServiceRestTransport(_BaseSqlSslCertsServiceRestTransport):
"""REST backend synchronous transport for SqlSslCertsService.
+ Service to manage SSL certs for Cloud SQL instances.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/async_client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/async_client.py
index dc9796add354..85c85c4b0335 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/async_client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/async_client.py
@@ -65,7 +65,7 @@
class SqlUsersServiceAsyncClient:
- """"""
+ """Cloud SQL users service."""
_client: SqlUsersServiceClient
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/client.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/client.py
index a6514e634364..41208222c9b9 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/client.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/client.py
@@ -116,7 +116,7 @@ def get_transport_class(
class SqlUsersServiceClient(metaclass=SqlUsersServiceClientMeta):
- """"""
+ """Cloud SQL users service."""
# Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
DEFAULT_ENDPOINT = "sqladmin.googleapis.com"
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/grpc.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/grpc.py
index 6e1008192825..b7c6094428ae 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/grpc.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/grpc.py
@@ -112,6 +112,8 @@ def intercept_unary_unary(self, continuation, client_call_details, request):
class SqlUsersServiceGrpcTransport(SqlUsersServiceTransport):
"""gRPC backend transport for SqlUsersService.
+ Cloud SQL users service.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/grpc_asyncio.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/grpc_asyncio.py
index 274f0d23ce7b..308a8ec679e3 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/grpc_asyncio.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/grpc_asyncio.py
@@ -118,6 +118,8 @@ async def intercept_unary_unary(self, continuation, client_call_details, request
class SqlUsersServiceGrpcAsyncIOTransport(SqlUsersServiceTransport):
"""gRPC AsyncIO backend transport for SqlUsersService.
+ Cloud SQL users service.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/rest.py b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/rest.py
index 462a8b9cc488..10198d28f648 100644
--- a/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/rest.py
+++ b/packages/google-cloud-sql/google/cloud/sqladmin_v1beta4/services/sql_users_service/transports/rest.py
@@ -371,6 +371,8 @@ class SqlUsersServiceRestStub:
class SqlUsersServiceRestTransport(_BaseSqlUsersServiceRestTransport):
"""REST backend synchronous transport for SqlUsersService.
+ Cloud SQL users service.
+
This class defines the same methods as the primary client, so the
primary client can load the underlying transport implementation
and call it.
diff --git a/packages/google-maps-navconnect/.repo-metadata.json b/packages/google-maps-navconnect/.repo-metadata.json
index cdbfaaff6f2a..142d1fec9da9 100644
--- a/packages/google-maps-navconnect/.repo-metadata.json
+++ b/packages/google-maps-navconnect/.repo-metadata.json
@@ -1,5 +1,5 @@
{
- "api_description": "Navigation Connect API.",
+ "api_description": "Navigate and track trips seamlessly with Google Maps or Waze.",
"api_id": "navigationconnect.googleapis.com",
"api_shortname": "navigationconnect",
"client_documentation": "https://googleapis.dev/python/google-maps-navconnect/latest",
diff --git a/packages/google-maps-navconnect/README.rst b/packages/google-maps-navconnect/README.rst
index e5b3d8d63fca..6ccad80643f3 100644
--- a/packages/google-maps-navconnect/README.rst
+++ b/packages/google-maps-navconnect/README.rst
@@ -3,7 +3,7 @@ Python Client for Navigation Connect
|preview| |pypi| |versions|
-`Navigation Connect`_: Navigation Connect API.
+`Navigation Connect`_: Navigate and track trips seamlessly with Google Maps or Waze.
- `Client Library Documentation`_
- `Product Documentation`_
diff --git a/packages/google-maps-navconnect/docs/README.rst b/packages/google-maps-navconnect/docs/README.rst
index e5b3d8d63fca..6ccad80643f3 100644
--- a/packages/google-maps-navconnect/docs/README.rst
+++ b/packages/google-maps-navconnect/docs/README.rst
@@ -3,7 +3,7 @@ Python Client for Navigation Connect
|preview| |pypi| |versions|
-`Navigation Connect`_: Navigation Connect API.
+`Navigation Connect`_: Navigate and track trips seamlessly with Google Maps or Waze.
- `Client Library Documentation`_
- `Product Documentation`_
diff --git a/packages/google-maps-navconnect/google/maps/navconnect/__init__.py b/packages/google-maps-navconnect/google/maps/navconnect/__init__.py
index 6a850bfbf2ac..3a80a5336a35 100644
--- a/packages/google-maps-navconnect/google/maps/navconnect/__init__.py
+++ b/packages/google-maps-navconnect/google/maps/navconnect/__init__.py
@@ -29,6 +29,10 @@
CreateTripRequest,
GetTripRequest,
Location,
+ Route,
+ RouteDeviation,
+ SimplePolyline,
+ SpeedReadingInterval,
Stop,
Trip,
TripConfig,
@@ -42,6 +46,10 @@
"CreateTripRequest",
"GetTripRequest",
"Location",
+ "Route",
+ "RouteDeviation",
+ "SimplePolyline",
+ "SpeedReadingInterval",
"Stop",
"Trip",
"TripConfig",
diff --git a/packages/google-maps-navconnect/google/maps/navconnect_v1/__init__.py b/packages/google-maps-navconnect/google/maps/navconnect_v1/__init__.py
index 7a9fc8f7e095..b71c0307c732 100644
--- a/packages/google-maps-navconnect/google/maps/navconnect_v1/__init__.py
+++ b/packages/google-maps-navconnect/google/maps/navconnect_v1/__init__.py
@@ -40,6 +40,10 @@
CreateTripRequest,
GetTripRequest,
Location,
+ Route,
+ RouteDeviation,
+ SimplePolyline,
+ SpeedReadingInterval,
Stop,
Trip,
TripConfig,
@@ -53,6 +57,10 @@
"GetTripRequest",
"Location",
"NavConnectServiceClient",
+ "Route",
+ "RouteDeviation",
+ "SimplePolyline",
+ "SpeedReadingInterval",
"Stop",
"Trip",
"TripConfig",
diff --git a/packages/google-maps-navconnect/google/maps/navconnect_v1/types/__init__.py b/packages/google-maps-navconnect/google/maps/navconnect_v1/types/__init__.py
index ab0d0e90ff01..4054edce62d3 100644
--- a/packages/google-maps-navconnect/google/maps/navconnect_v1/types/__init__.py
+++ b/packages/google-maps-navconnect/google/maps/navconnect_v1/types/__init__.py
@@ -18,6 +18,10 @@
CreateTripRequest,
GetTripRequest,
Location,
+ Route,
+ RouteDeviation,
+ SimplePolyline,
+ SpeedReadingInterval,
Stop,
Trip,
TripConfig,
@@ -29,6 +33,10 @@
"CreateTripRequest",
"GetTripRequest",
"Location",
+ "Route",
+ "RouteDeviation",
+ "SimplePolyline",
+ "SpeedReadingInterval",
"Stop",
"Trip",
"TripConfig",
diff --git a/packages/google-maps-navconnect/google/maps/navconnect_v1/types/navconnect_service.py b/packages/google-maps-navconnect/google/maps/navconnect_v1/types/navconnect_service.py
index 660651489679..0c3c07400240 100644
--- a/packages/google-maps-navconnect/google/maps/navconnect_v1/types/navconnect_service.py
+++ b/packages/google-maps-navconnect/google/maps/navconnect_v1/types/navconnect_service.py
@@ -19,6 +19,7 @@
import google.protobuf.duration_pb2 as duration_pb2 # type: ignore
import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.protobuf.struct_pb2 as struct_pb2 # type: ignore
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
import google.type.latlng_pb2 as latlng_pb2 # type: ignore
import proto # type: ignore
@@ -30,8 +31,12 @@
"TripConfig",
"AuthToken",
"TripExecution",
+ "RouteDeviation",
"Stop",
"Location",
+ "SimplePolyline",
+ "SpeedReadingInterval",
+ "Route",
"CreateTripRequest",
"GetTripRequest",
},
@@ -152,7 +157,7 @@ class TripConfig(proto.Message):
Attributes:
enable_high_frequency_updates (bool):
- Optional. Whether to enable high frequency
+ Optional. Whether to enable high-frequency
trip updates.
NOTE: Enabling this feature logs the trip under
Enterprise Tier usage, and is subject to
@@ -175,6 +180,18 @@ class TripConfig(proto.Message):
- ``config``
NOTE: This field is ignored if ``enable_pubsub`` is false.
+ enable_remaining_route_reporting (bool):
+ Optional. Whether to enable remaining route
+ reporting for the trip.
+ NOTE: Enabling this feature logs the trip under
+ Enterprise Tier usage, and is subject to
+ Enterprise Tier rates.
+ enable_route_deviation_reporting (bool):
+ Optional. Whether to enable route deviation
+ reporting for the trip.
+ NOTE: Enabling this feature logs the trip under
+ Enterprise Tier usage, and is subject to
+ Enterprise Tier rates.
"""
enable_high_frequency_updates: bool = proto.Field(
@@ -190,6 +207,14 @@ class TripConfig(proto.Message):
number=3,
message=field_mask_pb2.FieldMask,
)
+ enable_remaining_route_reporting: bool = proto.Field(
+ proto.BOOL,
+ number=4,
+ )
+ enable_route_deviation_reporting: bool = proto.Field(
+ proto.BOOL,
+ number=5,
+ )
class AuthToken(proto.Message):
@@ -232,6 +257,12 @@ class TripExecution(proto.Message):
Output only. The location signal representing
the last known location of the transporter. This
will be the road snapped location if available.
+ remaining_route (google.maps.navconnect_v1.types.Route):
+ Output only. Provides the polyline for the
+ remaining portion of the route.
+ last_route_deviation (google.maps.navconnect_v1.types.RouteDeviation):
+ Output only. The most recent route deviation
+ event captured during the trip.
traveled_duration (google.protobuf.duration_pb2.Duration):
Output only. Time traveled thus far.
remaining_duration (google.protobuf.duration_pb2.Duration):
@@ -269,6 +300,16 @@ class TripExecution(proto.Message):
number=3,
message="Location",
)
+ remaining_route: "Route" = proto.Field(
+ proto.MESSAGE,
+ number=9,
+ message="Route",
+ )
+ last_route_deviation: "RouteDeviation" = proto.Field(
+ proto.MESSAGE,
+ number=10,
+ message="RouteDeviation",
+ )
traveled_duration: duration_pb2.Duration = proto.Field(
proto.MESSAGE,
number=4,
@@ -296,6 +337,48 @@ class TripExecution(proto.Message):
)
+class RouteDeviation(proto.Message):
+ r"""Route deviation information.
+
+ Attributes:
+ location (google.maps.navconnect_v1.types.Location):
+ Output only. Location where the deviation
+ occurred.
+ source (google.maps.navconnect_v1.types.RouteDeviation.TriggerSource):
+ Output only. Source for the deviation
+ trigger.
+ """
+
+ class TriggerSource(proto.Enum):
+ r"""The source that triggered the route deviation.
+
+ Values:
+ TRIGGER_SOURCE_UNSPECIFIED (0):
+ The trigger source is unspecified.
+ DRIVER_INITIATED_REROUTE (1):
+ The route deviation was triggered by the
+ driver (e.g. wrong turn).
+ SYSTEM_INITIATED_REROUTE (2):
+ The route deviation was triggered by the
+ system (e.g. traffic closure).
+ """
+
+ TRIGGER_SOURCE_UNSPECIFIED = 0
+ DRIVER_INITIATED_REROUTE = 1
+ SYSTEM_INITIATED_REROUTE = 2
+
+ location: "Location" = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ message="Location",
+ )
+ source: TriggerSource = proto.Field(
+ proto.ENUM,
+ number=2,
+ enum=TriggerSource,
+ )
+
+
class Stop(proto.Message):
r"""A stop in the trip where some task is to be performed.
@@ -343,6 +426,158 @@ class Location(proto.Message):
)
+class SimplePolyline(proto.Message):
+ r"""Represents a polyline using a simple list of points.
+
+ Attributes:
+ points (MutableSequence[google.type.latlng_pb2.LatLng]):
+ Output only. Ordered list of points
+ representing the polyline.
+ """
+
+ points: MutableSequence[latlng_pb2.LatLng] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=1,
+ message=latlng_pb2.LatLng,
+ )
+
+
+class SpeedReadingInterval(proto.Message):
+ r"""Traffic density indicator on a contiguous segment of a path. Given a
+ path with points P_0, P_1, ... , P_N (zero-based index), the
+ SpeedReadingInterval defines an interval and describes its traffic
+ using the ``Speed`` categories.
+
+
+ .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields
+
+ Attributes:
+ start_polyline_point_index (int):
+ Output only. The starting index of this
+ interval in the path.
+
+ This field is a member of `oneof`_ ``_start_polyline_point_index``.
+ end_polyline_point_index (int):
+ Output only. The ending index of this
+ interval in the path.
+
+ This field is a member of `oneof`_ ``_end_polyline_point_index``.
+ speed (google.maps.navconnect_v1.types.SpeedReadingInterval.Speed):
+ Output only. Traffic speed in this interval.
+ """
+
+ class Speed(proto.Enum):
+ r"""The classification of polyline speed based on traffic data.
+
+ Values:
+ SPEED_UNSPECIFIED (0):
+ The speed is unspecified.
+ NORMAL (1):
+ Normal speed, no traffic delays.
+ SLOW (2):
+ Slowdown detected, light to medium amount of
+ traffic.
+ TRAFFIC_JAM (3):
+ Traffic delays, including standstill traffic.
+ """
+
+ SPEED_UNSPECIFIED = 0
+ NORMAL = 1
+ SLOW = 2
+ TRAFFIC_JAM = 3
+
+ start_polyline_point_index: int = proto.Field(
+ proto.INT32,
+ number=1,
+ optional=True,
+ )
+ end_polyline_point_index: int = proto.Field(
+ proto.INT32,
+ number=2,
+ optional=True,
+ )
+ speed: Speed = proto.Field(
+ proto.ENUM,
+ number=3,
+ enum=Speed,
+ )
+
+
+class Route(proto.Message):
+ r"""A route polyline.
+
+ 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:
+ simple_polyline (google.maps.navconnect_v1.types.SimplePolyline):
+ Output only. The route as a simple list of
+ latlngs.
+
+ This field is a member of `oneof`_ ``format``.
+ encoded_polyline (str):
+ Output only. The route as an encoded
+ polyline. See
+ https://developers.google.com/maps/documentation/utilities/polylinealgorithm.
+
+ This field is a member of `oneof`_ ``format``.
+ s2_polyline (bytes):
+ Output only. The route as an encoded S2Polyline. See
+ https://s2geometry.io/devguide/basic_types.html.
+
+ This field is a member of `oneof`_ ``format``.
+ geo_json (google.protobuf.struct_pb2.Struct):
+ Output only. The route as a GeoJSON
+ LineString. See
+ https://tools.ietf.org/html/rfc7946#section-3.1.4.
+
+ This field is a member of `oneof`_ ``format``.
+ traffic_information (MutableSequence[google.maps.navconnect_v1.types.SpeedReadingInterval]):
+ Output only. Traffic information on the polyline described
+ as speed reading intervals.
+
+ NOTES:
+
+ - The intervals are non-overlapping.
+ - The intervals are contiguous.
+ - The intervals cover the entire polyline.
+ - The intervals are sorted by increasing index.
+ - Speed is specified for each interval.
+ """
+
+ simple_polyline: "SimplePolyline" = proto.Field(
+ proto.MESSAGE,
+ number=1,
+ oneof="format",
+ message="SimplePolyline",
+ )
+ encoded_polyline: str = proto.Field(
+ proto.STRING,
+ number=5,
+ oneof="format",
+ )
+ s2_polyline: bytes = proto.Field(
+ proto.BYTES,
+ number=2,
+ oneof="format",
+ )
+ geo_json: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ oneof="format",
+ message=struct_pb2.Struct,
+ )
+ traffic_information: MutableSequence["SpeedReadingInterval"] = proto.RepeatedField(
+ proto.MESSAGE,
+ number=4,
+ message="SpeedReadingInterval",
+ )
+
+
class CreateTripRequest(proto.Message):
r"""Request message for NavConnectService.CreateTrip.
@@ -382,12 +617,48 @@ class GetTripRequest(proto.Message):
name (str):
Required. The resource name of the trip to get. Format:
projects/{project}/trips/{trip_id}
+ route_polyline_format (google.maps.navconnect_v1.types.GetTripRequest.RoutePolylineFormat):
+ Optional. The format of the route polyline to return. If not
+ set, ``SIMPLE`` route polyline will be returned.
"""
+ class RoutePolylineFormat(proto.Enum):
+ r"""Specifies the format of the route polyline.
+
+ Values:
+ ROUTE_POLYLINE_FORMAT_UNSPECIFIED (0):
+ The route polyline format is unspecified.
+ SIMPLE (1):
+ The route polyline is returned as a simple array of points
+ represented as ``google.type.LatLng``.
+ ENCODED (4):
+ The route polyline is returned as an encoded
+ string. See
+ https://developers.google.com/maps/documentation/utilities/polylinealgorithm.
+ S2ENCODED (2):
+ The route polyline is encoded as a S2Polyline. See
+ https://s2geometry.io/devguide/basic_types.html.
+ GEO_JSON (3):
+ The route polyline is returned as a GeoJSON
+ LineString. See
+ https://tools.ietf.org/html/rfc7946#section-3.1.4.
+ """
+
+ ROUTE_POLYLINE_FORMAT_UNSPECIFIED = 0
+ SIMPLE = 1
+ ENCODED = 4
+ S2ENCODED = 2
+ GEO_JSON = 3
+
name: str = proto.Field(
proto.STRING,
number=1,
)
+ route_polyline_format: RoutePolylineFormat = proto.Field(
+ proto.ENUM,
+ number=2,
+ enum=RoutePolylineFormat,
+ )
__all__ = tuple(sorted(__protobuf__.manifest))
diff --git a/packages/google-maps-navconnect/tests/unit/gapic/navconnect_v1/test_nav_connect_service.py b/packages/google-maps-navconnect/tests/unit/gapic/navconnect_v1/test_nav_connect_service.py
index dab5ca31930f..3a8be246ee9a 100644
--- a/packages/google-maps-navconnect/tests/unit/gapic/navconnect_v1/test_nav_connect_service.py
+++ b/packages/google-maps-navconnect/tests/unit/gapic/navconnect_v1/test_nav_connect_service.py
@@ -41,6 +41,7 @@
import google.auth
import google.protobuf.duration_pb2 as duration_pb2 # type: ignore
import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore
+import google.protobuf.struct_pb2 as struct_pb2 # type: ignore
import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore
import google.type.latlng_pb2 as latlng_pb2 # type: ignore
from google.api_core import (
@@ -2031,6 +2032,9 @@ def test_get_trip_rest_required_fields(request_type=navconnect_service.GetTripRe
jsonified_request["name"] = "name_value"
+ # Check that path parameters and body parameters are not mixing in.
+ assert not set(unset_fields) - set(("routePolylineFormat",))
+
# verify required fields with non-default values are left alone
assert "name" in jsonified_request
assert jsonified_request["name"] == "name_value"
@@ -2404,6 +2408,8 @@ def test_create_trip_rest_call_success(request_type):
"enable_high_frequency_updates": True,
"enable_pubsub": True,
"pubsub_field_mask": {"paths": ["paths_value1", "paths_value2"]},
+ "enable_remaining_route_reporting": True,
+ "enable_route_deviation_reporting": True,
},
"android_app_id": "android_app_id_value",
"ios_app_id": "ios_app_id_value",
@@ -2420,6 +2426,20 @@ def test_create_trip_rest_call_success(request_type):
},
"destination": {"point": {}},
"location": {},
+ "remaining_route": {
+ "simple_polyline": {"points": {}},
+ "encoded_polyline": "encoded_polyline_value",
+ "s2_polyline": b"s2_polyline_blob",
+ "geo_json": {"fields": {}},
+ "traffic_information": [
+ {
+ "start_polyline_point_index": 2809,
+ "end_polyline_point_index": 2562,
+ "speed": 1,
+ }
+ ],
+ },
+ "last_route_deviation": {"location": {}, "source": 1},
"traveled_duration": {"seconds": 751, "nanos": 543},
"remaining_duration": {},
"traveled_distance_meters": 2544,
diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py
index 1e31da9f2338..b2ef18f7223c 100644
--- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py
+++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py
@@ -596,10 +596,6 @@ async def optimize_tours_long_running(
[OptimizeToursResponse][google.maps.routeoptimization.v1.OptimizeToursResponse],
if successful.
- Experimental: See
- https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request
- for more details.
-
.. code-block:: python
# This snippet has been automatically generated and should be regarded as a
@@ -723,16 +719,12 @@ async def optimize_tours_uri(
of the format ``/operations/`` and can be
used to track progress of the computation. The
[metadata][google.longrunning.Operation.metadata] field type is
- [OptimizeToursLongRunningMetadata][google.maps.routeoptimization.v1.OptimizeToursUriMetadata].
+ [OptimizeToursUriMetadata][google.maps.routeoptimization.v1.OptimizeToursUriMetadata].
The [response][google.longrunning.Operation.response] field type
is
[OptimizeToursUriResponse][google.maps.routeoptimization.v1.OptimizeToursUriResponse],
if successful.
- Experimental: See
- https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request
- for more details.
-
.. code-block:: python
# This snippet has been automatically generated and should be regarded as a
diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py
index 8898b5690481..7e46c07d7ed1 100644
--- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py
+++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py
@@ -870,10 +870,6 @@ def optimize_tours_long_running(
[OptimizeToursResponse][google.maps.routeoptimization.v1.OptimizeToursResponse],
if successful.
- Experimental: See
- https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request
- for more details.
-
.. code-block:: python
# This snippet has been automatically generated and should be regarded as a
@@ -997,16 +993,12 @@ def optimize_tours_uri(
of the format ``/operations/`` and can be
used to track progress of the computation. The
[metadata][google.longrunning.Operation.metadata] field type is
- [OptimizeToursLongRunningMetadata][google.maps.routeoptimization.v1.OptimizeToursUriMetadata].
+ [OptimizeToursUriMetadata][google.maps.routeoptimization.v1.OptimizeToursUriMetadata].
The [response][google.longrunning.Operation.response] field type
is
[OptimizeToursUriResponse][google.maps.routeoptimization.v1.OptimizeToursUriResponse],
if successful.
- Experimental: See
- https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request
- for more details.
-
.. code-block:: python
# This snippet has been automatically generated and should be regarded as a
diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py
index 68df8c555a91..cdaa7120f124 100644
--- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py
+++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py
@@ -485,10 +485,6 @@ def optimize_tours_long_running(
[OptimizeToursResponse][google.maps.routeoptimization.v1.OptimizeToursResponse],
if successful.
- Experimental: See
- https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request
- for more details.
-
Returns:
Callable[[~.OptimizeToursRequest],
~.Operation]:
@@ -537,16 +533,12 @@ def optimize_tours_uri(
of the format ``/operations/`` and can be
used to track progress of the computation. The
[metadata][google.longrunning.Operation.metadata] field type is
- [OptimizeToursLongRunningMetadata][google.maps.routeoptimization.v1.OptimizeToursUriMetadata].
+ [OptimizeToursUriMetadata][google.maps.routeoptimization.v1.OptimizeToursUriMetadata].
The [response][google.longrunning.Operation.response] field type
is
[OptimizeToursUriResponse][google.maps.routeoptimization.v1.OptimizeToursUriResponse],
if successful.
- Experimental: See
- https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request
- for more details.
-
Returns:
Callable[[~.OptimizeToursUriRequest],
~.Operation]:
diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py
index 11fe431fe06c..4c0832829bb3 100644
--- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py
+++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py
@@ -495,10 +495,6 @@ def optimize_tours_long_running(
[OptimizeToursResponse][google.maps.routeoptimization.v1.OptimizeToursResponse],
if successful.
- Experimental: See
- https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request
- for more details.
-
Returns:
Callable[[~.OptimizeToursRequest],
Awaitable[~.Operation]]:
@@ -548,16 +544,12 @@ def optimize_tours_uri(
of the format ``/operations/`` and can be
used to track progress of the computation. The
[metadata][google.longrunning.Operation.metadata] field type is
- [OptimizeToursLongRunningMetadata][google.maps.routeoptimization.v1.OptimizeToursUriMetadata].
+ [OptimizeToursUriMetadata][google.maps.routeoptimization.v1.OptimizeToursUriMetadata].
The [response][google.longrunning.Operation.response] field type
is
[OptimizeToursUriResponse][google.maps.routeoptimization.v1.OptimizeToursUriResponse],
if successful.
- Experimental: See
- https://developers.google.com/maps/tt/route-optimization/experimental/otlr/make-request
- for more details.
-
Returns:
Callable[[~.OptimizeToursUriRequest],
Awaitable[~.Operation]]:
diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/route_optimization_service.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/route_optimization_service.py
index 0687f1f72aa0..cc648e39c1a8 100644
--- a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/route_optimization_service.py
+++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/route_optimization_service.py
@@ -115,10 +115,9 @@ class OptimizeToursUriRequest(proto.Message):
Format:
- ``projects/{project-id}``
- - ``projects/{project-id}/locations/{location-id}``
+ - ``projects/{project-id}/locations/-``
- If no location is specified, a region will be chosen
- automatically.
+ Regional ``{location-id}`` values are not supported.
input (google.maps.routeoptimization_v1.types.Uri):
Required. The URI of the Cloud Storage object containing the
``OptimizeToursRequest``.
@@ -184,10 +183,9 @@ class BatchOptimizeToursRequest(proto.Message):
Format:
- ``projects/{project-id}``
- - ``projects/{project-id}/locations/{location-id}``
+ - ``projects/{project-id}/locations/-``
- If no location is specified, a region will be chosen
- automatically.
+ Regional ``{location-id}`` values are not supported.
model_configs (MutableSequence[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest.AsyncModelConfig]):
Required. Input/Output information each
purchase model, such as file paths and data
@@ -265,10 +263,9 @@ class OptimizeToursRequest(proto.Message):
Format:
- ``projects/{project-id}``
- - ``projects/{project-id}/locations/{location-id}``
+ - ``projects/{project-id}/locations/-``
- If no location is specified, a region will be chosen
- automatically.
+ Regional ``{location-id}`` values are not supported.
timeout (google.protobuf.duration_pb2.Duration):
If this timeout is set, the server returns a
response before the timeout period has elapsed
@@ -674,7 +671,10 @@ class Metrics(proto.Message):
[ShipmentRoute.metrics][google.maps.routeoptimization.v1.ShipmentRoute.metrics]
fields of the same name.
skipped_mandatory_shipment_count (int):
- Number of mandatory shipments skipped.
+ Number of high priority shipments skipped. High priority
+ shipments are those with an unset
+ [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]
+ field.
used_vehicle_count (int):
Number of vehicles used. Note: if a vehicle route is empty
and
@@ -1279,15 +1279,16 @@ class Shipment(proto.Message):
not appear in the map, the corresponding load is considered
as null.
penalty_cost (float):
- If the shipment is not completed, this penalty is added to
- the overall cost of the routes. A shipment is considered
- completed if one of its pickup and delivery alternatives is
- visited. The cost may be expressed in the same unit used for
- all other cost-related fields in the model and must be
- positive.
+ Optional. If the shipment is not completed, this penalty is
+ added to the overall cost of the routes. A shipment is
+ considered completed if one of its pickup and delivery
+ alternatives is visited. The cost may be expressed in the
+ same unit used for all other cost-related fields in the
+ model and must be non-negative.
*IMPORTANT*: If this penalty is not specified, it is
- considered infinite, i.e. the shipment must be completed.
+ considered higher priority than shipments with a specified
+ ``penalty cost``.
This field is a member of `oneof`_ ``_penalty_cost``.
allowed_vehicle_indices (MutableSequence[int]):
@@ -2039,11 +2040,19 @@ class TravelMode(proto.Enum):
WALKING (2):
Travel mode corresponding to walking
directions.
+ TWO_WHEELER (5):
+ Two-wheeled, motorized vehicle. For example, motorcycle.
+ Note that this differs from the BICYCLING travel mode which
+ covers human-powered mode. This travel mode is supported
+ only in the countries listed at `Countries and regions
+ supported for two-wheeled
+ vehicles `__.
"""
TRAVEL_MODE_UNSPECIFIED = 0
DRIVING = 1
WALKING = 2
+ TWO_WHEELER = 5
class UnloadingPolicy(proto.Enum):
r"""Policy on how a vehicle can be unloaded. Applies only to shipments
@@ -2359,15 +2368,15 @@ class DurationLimit(proto.Message):
duration. This cost adds up to other costs defined in the
model, with the same unit.
- If defined, ``quadratic_soft_max_duration`` must be
- nonnegative. If ``max_duration`` is also defined,
- ``quadratic_soft_max_duration`` must be less than
- ``max_duration``, and the difference must be no larger than
- one day:
+ If ``quadratic_soft_max_duration`` is set, the following
+ conditions must be met:
- ::
-
- `max_duration - quadratic_soft_max_duration <= 86400 seconds`
+ - It must be non-negative.
+ - ``max_duration`` must be defined.
+ - ``quadratic_soft_max_duration`` must be less than
+ ``max_duration``.
+ - The difference must be no more than one day:
+ ``max_duration - quadratic_soft_max_duration <= 86400 seconds``
cost_per_square_hour_after_quadratic_soft_max (float):
Cost per square hour incurred if the
``quadratic_soft_max_duration`` threshold is violated.
@@ -3295,8 +3304,30 @@ class Visit(proto.Message):
for more details.
This field is a member of `oneof`_ ``_injected_solution_location_token``.
+ visit_type (google.maps.routeoptimization_v1.types.ShipmentRoute.Visit.VisitType):
+ Optional. Specifies the type of the visit. Overrides the
+ [Visit.is_pickup][google.maps.routeoptimization.v1.ShipmentRoute.Visit.is_pickup]
+ field.
"""
+ class VisitType(proto.Enum):
+ r"""Indicates whether the visit is a pickup, a delivery, or a visit to a
+ [Stop][google.maps.routeoptimization.v1.Stop]. Visits to a stop are
+ used only when multimodal optimization is enabled.
+
+ Values:
+ VISIT_TYPE_UNSPECIFIED (0):
+ Unspecified visit type.
+ PICKUP_SHIPMENT (1):
+ Visit corresponds to a shipment pickup.
+ DELIVER_SHIPMENT (2):
+ Visit corresponds to a shipment delivery.
+ """
+
+ VISIT_TYPE_UNSPECIFIED = 0
+ PICKUP_SHIPMENT = 1
+ DELIVER_SHIPMENT = 2
+
shipment_index: int = proto.Field(
proto.INT32,
number=1,
@@ -3338,6 +3369,11 @@ class Visit(proto.Message):
number=13,
optional=True,
)
+ visit_type: "ShipmentRoute.Visit.VisitType" = proto.Field(
+ proto.ENUM,
+ number=14,
+ enum="ShipmentRoute.Visit.VisitType",
+ )
class Transition(proto.Message):
r"""Transition between two events on the route. See the description of
@@ -3836,7 +3872,7 @@ class AggregatedMetrics(proto.Message):
r"""Aggregated metrics for
[ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]
(resp. for
- [OptimizeToursResponse][google.maps.routeoptimization.v1.OptimizeToursResponse]
+ [OptimizeToursResponse][google.maps.routeoptimization.v1.OptimizeToursResponse])
over all
[Transition][google.maps.routeoptimization.v1.ShipmentRoute.Transition]
and/or [Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit]
@@ -3852,10 +3888,13 @@ class AggregatedMetrics(proto.Message):
Number of shipments performed. Note that a
pickup and delivery pair only counts once.
performed_mandatory_shipment_count (int):
- Number of mandatory shipments performed.
+ Number of high priority shipments performed. High priority
+ shipments are those with an unset
+ [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]
+ field.
- Experimental: This field's behavior or existence
- may change in future.
+ Experimental: This field's behavior or existence may change
+ in future.
This field is a member of `oneof`_ ``_performed_mandatory_shipment_count``.
performed_shipment_penalty_cost_sum (float):
diff --git a/packages/google-maps-solar/google/maps/solar_v1/types/solar_service.py b/packages/google-maps-solar/google/maps/solar_v1/types/solar_service.py
index 3645d1ea0659..54dabe9539f5 100644
--- a/packages/google-maps-solar/google/maps/solar_v1/types/solar_service.py
+++ b/packages/google-maps-solar/google/maps/solar_v1/types/solar_service.py
@@ -17,6 +17,7 @@
from typing import MutableMapping, MutableSequence
+import google.protobuf.struct_pb2 as struct_pb2 # type: ignore
import google.type.date_pb2 as date_pb2 # type: ignore
import google.type.latlng_pb2 as latlng_pb2 # type: ignore
import google.type.money_pb2 as money_pb2 # type: ignore
@@ -317,6 +318,9 @@ class DetectedArrays(proto.Message):
detection_status (google.maps.solar_v1.types.BuildingInsights.DetectedArrays.DetectionStatus):
Indicates the detection status of solar
arrays for this building.
+ arrays (MutableSequence[google.maps.solar_v1.types.BuildingInsights.DetectedArrays.SolarArray]):
+ A list of solar arrays detected on the
+ building.
latest_capture_date (google.type.date_pb2.Date):
The date indicating when the latest solar
array data was captured.
@@ -344,6 +348,32 @@ class DetectionStatus(proto.Enum):
DETECTION_STATUS_ARRAYS_DETECTED = 2
DETECTION_STATUS_NO_ARRAYS_DETECTED = 3
+ class SolarArray(proto.Message):
+ r"""Details of a single detected solar array.
+
+ Attributes:
+ polygon_geojson (google.protobuf.struct_pb2.Struct):
+ A GeoJSON representation of the building area where solar
+ panels were detected.
+
+ The GeoJSON data must be in RFC 7946 format and represent a
+ Polygon for a single contiguous area.
+
+ The Polygon will be represented by several loops when it
+ contains holes.
+
+ Example:
+
+ { "type": "Polygon", "coordinates": [ [ [-1, -1], [-1, 0],
+ [0, 0], [-1, -1] ] ] }
+ """
+
+ polygon_geojson: struct_pb2.Struct = proto.Field(
+ proto.MESSAGE,
+ number=3,
+ message=struct_pb2.Struct,
+ )
+
detection_status: "BuildingInsights.DetectedArrays.DetectionStatus" = (
proto.Field(
proto.ENUM,
@@ -351,6 +381,13 @@ class DetectionStatus(proto.Enum):
enum="BuildingInsights.DetectedArrays.DetectionStatus",
)
)
+ arrays: MutableSequence["BuildingInsights.DetectedArrays.SolarArray"] = (
+ proto.RepeatedField(
+ proto.MESSAGE,
+ number=2,
+ message="BuildingInsights.DetectedArrays.SolarArray",
+ )
+ )
latest_capture_date: date_pb2.Date = proto.Field(
proto.MESSAGE,
number=3,
diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/folder_global_vm_extension_policies.rst b/preview-packages/google-cloud-compute/docs/compute_v1/folder_global_vm_extension_policies.rst
new file mode 100644
index 000000000000..12c544dcf142
--- /dev/null
+++ b/preview-packages/google-cloud-compute/docs/compute_v1/folder_global_vm_extension_policies.rst
@@ -0,0 +1,10 @@
+FolderGlobalVmExtensionPolicies
+-------------------------------------------------
+
+.. automodule:: google.cloud.compute_v1.services.folder_global_vm_extension_policies
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.compute_v1.services.folder_global_vm_extension_policies.pagers
+ :members:
+ :inherited-members:
diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/folder_zone_vm_extension_policies.rst b/preview-packages/google-cloud-compute/docs/compute_v1/folder_zone_vm_extension_policies.rst
new file mode 100644
index 000000000000..e63e3ad6bf18
--- /dev/null
+++ b/preview-packages/google-cloud-compute/docs/compute_v1/folder_zone_vm_extension_policies.rst
@@ -0,0 +1,10 @@
+FolderZoneVmExtensionPolicies
+-----------------------------------------------
+
+.. automodule:: google.cloud.compute_v1.services.folder_zone_vm_extension_policies
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.compute_v1.services.folder_zone_vm_extension_policies.pagers
+ :members:
+ :inherited-members:
diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/global_folder_operations.rst b/preview-packages/google-cloud-compute/docs/compute_v1/global_folder_operations.rst
new file mode 100644
index 000000000000..0a08537f1156
--- /dev/null
+++ b/preview-packages/google-cloud-compute/docs/compute_v1/global_folder_operations.rst
@@ -0,0 +1,10 @@
+GlobalFolderOperations
+----------------------------------------
+
+.. automodule:: google.cloud.compute_v1.services.global_folder_operations
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.compute_v1.services.global_folder_operations.pagers
+ :members:
+ :inherited-members:
diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/organization_global_vm_extension_policies.rst b/preview-packages/google-cloud-compute/docs/compute_v1/organization_global_vm_extension_policies.rst
new file mode 100644
index 000000000000..212f974f95cd
--- /dev/null
+++ b/preview-packages/google-cloud-compute/docs/compute_v1/organization_global_vm_extension_policies.rst
@@ -0,0 +1,10 @@
+OrganizationGlobalVmExtensionPolicies
+-------------------------------------------------------
+
+.. automodule:: google.cloud.compute_v1.services.organization_global_vm_extension_policies
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.compute_v1.services.organization_global_vm_extension_policies.pagers
+ :members:
+ :inherited-members:
diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/organization_zone_vm_extension_policies.rst b/preview-packages/google-cloud-compute/docs/compute_v1/organization_zone_vm_extension_policies.rst
new file mode 100644
index 000000000000..d41d39c06a40
--- /dev/null
+++ b/preview-packages/google-cloud-compute/docs/compute_v1/organization_zone_vm_extension_policies.rst
@@ -0,0 +1,10 @@
+OrganizationZoneVmExtensionPolicies
+-----------------------------------------------------
+
+.. automodule:: google.cloud.compute_v1.services.organization_zone_vm_extension_policies
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.compute_v1.services.organization_zone_vm_extension_policies.pagers
+ :members:
+ :inherited-members:
diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/services_.rst b/preview-packages/google-cloud-compute/docs/compute_v1/services_.rst
index 34a483a3b4ac..0cc3b2e8c60a 100644
--- a/preview-packages/google-cloud-compute/docs/compute_v1/services_.rst
+++ b/preview-packages/google-cloud-compute/docs/compute_v1/services_.rst
@@ -18,9 +18,12 @@ Services for Google Cloud Compute v1 API
external_vpn_gateways
firewall_policies
firewalls
+ folder_global_vm_extension_policies
+ folder_zone_vm_extension_policies
forwarding_rules
future_reservations
global_addresses
+ global_folder_operations
global_forwarding_rules
global_frontend_settings_service
global_network_endpoint_groups
@@ -62,7 +65,9 @@ Services for Google Cloud Compute v1 API
node_groups
node_templates
node_types
+ organization_global_vm_extension_policies
organization_security_policies
+ organization_zone_vm_extension_policies
packet_mirrorings
preview_features
projects
@@ -133,6 +138,8 @@ Services for Google Cloud Compute v1 API
vpn_gateways
vpn_tunnels
wire_groups
+ zone_folder_operations
zone_operations
+ zone_organization_operations
zones
zone_vm_extension_policies
diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/zone_folder_operations.rst b/preview-packages/google-cloud-compute/docs/compute_v1/zone_folder_operations.rst
new file mode 100644
index 000000000000..5a9f8a7a2005
--- /dev/null
+++ b/preview-packages/google-cloud-compute/docs/compute_v1/zone_folder_operations.rst
@@ -0,0 +1,10 @@
+ZoneFolderOperations
+--------------------------------------
+
+.. automodule:: google.cloud.compute_v1.services.zone_folder_operations
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.compute_v1.services.zone_folder_operations.pagers
+ :members:
+ :inherited-members:
diff --git a/preview-packages/google-cloud-compute/docs/compute_v1/zone_organization_operations.rst b/preview-packages/google-cloud-compute/docs/compute_v1/zone_organization_operations.rst
new file mode 100644
index 000000000000..37bc769e7ab7
--- /dev/null
+++ b/preview-packages/google-cloud-compute/docs/compute_v1/zone_organization_operations.rst
@@ -0,0 +1,10 @@
+ZoneOrganizationOperations
+--------------------------------------------
+
+.. automodule:: google.cloud.compute_v1.services.zone_organization_operations
+ :members:
+ :inherited-members:
+
+.. automodule:: google.cloud.compute_v1.services.zone_organization_operations.pagers
+ :members:
+ :inherited-members:
diff --git a/preview-packages/google-cloud-compute/google/cloud/compute/__init__.py b/preview-packages/google-cloud-compute/google/cloud/compute/__init__.py
index c5981addf56a..c570fb73671a 100644
--- a/preview-packages/google-cloud-compute/google/cloud/compute/__init__.py
+++ b/preview-packages/google-cloud-compute/google/cloud/compute/__init__.py
@@ -49,6 +49,12 @@
FirewallPoliciesClient,
)
from google.cloud.compute_v1.services.firewalls.client import FirewallsClient
+from google.cloud.compute_v1.services.folder_global_vm_extension_policies.client import (
+ FolderGlobalVmExtensionPoliciesClient,
+)
+from google.cloud.compute_v1.services.folder_zone_vm_extension_policies.client import (
+ FolderZoneVmExtensionPoliciesClient,
+)
from google.cloud.compute_v1.services.forwarding_rules.client import (
ForwardingRulesClient,
)
@@ -58,6 +64,9 @@
from google.cloud.compute_v1.services.global_addresses.client import (
GlobalAddressesClient,
)
+from google.cloud.compute_v1.services.global_folder_operations.client import (
+ GlobalFolderOperationsClient,
+)
from google.cloud.compute_v1.services.global_forwarding_rules.client import (
GlobalForwardingRulesClient,
)
@@ -149,9 +158,15 @@
from google.cloud.compute_v1.services.node_groups.client import NodeGroupsClient
from google.cloud.compute_v1.services.node_templates.client import NodeTemplatesClient
from google.cloud.compute_v1.services.node_types.client import NodeTypesClient
+from google.cloud.compute_v1.services.organization_global_vm_extension_policies.client import (
+ OrganizationGlobalVmExtensionPoliciesClient,
+)
from google.cloud.compute_v1.services.organization_security_policies.client import (
OrganizationSecurityPoliciesClient,
)
+from google.cloud.compute_v1.services.organization_zone_vm_extension_policies.client import (
+ OrganizationZoneVmExtensionPoliciesClient,
+)
from google.cloud.compute_v1.services.packet_mirrorings.client import (
PacketMirroringsClient,
)
@@ -322,7 +337,13 @@
from google.cloud.compute_v1.services.vpn_gateways.client import VpnGatewaysClient
from google.cloud.compute_v1.services.vpn_tunnels.client import VpnTunnelsClient
from google.cloud.compute_v1.services.wire_groups.client import WireGroupsClient
+from google.cloud.compute_v1.services.zone_folder_operations.client import (
+ ZoneFolderOperationsClient,
+)
from google.cloud.compute_v1.services.zone_operations.client import ZoneOperationsClient
+from google.cloud.compute_v1.services.zone_organization_operations.client import (
+ ZoneOrganizationOperationsClient,
+)
from google.cloud.compute_v1.services.zone_vm_extension_policies.client import (
ZoneVmExtensionPoliciesClient,
)
@@ -384,6 +405,7 @@
AggregatedListBackendServicesRequest,
AggregatedListDisksRequest,
AggregatedListDiskTypesRequest,
+ AggregatedListFolderGlobalVmExtensionPoliciesRequest,
AggregatedListForwardingRulesRequest,
AggregatedListFutureReservationsRequest,
AggregatedListGlobalOperationsRequest,
@@ -404,6 +426,7 @@
AggregatedListNodeGroupsRequest,
AggregatedListNodeTemplatesRequest,
AggregatedListNodeTypesRequest,
+ AggregatedListOrganizationGlobalVmExtensionPoliciesRequest,
AggregatedListPacketMirroringsRequest,
AggregatedListPublicDelegatedPrefixesRequest,
AggregatedListRegionCommitmentsRequest,
@@ -620,6 +643,8 @@
DeleteExternalVpnGatewayRequest,
DeleteFirewallPolicyRequest,
DeleteFirewallRequest,
+ DeleteFolderGlobalVmExtensionPolicyRequest,
+ DeleteFolderZoneVmExtensionPolicyRequest,
DeleteForwardingRuleRequest,
DeleteFutureReservationRequest,
DeleteGlobalAddressRequest,
@@ -659,7 +684,9 @@
DeleteNodeGroupRequest,
DeleteNodesNodeGroupRequest,
DeleteNodeTemplateRequest,
+ DeleteOrganizationGlobalVmExtensionPolicyRequest,
DeleteOrganizationSecurityPolicyRequest,
+ DeleteOrganizationZoneVmExtensionPolicyRequest,
DeletePacketMirroringRequest,
DeletePerInstanceConfigsInstanceGroupManagerRequest,
DeletePerInstanceConfigsRegionInstanceGroupManagerRequest,
@@ -772,6 +799,8 @@
ExternalVpnGatewayList,
ExternalVpnGatewayParams,
FailoverHaControllerRequest,
+ FetchEncryptionKeyRegionSslCertificateRequest,
+ FetchEncryptionKeySslCertificateRequest,
FileContentBuffer,
Firewall,
FirewallList,
@@ -788,6 +817,7 @@
FirewallPolicyRuleSecureTag,
FixedOrPercent,
FlexibleTimeRange,
+ FolderVmExtensionPolicyAggregatedListResponse,
ForwardingRule,
ForwardingRuleAggregatedList,
ForwardingRuleAttachedExtension,
@@ -842,10 +872,13 @@
GetExternalVpnGatewayRequest,
GetFirewallPolicyRequest,
GetFirewallRequest,
+ GetFolderGlobalVmExtensionPolicyRequest,
+ GetFolderZoneVmExtensionPolicyRequest,
GetForwardingRuleRequest,
GetFromFamilyImageRequest,
GetFutureReservationRequest,
GetGlobalAddressRequest,
+ GetGlobalFolderOperationRequest,
GetGlobalForwardingRuleRequest,
GetGlobalFrontendSettingRequest,
GetGlobalNetworkEndpointGroupRequest,
@@ -935,7 +968,9 @@
GetNodeTypeRequest,
GetOperationalStatusInterconnectAttachmentGroupRequest,
GetOperationalStatusInterconnectGroupRequest,
+ GetOrganizationGlobalVmExtensionPolicyRequest,
GetOrganizationSecurityPolicyRequest,
+ GetOrganizationZoneVmExtensionPolicyRequest,
GetPacketMirroringRequest,
GetPacketMirroringRuleNetworkFirewallPolicyRequest,
GetPreviewFeatureRequest,
@@ -1019,22 +1054,32 @@
GetVersionOperationMetadataSbomInfo,
GetVersionReservationSlotRequest,
GetVersionReservationSubBlockRequest,
+ GetVmExtensionFolderGlobalVmExtensionPolicyRequest,
+ GetVmExtensionFolderZoneVmExtensionPolicyRequest,
+ GetVmExtensionGlobalVmExtensionPolicyRequest,
+ GetVmExtensionOrganizationGlobalVmExtensionPolicyRequest,
+ GetVmExtensionOrganizationZoneVmExtensionPolicyRequest,
+ GetVmExtensionZoneVmExtensionPolicyRequest,
GetVpnGatewayRequest,
GetVpnTunnelRequest,
GetWireGroupRequest,
GetXpnHostProjectRequest,
GetXpnResourcesProjectsRequest,
+ GetZoneFolderOperationRequest,
GetZoneOperationRequest,
+ GetZoneOrganizationOperationRequest,
GetZoneRequest,
GetZoneVmExtensionPolicyRequest,
GlobalAddressesMoveRequest,
GlobalFrontendSettings,
GlobalFrontendSettingsPatchResponse,
+ GlobalListVmExtensionsResponse,
GlobalNetworkEndpointGroupsAttachEndpointsRequest,
GlobalNetworkEndpointGroupsDetachEndpointsRequest,
GlobalOrganizationSetPolicyRequest,
GlobalSetLabelsRequest,
GlobalSetPolicyRequest,
+ GlobalVmExtension,
GlobalVmExtensionPolicy,
GlobalVmExtensionPolicyExtensionPolicy,
GlobalVmExtensionPolicyInstanceSelector,
@@ -1136,6 +1181,8 @@
InsertExternalVpnGatewayRequest,
InsertFirewallPolicyRequest,
InsertFirewallRequest,
+ InsertFolderGlobalVmExtensionPolicyRequest,
+ InsertFolderZoneVmExtensionPolicyRequest,
InsertForwardingRuleRequest,
InsertFutureReservationRequest,
InsertGlobalAddressRequest,
@@ -1166,7 +1213,9 @@
InsertNetworkRequest,
InsertNodeGroupRequest,
InsertNodeTemplateRequest,
+ InsertOrganizationGlobalVmExtensionPolicyRequest,
InsertOrganizationSecurityPolicyRequest,
+ InsertOrganizationZoneVmExtensionPolicyRequest,
InsertPacketMirroringRequest,
InsertPublicAdvertisedPrefixeRequest,
InsertPublicDelegatedPrefixeRequest,
@@ -1436,9 +1485,12 @@
ListExternalVpnGatewaysRequest,
ListFirewallPoliciesRequest,
ListFirewallsRequest,
+ ListFolderGlobalVmExtensionPoliciesRequest,
+ ListFolderZoneVmExtensionPoliciesRequest,
ListForwardingRulesRequest,
ListFutureReservationsRequest,
ListGlobalAddressesRequest,
+ ListGlobalFolderOperationsRequest,
ListGlobalForwardingRulesRequest,
ListGlobalNetworkEndpointGroupsRequest,
ListGlobalOperationsRequest,
@@ -1485,7 +1537,9 @@
ListNodesNodeGroupsRequest,
ListNodeTemplatesRequest,
ListNodeTypesRequest,
+ ListOrganizationGlobalVmExtensionPoliciesRequest,
ListOrganizationSecurityPoliciesRequest,
+ ListOrganizationZoneVmExtensionPoliciesRequest,
ListPacketMirroringsRequest,
ListPeeringRoutesNetworksRequest,
ListPerInstanceConfigsInstanceGroupManagersRequest,
@@ -1560,11 +1614,20 @@
ListUsableRegionBackendBucketsRequest,
ListUsableRegionBackendServicesRequest,
ListUsableSubnetworksRequest,
+ ListVmExtensionsFolderGlobalVmExtensionPoliciesRequest,
+ ListVmExtensionsFolderZoneVmExtensionPoliciesRequest,
+ ListVmExtensionsGlobalVmExtensionPoliciesRequest,
+ ListVmExtensionsOrganizationGlobalVmExtensionPoliciesRequest,
+ ListVmExtensionsOrganizationZoneVmExtensionPoliciesRequest,
+ ListVmExtensionsResponse,
+ ListVmExtensionsZoneVmExtensionPoliciesRequest,
ListVpnGatewaysRequest,
ListVpnTunnelsRequest,
ListWireGroupsRequest,
ListXpnHostsProjectsRequest,
+ ListZoneFolderOperationsRequest,
ListZoneOperationsRequest,
+ ListZoneOrganizationOperationsRequest,
ListZonesRequest,
ListZoneVmExtensionPoliciesRequest,
LocalDisk,
@@ -1651,6 +1714,7 @@
NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy,
NetworksRemovePeeringRequest,
NetworksRequestRemovePeeringRequest,
+ NetworksUpdateNetworkProfileRequest,
NetworksUpdatePeeringRequest,
NodeGroup,
NodeGroupAggregatedList,
@@ -1681,9 +1745,11 @@
NotificationEndpointsScopedList,
Operation,
OperationAggregatedList,
+ OperationDetails,
OperationList,
OperationsScopedList,
OrganizationSecurityPoliciesListAssociationsResponse,
+ OrganizationVmExtensionPolicyAggregatedListResponse,
OutlierDetection,
PacketIntervals,
PacketMirroring,
@@ -2196,6 +2262,7 @@
SslCertificateList,
SslCertificateManagedSslCertificate,
SslCertificateSelfManagedSslCertificate,
+ SslCertificatesFetchEncryptionKeyResponse,
SslCertificatesScopedList,
SSLHealthCheck,
SslPoliciesAggregatedList,
@@ -2272,11 +2339,13 @@
TargetInstance,
TargetInstanceAggregatedList,
TargetInstanceList,
+ TargetInstanceParams,
TargetInstancesScopedList,
TargetPool,
TargetPoolAggregatedList,
TargetPoolInstanceHealth,
TargetPoolList,
+ TargetPoolParams,
TargetPoolsAddHealthCheckRequest,
TargetPoolsAddInstanceRequest,
TargetPoolsRemoveHealthCheckRequest,
@@ -2371,6 +2440,8 @@
UpdateDiskRequest,
UpdateDisplayDeviceInstanceRequest,
UpdateFirewallRequest,
+ UpdateFolderGlobalVmExtensionPolicyRequest,
+ UpdateFolderZoneVmExtensionPolicyRequest,
UpdateFutureReservationRequest,
UpdateGlobalVmExtensionPolicyRequest,
UpdateHealthCheckRequest,
@@ -2382,6 +2453,9 @@
UpdateLicenseRequest,
UpdateNamedSetRouterRequest,
UpdateNetworkInterfaceInstanceRequest,
+ UpdateNetworkProfileNetworkRequest,
+ UpdateOrganizationGlobalVmExtensionPolicyRequest,
+ UpdateOrganizationZoneVmExtensionPolicyRequest,
UpdatePeeringNetworkRequest,
UpdatePerInstanceConfigsInstanceGroupManagerRequest,
UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest,
@@ -2421,6 +2495,7 @@
VmEndpointNatMappingsInterfaceNatMappings,
VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings,
VmEndpointNatMappingsList,
+ VmExtension,
VmExtensionPoliciesScopedList,
VmExtensionPolicy,
VmExtensionPolicyAggregatedListResponse,
@@ -2440,12 +2515,14 @@
VpnGatewayStatusVpnConnection,
VpnGatewayVpnGatewayInterface,
VpnTunnel,
+ VpnTunnelAdditionalKeyExchanges,
VpnTunnelAggregatedList,
VpnTunnelCipherSuite,
VpnTunnelList,
VpnTunnelParams,
VpnTunnelPhase1Algorithms,
VpnTunnelPhase2Algorithms,
+ VpnTunnelPqc,
VpnTunnelsScopedList,
WafExpressionSet,
WafExpressionSetExpression,
@@ -2493,9 +2570,12 @@
"ExternalVpnGatewaysClient",
"FirewallPoliciesClient",
"FirewallsClient",
+ "FolderGlobalVmExtensionPoliciesClient",
+ "FolderZoneVmExtensionPoliciesClient",
"ForwardingRulesClient",
"FutureReservationsClient",
"GlobalAddressesClient",
+ "GlobalFolderOperationsClient",
"GlobalForwardingRulesClient",
"GlobalFrontendSettingsServiceClient",
"GlobalNetworkEndpointGroupsClient",
@@ -2537,7 +2617,9 @@
"NodeGroupsClient",
"NodeTemplatesClient",
"NodeTypesClient",
+ "OrganizationGlobalVmExtensionPoliciesClient",
"OrganizationSecurityPoliciesClient",
+ "OrganizationZoneVmExtensionPoliciesClient",
"PacketMirroringsClient",
"PreviewFeaturesClient",
"ProjectsClient",
@@ -2608,7 +2690,9 @@
"VpnGatewaysClient",
"VpnTunnelsClient",
"WireGroupsClient",
+ "ZoneFolderOperationsClient",
"ZoneOperationsClient",
+ "ZoneOrganizationOperationsClient",
"ZonesClient",
"ZoneVmExtensionPoliciesClient",
"AbandonInstancesInstanceGroupManagerRequest",
@@ -2667,6 +2751,7 @@
"AggregatedListBackendServicesRequest",
"AggregatedListDisksRequest",
"AggregatedListDiskTypesRequest",
+ "AggregatedListFolderGlobalVmExtensionPoliciesRequest",
"AggregatedListForwardingRulesRequest",
"AggregatedListFutureReservationsRequest",
"AggregatedListGlobalOperationsRequest",
@@ -2687,6 +2772,7 @@
"AggregatedListNodeGroupsRequest",
"AggregatedListNodeTemplatesRequest",
"AggregatedListNodeTypesRequest",
+ "AggregatedListOrganizationGlobalVmExtensionPoliciesRequest",
"AggregatedListPacketMirroringsRequest",
"AggregatedListPublicDelegatedPrefixesRequest",
"AggregatedListRegionCommitmentsRequest",
@@ -2903,6 +2989,8 @@
"DeleteExternalVpnGatewayRequest",
"DeleteFirewallPolicyRequest",
"DeleteFirewallRequest",
+ "DeleteFolderGlobalVmExtensionPolicyRequest",
+ "DeleteFolderZoneVmExtensionPolicyRequest",
"DeleteForwardingRuleRequest",
"DeleteFutureReservationRequest",
"DeleteGlobalAddressRequest",
@@ -2942,7 +3030,9 @@
"DeleteNodeGroupRequest",
"DeleteNodesNodeGroupRequest",
"DeleteNodeTemplateRequest",
+ "DeleteOrganizationGlobalVmExtensionPolicyRequest",
"DeleteOrganizationSecurityPolicyRequest",
+ "DeleteOrganizationZoneVmExtensionPolicyRequest",
"DeletePacketMirroringRequest",
"DeletePerInstanceConfigsInstanceGroupManagerRequest",
"DeletePerInstanceConfigsRegionInstanceGroupManagerRequest",
@@ -3055,6 +3145,8 @@
"ExternalVpnGatewayList",
"ExternalVpnGatewayParams",
"FailoverHaControllerRequest",
+ "FetchEncryptionKeyRegionSslCertificateRequest",
+ "FetchEncryptionKeySslCertificateRequest",
"FileContentBuffer",
"Firewall",
"FirewallList",
@@ -3071,6 +3163,7 @@
"FirewallPolicyRuleSecureTag",
"FixedOrPercent",
"FlexibleTimeRange",
+ "FolderVmExtensionPolicyAggregatedListResponse",
"ForwardingRule",
"ForwardingRuleAggregatedList",
"ForwardingRuleAttachedExtension",
@@ -3125,10 +3218,13 @@
"GetExternalVpnGatewayRequest",
"GetFirewallPolicyRequest",
"GetFirewallRequest",
+ "GetFolderGlobalVmExtensionPolicyRequest",
+ "GetFolderZoneVmExtensionPolicyRequest",
"GetForwardingRuleRequest",
"GetFromFamilyImageRequest",
"GetFutureReservationRequest",
"GetGlobalAddressRequest",
+ "GetGlobalFolderOperationRequest",
"GetGlobalForwardingRuleRequest",
"GetGlobalFrontendSettingRequest",
"GetGlobalNetworkEndpointGroupRequest",
@@ -3218,7 +3314,9 @@
"GetNodeTypeRequest",
"GetOperationalStatusInterconnectAttachmentGroupRequest",
"GetOperationalStatusInterconnectGroupRequest",
+ "GetOrganizationGlobalVmExtensionPolicyRequest",
"GetOrganizationSecurityPolicyRequest",
+ "GetOrganizationZoneVmExtensionPolicyRequest",
"GetPacketMirroringRequest",
"GetPacketMirroringRuleNetworkFirewallPolicyRequest",
"GetPreviewFeatureRequest",
@@ -3302,22 +3400,32 @@
"GetVersionOperationMetadataSbomInfo",
"GetVersionReservationSlotRequest",
"GetVersionReservationSubBlockRequest",
+ "GetVmExtensionFolderGlobalVmExtensionPolicyRequest",
+ "GetVmExtensionFolderZoneVmExtensionPolicyRequest",
+ "GetVmExtensionGlobalVmExtensionPolicyRequest",
+ "GetVmExtensionOrganizationGlobalVmExtensionPolicyRequest",
+ "GetVmExtensionOrganizationZoneVmExtensionPolicyRequest",
+ "GetVmExtensionZoneVmExtensionPolicyRequest",
"GetVpnGatewayRequest",
"GetVpnTunnelRequest",
"GetWireGroupRequest",
"GetXpnHostProjectRequest",
"GetXpnResourcesProjectsRequest",
+ "GetZoneFolderOperationRequest",
"GetZoneOperationRequest",
+ "GetZoneOrganizationOperationRequest",
"GetZoneRequest",
"GetZoneVmExtensionPolicyRequest",
"GlobalAddressesMoveRequest",
"GlobalFrontendSettings",
"GlobalFrontendSettingsPatchResponse",
+ "GlobalListVmExtensionsResponse",
"GlobalNetworkEndpointGroupsAttachEndpointsRequest",
"GlobalNetworkEndpointGroupsDetachEndpointsRequest",
"GlobalOrganizationSetPolicyRequest",
"GlobalSetLabelsRequest",
"GlobalSetPolicyRequest",
+ "GlobalVmExtension",
"GlobalVmExtensionPolicy",
"GlobalVmExtensionPolicyExtensionPolicy",
"GlobalVmExtensionPolicyInstanceSelector",
@@ -3419,6 +3527,8 @@
"InsertExternalVpnGatewayRequest",
"InsertFirewallPolicyRequest",
"InsertFirewallRequest",
+ "InsertFolderGlobalVmExtensionPolicyRequest",
+ "InsertFolderZoneVmExtensionPolicyRequest",
"InsertForwardingRuleRequest",
"InsertFutureReservationRequest",
"InsertGlobalAddressRequest",
@@ -3449,7 +3559,9 @@
"InsertNetworkRequest",
"InsertNodeGroupRequest",
"InsertNodeTemplateRequest",
+ "InsertOrganizationGlobalVmExtensionPolicyRequest",
"InsertOrganizationSecurityPolicyRequest",
+ "InsertOrganizationZoneVmExtensionPolicyRequest",
"InsertPacketMirroringRequest",
"InsertPublicAdvertisedPrefixeRequest",
"InsertPublicDelegatedPrefixeRequest",
@@ -3719,9 +3831,12 @@
"ListExternalVpnGatewaysRequest",
"ListFirewallPoliciesRequest",
"ListFirewallsRequest",
+ "ListFolderGlobalVmExtensionPoliciesRequest",
+ "ListFolderZoneVmExtensionPoliciesRequest",
"ListForwardingRulesRequest",
"ListFutureReservationsRequest",
"ListGlobalAddressesRequest",
+ "ListGlobalFolderOperationsRequest",
"ListGlobalForwardingRulesRequest",
"ListGlobalNetworkEndpointGroupsRequest",
"ListGlobalOperationsRequest",
@@ -3768,7 +3883,9 @@
"ListNodesNodeGroupsRequest",
"ListNodeTemplatesRequest",
"ListNodeTypesRequest",
+ "ListOrganizationGlobalVmExtensionPoliciesRequest",
"ListOrganizationSecurityPoliciesRequest",
+ "ListOrganizationZoneVmExtensionPoliciesRequest",
"ListPacketMirroringsRequest",
"ListPeeringRoutesNetworksRequest",
"ListPerInstanceConfigsInstanceGroupManagersRequest",
@@ -3843,11 +3960,20 @@
"ListUsableRegionBackendBucketsRequest",
"ListUsableRegionBackendServicesRequest",
"ListUsableSubnetworksRequest",
+ "ListVmExtensionsFolderGlobalVmExtensionPoliciesRequest",
+ "ListVmExtensionsFolderZoneVmExtensionPoliciesRequest",
+ "ListVmExtensionsGlobalVmExtensionPoliciesRequest",
+ "ListVmExtensionsOrganizationGlobalVmExtensionPoliciesRequest",
+ "ListVmExtensionsOrganizationZoneVmExtensionPoliciesRequest",
+ "ListVmExtensionsResponse",
+ "ListVmExtensionsZoneVmExtensionPoliciesRequest",
"ListVpnGatewaysRequest",
"ListVpnTunnelsRequest",
"ListWireGroupsRequest",
"ListXpnHostsProjectsRequest",
+ "ListZoneFolderOperationsRequest",
"ListZoneOperationsRequest",
+ "ListZoneOrganizationOperationsRequest",
"ListZonesRequest",
"ListZoneVmExtensionPoliciesRequest",
"LocalDisk",
@@ -3934,6 +4060,7 @@
"NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy",
"NetworksRemovePeeringRequest",
"NetworksRequestRemovePeeringRequest",
+ "NetworksUpdateNetworkProfileRequest",
"NetworksUpdatePeeringRequest",
"NodeGroup",
"NodeGroupAggregatedList",
@@ -3964,9 +4091,11 @@
"NotificationEndpointsScopedList",
"Operation",
"OperationAggregatedList",
+ "OperationDetails",
"OperationList",
"OperationsScopedList",
"OrganizationSecurityPoliciesListAssociationsResponse",
+ "OrganizationVmExtensionPolicyAggregatedListResponse",
"OutlierDetection",
"PacketIntervals",
"PacketMirroring",
@@ -4479,6 +4608,7 @@
"SslCertificateList",
"SslCertificateManagedSslCertificate",
"SslCertificateSelfManagedSslCertificate",
+ "SslCertificatesFetchEncryptionKeyResponse",
"SslCertificatesScopedList",
"SSLHealthCheck",
"SslPoliciesAggregatedList",
@@ -4555,11 +4685,13 @@
"TargetInstance",
"TargetInstanceAggregatedList",
"TargetInstanceList",
+ "TargetInstanceParams",
"TargetInstancesScopedList",
"TargetPool",
"TargetPoolAggregatedList",
"TargetPoolInstanceHealth",
"TargetPoolList",
+ "TargetPoolParams",
"TargetPoolsAddHealthCheckRequest",
"TargetPoolsAddInstanceRequest",
"TargetPoolsRemoveHealthCheckRequest",
@@ -4654,6 +4786,8 @@
"UpdateDiskRequest",
"UpdateDisplayDeviceInstanceRequest",
"UpdateFirewallRequest",
+ "UpdateFolderGlobalVmExtensionPolicyRequest",
+ "UpdateFolderZoneVmExtensionPolicyRequest",
"UpdateFutureReservationRequest",
"UpdateGlobalVmExtensionPolicyRequest",
"UpdateHealthCheckRequest",
@@ -4665,6 +4799,9 @@
"UpdateLicenseRequest",
"UpdateNamedSetRouterRequest",
"UpdateNetworkInterfaceInstanceRequest",
+ "UpdateNetworkProfileNetworkRequest",
+ "UpdateOrganizationGlobalVmExtensionPolicyRequest",
+ "UpdateOrganizationZoneVmExtensionPolicyRequest",
"UpdatePeeringNetworkRequest",
"UpdatePerInstanceConfigsInstanceGroupManagerRequest",
"UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest",
@@ -4704,6 +4841,7 @@
"VmEndpointNatMappingsInterfaceNatMappings",
"VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings",
"VmEndpointNatMappingsList",
+ "VmExtension",
"VmExtensionPoliciesScopedList",
"VmExtensionPolicy",
"VmExtensionPolicyAggregatedListResponse",
@@ -4723,12 +4861,14 @@
"VpnGatewayStatusVpnConnection",
"VpnGatewayVpnGatewayInterface",
"VpnTunnel",
+ "VpnTunnelAdditionalKeyExchanges",
"VpnTunnelAggregatedList",
"VpnTunnelCipherSuite",
"VpnTunnelList",
"VpnTunnelParams",
"VpnTunnelPhase1Algorithms",
"VpnTunnelPhase2Algorithms",
+ "VpnTunnelPqc",
"VpnTunnelsScopedList",
"WafExpressionSet",
"WafExpressionSetExpression",
diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/__init__.py
index ca325c968053..2e455be58999 100644
--- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/__init__.py
+++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/__init__.py
@@ -41,9 +41,12 @@
"google.cloud.compute_v1.services.external_vpn_gateways",
"google.cloud.compute_v1.services.firewall_policies",
"google.cloud.compute_v1.services.firewalls",
+ "google.cloud.compute_v1.services.folder_global_vm_extension_policies",
+ "google.cloud.compute_v1.services.folder_zone_vm_extension_policies",
"google.cloud.compute_v1.services.forwarding_rules",
"google.cloud.compute_v1.services.future_reservations",
"google.cloud.compute_v1.services.global_addresses",
+ "google.cloud.compute_v1.services.global_folder_operations",
"google.cloud.compute_v1.services.global_forwarding_rules",
"google.cloud.compute_v1.services.global_frontend_settings_service",
"google.cloud.compute_v1.services.global_network_endpoint_groups",
@@ -85,7 +88,9 @@
"google.cloud.compute_v1.services.node_groups",
"google.cloud.compute_v1.services.node_templates",
"google.cloud.compute_v1.services.node_types",
+ "google.cloud.compute_v1.services.organization_global_vm_extension_policies",
"google.cloud.compute_v1.services.organization_security_policies",
+ "google.cloud.compute_v1.services.organization_zone_vm_extension_policies",
"google.cloud.compute_v1.services.packet_mirrorings",
"google.cloud.compute_v1.services.preview_features",
"google.cloud.compute_v1.services.project_views",
@@ -156,7 +161,9 @@
"google.cloud.compute_v1.services.vpn_gateways",
"google.cloud.compute_v1.services.vpn_tunnels",
"google.cloud.compute_v1.services.wire_groups",
+ "google.cloud.compute_v1.services.zone_folder_operations",
"google.cloud.compute_v1.services.zone_operations",
+ "google.cloud.compute_v1.services.zone_organization_operations",
"google.cloud.compute_v1.services.zone_vm_extension_policies",
"google.cloud.compute_v1.services.zones",
"google.cloud.compute_v1.types.compute",
@@ -180,9 +187,16 @@
from .services.external_vpn_gateways import ExternalVpnGatewaysClient
from .services.firewall_policies import FirewallPoliciesClient
from .services.firewalls import FirewallsClient
+from .services.folder_global_vm_extension_policies import (
+ FolderGlobalVmExtensionPoliciesClient,
+)
+from .services.folder_zone_vm_extension_policies import (
+ FolderZoneVmExtensionPoliciesClient,
+)
from .services.forwarding_rules import ForwardingRulesClient
from .services.future_reservations import FutureReservationsClient
from .services.global_addresses import GlobalAddressesClient
+from .services.global_folder_operations import GlobalFolderOperationsClient
from .services.global_forwarding_rules import GlobalForwardingRulesClient
from .services.global_frontend_settings_service import (
GlobalFrontendSettingsServiceClient,
@@ -230,7 +244,13 @@
from .services.node_groups import NodeGroupsClient
from .services.node_templates import NodeTemplatesClient
from .services.node_types import NodeTypesClient
+from .services.organization_global_vm_extension_policies import (
+ OrganizationGlobalVmExtensionPoliciesClient,
+)
from .services.organization_security_policies import OrganizationSecurityPoliciesClient
+from .services.organization_zone_vm_extension_policies import (
+ OrganizationZoneVmExtensionPoliciesClient,
+)
from .services.packet_mirrorings import PacketMirroringsClient
from .services.preview_features import PreviewFeaturesClient
from .services.project_views import ProjectViewsClient
@@ -307,7 +327,9 @@
from .services.vpn_gateways import VpnGatewaysClient
from .services.vpn_tunnels import VpnTunnelsClient
from .services.wire_groups import WireGroupsClient
+from .services.zone_folder_operations import ZoneFolderOperationsClient
from .services.zone_operations import ZoneOperationsClient
+from .services.zone_organization_operations import ZoneOrganizationOperationsClient
from .services.zone_vm_extension_policies import ZoneVmExtensionPoliciesClient
from .services.zones import ZonesClient
from .types.compute import (
@@ -367,6 +389,7 @@
AggregatedListBackendServicesRequest,
AggregatedListDisksRequest,
AggregatedListDiskTypesRequest,
+ AggregatedListFolderGlobalVmExtensionPoliciesRequest,
AggregatedListForwardingRulesRequest,
AggregatedListFutureReservationsRequest,
AggregatedListGlobalOperationsRequest,
@@ -387,6 +410,7 @@
AggregatedListNodeGroupsRequest,
AggregatedListNodeTemplatesRequest,
AggregatedListNodeTypesRequest,
+ AggregatedListOrganizationGlobalVmExtensionPoliciesRequest,
AggregatedListPacketMirroringsRequest,
AggregatedListPublicDelegatedPrefixesRequest,
AggregatedListRegionCommitmentsRequest,
@@ -603,6 +627,8 @@
DeleteExternalVpnGatewayRequest,
DeleteFirewallPolicyRequest,
DeleteFirewallRequest,
+ DeleteFolderGlobalVmExtensionPolicyRequest,
+ DeleteFolderZoneVmExtensionPolicyRequest,
DeleteForwardingRuleRequest,
DeleteFutureReservationRequest,
DeleteGlobalAddressRequest,
@@ -642,7 +668,9 @@
DeleteNodeGroupRequest,
DeleteNodesNodeGroupRequest,
DeleteNodeTemplateRequest,
+ DeleteOrganizationGlobalVmExtensionPolicyRequest,
DeleteOrganizationSecurityPolicyRequest,
+ DeleteOrganizationZoneVmExtensionPolicyRequest,
DeletePacketMirroringRequest,
DeletePerInstanceConfigsInstanceGroupManagerRequest,
DeletePerInstanceConfigsRegionInstanceGroupManagerRequest,
@@ -755,6 +783,8 @@
ExternalVpnGatewayList,
ExternalVpnGatewayParams,
FailoverHaControllerRequest,
+ FetchEncryptionKeyRegionSslCertificateRequest,
+ FetchEncryptionKeySslCertificateRequest,
FileContentBuffer,
Firewall,
FirewallList,
@@ -771,6 +801,7 @@
FirewallPolicyRuleSecureTag,
FixedOrPercent,
FlexibleTimeRange,
+ FolderVmExtensionPolicyAggregatedListResponse,
ForwardingRule,
ForwardingRuleAggregatedList,
ForwardingRuleAttachedExtension,
@@ -825,10 +856,13 @@
GetExternalVpnGatewayRequest,
GetFirewallPolicyRequest,
GetFirewallRequest,
+ GetFolderGlobalVmExtensionPolicyRequest,
+ GetFolderZoneVmExtensionPolicyRequest,
GetForwardingRuleRequest,
GetFromFamilyImageRequest,
GetFutureReservationRequest,
GetGlobalAddressRequest,
+ GetGlobalFolderOperationRequest,
GetGlobalForwardingRuleRequest,
GetGlobalFrontendSettingRequest,
GetGlobalNetworkEndpointGroupRequest,
@@ -918,7 +952,9 @@
GetNodeTypeRequest,
GetOperationalStatusInterconnectAttachmentGroupRequest,
GetOperationalStatusInterconnectGroupRequest,
+ GetOrganizationGlobalVmExtensionPolicyRequest,
GetOrganizationSecurityPolicyRequest,
+ GetOrganizationZoneVmExtensionPolicyRequest,
GetPacketMirroringRequest,
GetPacketMirroringRuleNetworkFirewallPolicyRequest,
GetPreviewFeatureRequest,
@@ -1002,22 +1038,32 @@
GetVersionOperationMetadataSbomInfo,
GetVersionReservationSlotRequest,
GetVersionReservationSubBlockRequest,
+ GetVmExtensionFolderGlobalVmExtensionPolicyRequest,
+ GetVmExtensionFolderZoneVmExtensionPolicyRequest,
+ GetVmExtensionGlobalVmExtensionPolicyRequest,
+ GetVmExtensionOrganizationGlobalVmExtensionPolicyRequest,
+ GetVmExtensionOrganizationZoneVmExtensionPolicyRequest,
+ GetVmExtensionZoneVmExtensionPolicyRequest,
GetVpnGatewayRequest,
GetVpnTunnelRequest,
GetWireGroupRequest,
GetXpnHostProjectRequest,
GetXpnResourcesProjectsRequest,
+ GetZoneFolderOperationRequest,
GetZoneOperationRequest,
+ GetZoneOrganizationOperationRequest,
GetZoneRequest,
GetZoneVmExtensionPolicyRequest,
GlobalAddressesMoveRequest,
GlobalFrontendSettings,
GlobalFrontendSettingsPatchResponse,
+ GlobalListVmExtensionsResponse,
GlobalNetworkEndpointGroupsAttachEndpointsRequest,
GlobalNetworkEndpointGroupsDetachEndpointsRequest,
GlobalOrganizationSetPolicyRequest,
GlobalSetLabelsRequest,
GlobalSetPolicyRequest,
+ GlobalVmExtension,
GlobalVmExtensionPolicy,
GlobalVmExtensionPolicyExtensionPolicy,
GlobalVmExtensionPolicyInstanceSelector,
@@ -1119,6 +1165,8 @@
InsertExternalVpnGatewayRequest,
InsertFirewallPolicyRequest,
InsertFirewallRequest,
+ InsertFolderGlobalVmExtensionPolicyRequest,
+ InsertFolderZoneVmExtensionPolicyRequest,
InsertForwardingRuleRequest,
InsertFutureReservationRequest,
InsertGlobalAddressRequest,
@@ -1149,7 +1197,9 @@
InsertNetworkRequest,
InsertNodeGroupRequest,
InsertNodeTemplateRequest,
+ InsertOrganizationGlobalVmExtensionPolicyRequest,
InsertOrganizationSecurityPolicyRequest,
+ InsertOrganizationZoneVmExtensionPolicyRequest,
InsertPacketMirroringRequest,
InsertPublicAdvertisedPrefixeRequest,
InsertPublicDelegatedPrefixeRequest,
@@ -1419,9 +1469,12 @@
ListExternalVpnGatewaysRequest,
ListFirewallPoliciesRequest,
ListFirewallsRequest,
+ ListFolderGlobalVmExtensionPoliciesRequest,
+ ListFolderZoneVmExtensionPoliciesRequest,
ListForwardingRulesRequest,
ListFutureReservationsRequest,
ListGlobalAddressesRequest,
+ ListGlobalFolderOperationsRequest,
ListGlobalForwardingRulesRequest,
ListGlobalNetworkEndpointGroupsRequest,
ListGlobalOperationsRequest,
@@ -1468,7 +1521,9 @@
ListNodesNodeGroupsRequest,
ListNodeTemplatesRequest,
ListNodeTypesRequest,
+ ListOrganizationGlobalVmExtensionPoliciesRequest,
ListOrganizationSecurityPoliciesRequest,
+ ListOrganizationZoneVmExtensionPoliciesRequest,
ListPacketMirroringsRequest,
ListPeeringRoutesNetworksRequest,
ListPerInstanceConfigsInstanceGroupManagersRequest,
@@ -1543,11 +1598,20 @@
ListUsableRegionBackendBucketsRequest,
ListUsableRegionBackendServicesRequest,
ListUsableSubnetworksRequest,
+ ListVmExtensionsFolderGlobalVmExtensionPoliciesRequest,
+ ListVmExtensionsFolderZoneVmExtensionPoliciesRequest,
+ ListVmExtensionsGlobalVmExtensionPoliciesRequest,
+ ListVmExtensionsOrganizationGlobalVmExtensionPoliciesRequest,
+ ListVmExtensionsOrganizationZoneVmExtensionPoliciesRequest,
+ ListVmExtensionsResponse,
+ ListVmExtensionsZoneVmExtensionPoliciesRequest,
ListVpnGatewaysRequest,
ListVpnTunnelsRequest,
ListWireGroupsRequest,
ListXpnHostsProjectsRequest,
+ ListZoneFolderOperationsRequest,
ListZoneOperationsRequest,
+ ListZoneOrganizationOperationsRequest,
ListZonesRequest,
ListZoneVmExtensionPoliciesRequest,
LocalDisk,
@@ -1634,6 +1698,7 @@
NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy,
NetworksRemovePeeringRequest,
NetworksRequestRemovePeeringRequest,
+ NetworksUpdateNetworkProfileRequest,
NetworksUpdatePeeringRequest,
NodeGroup,
NodeGroupAggregatedList,
@@ -1664,9 +1729,11 @@
NotificationEndpointsScopedList,
Operation,
OperationAggregatedList,
+ OperationDetails,
OperationList,
OperationsScopedList,
OrganizationSecurityPoliciesListAssociationsResponse,
+ OrganizationVmExtensionPolicyAggregatedListResponse,
OutlierDetection,
PacketIntervals,
PacketMirroring,
@@ -2179,6 +2246,7 @@
SslCertificateList,
SslCertificateManagedSslCertificate,
SslCertificateSelfManagedSslCertificate,
+ SslCertificatesFetchEncryptionKeyResponse,
SslCertificatesScopedList,
SSLHealthCheck,
SslPoliciesAggregatedList,
@@ -2255,11 +2323,13 @@
TargetInstance,
TargetInstanceAggregatedList,
TargetInstanceList,
+ TargetInstanceParams,
TargetInstancesScopedList,
TargetPool,
TargetPoolAggregatedList,
TargetPoolInstanceHealth,
TargetPoolList,
+ TargetPoolParams,
TargetPoolsAddHealthCheckRequest,
TargetPoolsAddInstanceRequest,
TargetPoolsRemoveHealthCheckRequest,
@@ -2354,6 +2424,8 @@
UpdateDiskRequest,
UpdateDisplayDeviceInstanceRequest,
UpdateFirewallRequest,
+ UpdateFolderGlobalVmExtensionPolicyRequest,
+ UpdateFolderZoneVmExtensionPolicyRequest,
UpdateFutureReservationRequest,
UpdateGlobalVmExtensionPolicyRequest,
UpdateHealthCheckRequest,
@@ -2365,6 +2437,9 @@
UpdateLicenseRequest,
UpdateNamedSetRouterRequest,
UpdateNetworkInterfaceInstanceRequest,
+ UpdateNetworkProfileNetworkRequest,
+ UpdateOrganizationGlobalVmExtensionPolicyRequest,
+ UpdateOrganizationZoneVmExtensionPolicyRequest,
UpdatePeeringNetworkRequest,
UpdatePerInstanceConfigsInstanceGroupManagerRequest,
UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest,
@@ -2404,6 +2479,7 @@
VmEndpointNatMappingsInterfaceNatMappings,
VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings,
VmEndpointNatMappingsList,
+ VmExtension,
VmExtensionPoliciesScopedList,
VmExtensionPolicy,
VmExtensionPolicyAggregatedListResponse,
@@ -2423,12 +2499,14 @@
VpnGatewayStatusVpnConnection,
VpnGatewayVpnGatewayInterface,
VpnTunnel,
+ VpnTunnelAdditionalKeyExchanges,
VpnTunnelAggregatedList,
VpnTunnelCipherSuite,
VpnTunnelList,
VpnTunnelParams,
VpnTunnelPhase1Algorithms,
VpnTunnelPhase2Algorithms,
+ VpnTunnelPqc,
VpnTunnelsScopedList,
WafExpressionSet,
WafExpressionSetExpression,
@@ -2523,6 +2601,7 @@
"AggregatedListBackendServicesRequest",
"AggregatedListDiskTypesRequest",
"AggregatedListDisksRequest",
+ "AggregatedListFolderGlobalVmExtensionPoliciesRequest",
"AggregatedListForwardingRulesRequest",
"AggregatedListFutureReservationsRequest",
"AggregatedListGlobalOperationsRequest",
@@ -2543,6 +2622,7 @@
"AggregatedListNodeGroupsRequest",
"AggregatedListNodeTemplatesRequest",
"AggregatedListNodeTypesRequest",
+ "AggregatedListOrganizationGlobalVmExtensionPoliciesRequest",
"AggregatedListPacketMirroringsRequest",
"AggregatedListPublicDelegatedPrefixesRequest",
"AggregatedListRegionCommitmentsRequest",
@@ -2763,6 +2843,8 @@
"DeleteExternalVpnGatewayRequest",
"DeleteFirewallPolicyRequest",
"DeleteFirewallRequest",
+ "DeleteFolderGlobalVmExtensionPolicyRequest",
+ "DeleteFolderZoneVmExtensionPolicyRequest",
"DeleteForwardingRuleRequest",
"DeleteFutureReservationRequest",
"DeleteGlobalAddressRequest",
@@ -2802,7 +2884,9 @@
"DeleteNodeGroupRequest",
"DeleteNodeTemplateRequest",
"DeleteNodesNodeGroupRequest",
+ "DeleteOrganizationGlobalVmExtensionPolicyRequest",
"DeleteOrganizationSecurityPolicyRequest",
+ "DeleteOrganizationZoneVmExtensionPolicyRequest",
"DeletePacketMirroringRequest",
"DeletePerInstanceConfigsInstanceGroupManagerRequest",
"DeletePerInstanceConfigsRegionInstanceGroupManagerRequest",
@@ -2918,6 +3002,8 @@
"ExternalVpnGatewayParams",
"ExternalVpnGatewaysClient",
"FailoverHaControllerRequest",
+ "FetchEncryptionKeyRegionSslCertificateRequest",
+ "FetchEncryptionKeySslCertificateRequest",
"FileContentBuffer",
"Firewall",
"FirewallList",
@@ -2936,6 +3022,9 @@
"FirewallsClient",
"FixedOrPercent",
"FlexibleTimeRange",
+ "FolderGlobalVmExtensionPoliciesClient",
+ "FolderVmExtensionPolicyAggregatedListResponse",
+ "FolderZoneVmExtensionPoliciesClient",
"ForwardingRule",
"ForwardingRuleAggregatedList",
"ForwardingRuleAttachedExtension",
@@ -2994,10 +3083,13 @@
"GetExternalVpnGatewayRequest",
"GetFirewallPolicyRequest",
"GetFirewallRequest",
+ "GetFolderGlobalVmExtensionPolicyRequest",
+ "GetFolderZoneVmExtensionPolicyRequest",
"GetForwardingRuleRequest",
"GetFromFamilyImageRequest",
"GetFutureReservationRequest",
"GetGlobalAddressRequest",
+ "GetGlobalFolderOperationRequest",
"GetGlobalForwardingRuleRequest",
"GetGlobalFrontendSettingRequest",
"GetGlobalNetworkEndpointGroupRequest",
@@ -3087,7 +3179,9 @@
"GetNodeTypeRequest",
"GetOperationalStatusInterconnectAttachmentGroupRequest",
"GetOperationalStatusInterconnectGroupRequest",
+ "GetOrganizationGlobalVmExtensionPolicyRequest",
"GetOrganizationSecurityPolicyRequest",
+ "GetOrganizationZoneVmExtensionPolicyRequest",
"GetPacketMirroringRequest",
"GetPacketMirroringRuleNetworkFirewallPolicyRequest",
"GetPreviewFeatureRequest",
@@ -3171,20 +3265,30 @@
"GetVersionOperationMetadataSbomInfo",
"GetVersionReservationSlotRequest",
"GetVersionReservationSubBlockRequest",
+ "GetVmExtensionFolderGlobalVmExtensionPolicyRequest",
+ "GetVmExtensionFolderZoneVmExtensionPolicyRequest",
+ "GetVmExtensionGlobalVmExtensionPolicyRequest",
+ "GetVmExtensionOrganizationGlobalVmExtensionPolicyRequest",
+ "GetVmExtensionOrganizationZoneVmExtensionPolicyRequest",
+ "GetVmExtensionZoneVmExtensionPolicyRequest",
"GetVpnGatewayRequest",
"GetVpnTunnelRequest",
"GetWireGroupRequest",
"GetXpnHostProjectRequest",
"GetXpnResourcesProjectsRequest",
+ "GetZoneFolderOperationRequest",
"GetZoneOperationRequest",
+ "GetZoneOrganizationOperationRequest",
"GetZoneRequest",
"GetZoneVmExtensionPolicyRequest",
"GlobalAddressesClient",
"GlobalAddressesMoveRequest",
+ "GlobalFolderOperationsClient",
"GlobalForwardingRulesClient",
"GlobalFrontendSettings",
"GlobalFrontendSettingsPatchResponse",
"GlobalFrontendSettingsServiceClient",
+ "GlobalListVmExtensionsResponse",
"GlobalNetworkEndpointGroupsAttachEndpointsRequest",
"GlobalNetworkEndpointGroupsClient",
"GlobalNetworkEndpointGroupsDetachEndpointsRequest",
@@ -3194,6 +3298,7 @@
"GlobalPublicDelegatedPrefixesClient",
"GlobalSetLabelsRequest",
"GlobalSetPolicyRequest",
+ "GlobalVmExtension",
"GlobalVmExtensionPoliciesClient",
"GlobalVmExtensionPolicy",
"GlobalVmExtensionPolicyExtensionPolicy",
@@ -3300,6 +3405,8 @@
"InsertExternalVpnGatewayRequest",
"InsertFirewallPolicyRequest",
"InsertFirewallRequest",
+ "InsertFolderGlobalVmExtensionPolicyRequest",
+ "InsertFolderZoneVmExtensionPolicyRequest",
"InsertForwardingRuleRequest",
"InsertFutureReservationRequest",
"InsertGlobalAddressRequest",
@@ -3330,7 +3437,9 @@
"InsertNetworkRequest",
"InsertNodeGroupRequest",
"InsertNodeTemplateRequest",
+ "InsertOrganizationGlobalVmExtensionPolicyRequest",
"InsertOrganizationSecurityPolicyRequest",
+ "InsertOrganizationZoneVmExtensionPolicyRequest",
"InsertPacketMirroringRequest",
"InsertPublicAdvertisedPrefixeRequest",
"InsertPublicDelegatedPrefixeRequest",
@@ -3616,9 +3725,12 @@
"ListExternalVpnGatewaysRequest",
"ListFirewallPoliciesRequest",
"ListFirewallsRequest",
+ "ListFolderGlobalVmExtensionPoliciesRequest",
+ "ListFolderZoneVmExtensionPoliciesRequest",
"ListForwardingRulesRequest",
"ListFutureReservationsRequest",
"ListGlobalAddressesRequest",
+ "ListGlobalFolderOperationsRequest",
"ListGlobalForwardingRulesRequest",
"ListGlobalNetworkEndpointGroupsRequest",
"ListGlobalOperationsRequest",
@@ -3665,7 +3777,9 @@
"ListNodeTemplatesRequest",
"ListNodeTypesRequest",
"ListNodesNodeGroupsRequest",
+ "ListOrganizationGlobalVmExtensionPoliciesRequest",
"ListOrganizationSecurityPoliciesRequest",
+ "ListOrganizationZoneVmExtensionPoliciesRequest",
"ListPacketMirroringsRequest",
"ListPeeringRoutesNetworksRequest",
"ListPerInstanceConfigsInstanceGroupManagersRequest",
@@ -3740,11 +3854,20 @@
"ListUsableRegionBackendBucketsRequest",
"ListUsableRegionBackendServicesRequest",
"ListUsableSubnetworksRequest",
+ "ListVmExtensionsFolderGlobalVmExtensionPoliciesRequest",
+ "ListVmExtensionsFolderZoneVmExtensionPoliciesRequest",
+ "ListVmExtensionsGlobalVmExtensionPoliciesRequest",
+ "ListVmExtensionsOrganizationGlobalVmExtensionPoliciesRequest",
+ "ListVmExtensionsOrganizationZoneVmExtensionPoliciesRequest",
+ "ListVmExtensionsResponse",
+ "ListVmExtensionsZoneVmExtensionPoliciesRequest",
"ListVpnGatewaysRequest",
"ListVpnTunnelsRequest",
"ListWireGroupsRequest",
"ListXpnHostsProjectsRequest",
+ "ListZoneFolderOperationsRequest",
"ListZoneOperationsRequest",
+ "ListZoneOrganizationOperationsRequest",
"ListZoneVmExtensionPoliciesRequest",
"ListZonesRequest",
"LocalDisk",
@@ -3840,6 +3963,7 @@
"NetworksGetEffectiveFirewallsResponseEffectiveFirewallPolicy",
"NetworksRemovePeeringRequest",
"NetworksRequestRemovePeeringRequest",
+ "NetworksUpdateNetworkProfileRequest",
"NetworksUpdatePeeringRequest",
"NodeGroup",
"NodeGroupAggregatedList",
@@ -3873,10 +3997,14 @@
"NotificationEndpointsScopedList",
"Operation",
"OperationAggregatedList",
+ "OperationDetails",
"OperationList",
"OperationsScopedList",
+ "OrganizationGlobalVmExtensionPoliciesClient",
"OrganizationSecurityPoliciesClient",
"OrganizationSecurityPoliciesListAssociationsResponse",
+ "OrganizationVmExtensionPolicyAggregatedListResponse",
+ "OrganizationZoneVmExtensionPoliciesClient",
"OutlierDetection",
"PacketIntervals",
"PacketMirroring",
@@ -4444,6 +4572,7 @@
"SslCertificateManagedSslCertificate",
"SslCertificateSelfManagedSslCertificate",
"SslCertificatesClient",
+ "SslCertificatesFetchEncryptionKeyResponse",
"SslCertificatesScopedList",
"SslPoliciesAggregatedList",
"SslPoliciesClient",
@@ -4527,12 +4656,14 @@
"TargetInstance",
"TargetInstanceAggregatedList",
"TargetInstanceList",
+ "TargetInstanceParams",
"TargetInstancesClient",
"TargetInstancesScopedList",
"TargetPool",
"TargetPoolAggregatedList",
"TargetPoolInstanceHealth",
"TargetPoolList",
+ "TargetPoolParams",
"TargetPoolsAddHealthCheckRequest",
"TargetPoolsAddInstanceRequest",
"TargetPoolsClient",
@@ -4630,6 +4761,8 @@
"UpdateDiskRequest",
"UpdateDisplayDeviceInstanceRequest",
"UpdateFirewallRequest",
+ "UpdateFolderGlobalVmExtensionPolicyRequest",
+ "UpdateFolderZoneVmExtensionPolicyRequest",
"UpdateFutureReservationRequest",
"UpdateGlobalVmExtensionPolicyRequest",
"UpdateHealthCheckRequest",
@@ -4641,6 +4774,9 @@
"UpdateLicenseRequest",
"UpdateNamedSetRouterRequest",
"UpdateNetworkInterfaceInstanceRequest",
+ "UpdateNetworkProfileNetworkRequest",
+ "UpdateOrganizationGlobalVmExtensionPolicyRequest",
+ "UpdateOrganizationZoneVmExtensionPolicyRequest",
"UpdatePeeringNetworkRequest",
"UpdatePerInstanceConfigsInstanceGroupManagerRequest",
"UpdatePerInstanceConfigsRegionInstanceGroupManagerRequest",
@@ -4681,6 +4817,7 @@
"VmEndpointNatMappingsInterfaceNatMappings",
"VmEndpointNatMappingsInterfaceNatMappingsNatRuleMappings",
"VmEndpointNatMappingsList",
+ "VmExtension",
"VmExtensionPoliciesScopedList",
"VmExtensionPolicy",
"VmExtensionPolicyAggregatedListResponse",
@@ -4701,12 +4838,14 @@
"VpnGatewaysGetStatusResponse",
"VpnGatewaysScopedList",
"VpnTunnel",
+ "VpnTunnelAdditionalKeyExchanges",
"VpnTunnelAggregatedList",
"VpnTunnelCipherSuite",
"VpnTunnelList",
"VpnTunnelParams",
"VpnTunnelPhase1Algorithms",
"VpnTunnelPhase2Algorithms",
+ "VpnTunnelPqc",
"VpnTunnelsClient",
"VpnTunnelsScopedList",
"WafExpressionSet",
@@ -4733,8 +4872,10 @@
"XpnHostList",
"XpnResourceId",
"Zone",
+ "ZoneFolderOperationsClient",
"ZoneList",
"ZoneOperationsClient",
+ "ZoneOrganizationOperationsClient",
"ZoneResourceStatus",
"ZoneSetLabelsRequest",
"ZoneSetNestedPolicyRequest",
diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json b/preview-packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json
index 2a8980b5a724..f334a23d2558 100644
--- a/preview-packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json
+++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json
@@ -765,6 +765,101 @@
}
}
},
+ "FolderGlobalVmExtensionPolicies": {
+ "apiVersion": "2026-10-01-preview",
+ "clients": {
+ "rest": {
+ "libraryClient": "FolderGlobalVmExtensionPoliciesClient",
+ "rpcs": {
+ "AggregatedList": {
+ "methods": [
+ "aggregated_list"
+ ]
+ },
+ "Delete": {
+ "methods": [
+ "delete"
+ ]
+ },
+ "Get": {
+ "methods": [
+ "get"
+ ]
+ },
+ "GetVmExtension": {
+ "methods": [
+ "get_vm_extension"
+ ]
+ },
+ "Insert": {
+ "methods": [
+ "insert"
+ ]
+ },
+ "List": {
+ "methods": [
+ "list"
+ ]
+ },
+ "ListVmExtensions": {
+ "methods": [
+ "list_vm_extensions"
+ ]
+ },
+ "Update": {
+ "methods": [
+ "update"
+ ]
+ }
+ }
+ }
+ }
+ },
+ "FolderZoneVmExtensionPolicies": {
+ "apiVersion": "2026-10-01-preview",
+ "clients": {
+ "rest": {
+ "libraryClient": "FolderZoneVmExtensionPoliciesClient",
+ "rpcs": {
+ "Delete": {
+ "methods": [
+ "delete"
+ ]
+ },
+ "Get": {
+ "methods": [
+ "get"
+ ]
+ },
+ "GetVmExtension": {
+ "methods": [
+ "get_vm_extension"
+ ]
+ },
+ "Insert": {
+ "methods": [
+ "insert"
+ ]
+ },
+ "List": {
+ "methods": [
+ "list"
+ ]
+ },
+ "ListVmExtensions": {
+ "methods": [
+ "list_vm_extensions"
+ ]
+ },
+ "Update": {
+ "methods": [
+ "update"
+ ]
+ }
+ }
+ }
+ }
+ },
"ForwardingRules": {
"apiVersion": "2026-10-01-preview",
"clients": {
@@ -905,6 +1000,26 @@
}
}
},
+ "GlobalFolderOperations": {
+ "apiVersion": "2026-10-01-preview",
+ "clients": {
+ "rest": {
+ "libraryClient": "GlobalFolderOperationsClient",
+ "rpcs": {
+ "Get": {
+ "methods": [
+ "get"
+ ]
+ },
+ "List": {
+ "methods": [
+ "list"
+ ]
+ }
+ }
+ }
+ }
+ },
"GlobalForwardingRules": {
"apiVersion": "2026-10-01-preview",
"clients": {
@@ -1131,6 +1246,11 @@
"get"
]
},
+ "GetVmExtension": {
+ "methods": [
+ "get_vm_extension"
+ ]
+ },
"Insert": {
"methods": [
"insert"
@@ -1141,6 +1261,11 @@
"list"
]
},
+ "ListVmExtensions": {
+ "methods": [
+ "list_vm_extensions"
+ ]
+ },
"Update": {
"methods": [
"update"
@@ -2806,6 +2931,11 @@
"switch_to_custom_mode"
]
},
+ "UpdateNetworkProfile": {
+ "methods": [
+ "update_network_profile"
+ ]
+ },
"UpdatePeering": {
"methods": [
"update_peering"
@@ -2975,6 +3105,56 @@
}
}
},
+ "OrganizationGlobalVmExtensionPolicies": {
+ "apiVersion": "2026-10-01-preview",
+ "clients": {
+ "rest": {
+ "libraryClient": "OrganizationGlobalVmExtensionPoliciesClient",
+ "rpcs": {
+ "AggregatedList": {
+ "methods": [
+ "aggregated_list"
+ ]
+ },
+ "Delete": {
+ "methods": [
+ "delete"
+ ]
+ },
+ "Get": {
+ "methods": [
+ "get"
+ ]
+ },
+ "GetVmExtension": {
+ "methods": [
+ "get_vm_extension"
+ ]
+ },
+ "Insert": {
+ "methods": [
+ "insert"
+ ]
+ },
+ "List": {
+ "methods": [
+ "list"
+ ]
+ },
+ "ListVmExtensions": {
+ "methods": [
+ "list_vm_extensions"
+ ]
+ },
+ "Update": {
+ "methods": [
+ "update"
+ ]
+ }
+ }
+ }
+ }
+ },
"OrganizationSecurityPolicies": {
"apiVersion": "2026-10-01-preview",
"clients": {
@@ -3065,6 +3245,51 @@
}
}
},
+ "OrganizationZoneVmExtensionPolicies": {
+ "apiVersion": "2026-10-01-preview",
+ "clients": {
+ "rest": {
+ "libraryClient": "OrganizationZoneVmExtensionPoliciesClient",
+ "rpcs": {
+ "Delete": {
+ "methods": [
+ "delete"
+ ]
+ },
+ "Get": {
+ "methods": [
+ "get"
+ ]
+ },
+ "GetVmExtension": {
+ "methods": [
+ "get_vm_extension"
+ ]
+ },
+ "Insert": {
+ "methods": [
+ "insert"
+ ]
+ },
+ "List": {
+ "methods": [
+ "list"
+ ]
+ },
+ "ListVmExtensions": {
+ "methods": [
+ "list_vm_extensions"
+ ]
+ },
+ "Update": {
+ "methods": [
+ "update"
+ ]
+ }
+ }
+ }
+ }
+ },
"PacketMirrorings": {
"apiVersion": "2026-10-01-preview",
"clients": {
@@ -4581,6 +4806,11 @@
"delete"
]
},
+ "FetchEncryptionKey": {
+ "methods": [
+ "fetch_encryption_key"
+ ]
+ },
"Get": {
"methods": [
"get"
@@ -5541,6 +5771,11 @@
"delete"
]
},
+ "FetchEncryptionKey": {
+ "methods": [
+ "fetch_encryption_key"
+ ]
+ },
"Get": {
"methods": [
"get"
@@ -6360,6 +6595,26 @@
}
}
},
+ "ZoneFolderOperations": {
+ "apiVersion": "2026-10-01-preview",
+ "clients": {
+ "rest": {
+ "libraryClient": "ZoneFolderOperationsClient",
+ "rpcs": {
+ "Get": {
+ "methods": [
+ "get"
+ ]
+ },
+ "List": {
+ "methods": [
+ "list"
+ ]
+ }
+ }
+ }
+ }
+ },
"ZoneOperations": {
"apiVersion": "2026-10-01-preview",
"clients": {
@@ -6390,6 +6645,26 @@
}
}
},
+ "ZoneOrganizationOperations": {
+ "apiVersion": "2026-10-01-preview",
+ "clients": {
+ "rest": {
+ "libraryClient": "ZoneOrganizationOperationsClient",
+ "rpcs": {
+ "Get": {
+ "methods": [
+ "get"
+ ]
+ },
+ "List": {
+ "methods": [
+ "list"
+ ]
+ }
+ }
+ }
+ }
+ },
"ZoneVmExtensionPolicies": {
"apiVersion": "2026-10-01-preview",
"clients": {
@@ -6406,6 +6681,11 @@
"get"
]
},
+ "GetVmExtension": {
+ "methods": [
+ "get_vm_extension"
+ ]
+ },
"Insert": {
"methods": [
"insert"
@@ -6416,6 +6696,11 @@
"list"
]
},
+ "ListVmExtensions": {
+ "methods": [
+ "list_vm_extensions"
+ ]
+ },
"Update": {
"methods": [
"update"
diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/folder_global_vm_extension_policies/__init__.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/folder_global_vm_extension_policies/__init__.py
new file mode 100644
index 000000000000..859793f0e160
--- /dev/null
+++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/folder_global_vm_extension_policies/__init__.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+from .client import FolderGlobalVmExtensionPoliciesClient
+
+__all__ = ("FolderGlobalVmExtensionPoliciesClient",)
diff --git a/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/folder_global_vm_extension_policies/client.py b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/folder_global_vm_extension_policies/client.py
new file mode 100644
index 000000000000..9bf13f7de5fd
--- /dev/null
+++ b/preview-packages/google-cloud-compute/google/cloud/compute_v1/services/folder_global_vm_extension_policies/client.py
@@ -0,0 +1,2198 @@
+# -*- coding: utf-8 -*-
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+import functools
+import json
+import logging as std_logging
+import os
+import re
+import warnings
+from collections import OrderedDict
+from http import HTTPStatus
+from typing import (
+ Callable,
+ Dict,
+ Mapping,
+ MutableMapping,
+ MutableSequence,
+ Optional,
+ Sequence,
+ Tuple,
+ Type,
+ Union,
+ cast,
+)
+
+import google.protobuf
+from google.api_core import client_options as client_options_lib
+from google.api_core import exceptions as core_exceptions
+from google.api_core import extended_operation, gapic_v1
+from google.api_core import retry as retries
+from google.auth import credentials as ga_credentials # type: ignore
+from google.auth.exceptions import MutualTLSChannelError # type: ignore
+from google.auth.transport import mtls # type: ignore
+from google.auth.transport.grpc import SslCredentials # type: ignore
+from google.oauth2 import service_account # type: ignore
+
+from google.cloud.compute_v1 import gapic_version as package_version
+from google.cloud.compute_v1._compat import (
+ get_api_endpoint,
+ get_default_mtls_endpoint,
+ get_universe_domain,
+ read_environment_variables,
+ should_use_client_cert,
+)
+
+try:
+ from google.api_core import version_header
+
+ HAS_GOOGLE_API_CORE_VERSION_HEADER = True # pragma: NO COVER
+except ImportError: # pragma: NO COVER
+ HAS_GOOGLE_API_CORE_VERSION_HEADER = False
+
+try:
+ OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
+except AttributeError: # pragma: NO COVER
+ OptionalRetry = Union[retries.Retry, object, None] # type: ignore
+
+try:
+ from google.api_core import client_logging # type: ignore
+
+ CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
+except ImportError: # pragma: NO COVER
+ CLIENT_LOGGING_SUPPORTED = False
+
+_LOGGER = std_logging.getLogger(__name__)
+
+import google.api_core.extended_operation as extended_operation # type: ignore
+
+from google.cloud.compute_v1.services.folder_global_vm_extension_policies import pagers
+from google.cloud.compute_v1.types import compute
+
+from .transports.base import (
+ DEFAULT_CLIENT_INFO,
+ FolderGlobalVmExtensionPoliciesTransport,
+)
+from .transports.rest import FolderGlobalVmExtensionPoliciesRestTransport
+
+
+class FolderGlobalVmExtensionPoliciesClientMeta(type):
+ """Metaclass for the FolderGlobalVmExtensionPolicies 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[FolderGlobalVmExtensionPoliciesTransport]]
+ _transport_registry["rest"] = FolderGlobalVmExtensionPoliciesRestTransport
+
+ def get_transport_class(
+ cls,
+ label: Optional[str] = None,
+ ) -> Type[FolderGlobalVmExtensionPoliciesTransport]:
+ """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 FolderGlobalVmExtensionPoliciesClient(
+ metaclass=FolderGlobalVmExtensionPoliciesClientMeta
+):
+ """The FolderGlobalVmExtensionPolicies API. This class implements API version 2026-10-01-preview."""
+
+ # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
+ DEFAULT_ENDPOINT = "compute.googleapis.com"
+ DEFAULT_MTLS_ENDPOINT = get_default_mtls_endpoint(DEFAULT_ENDPOINT)
+
+ _DEFAULT_ENDPOINT_TEMPLATE = "compute.{UNIVERSE_DOMAIN}"
+ _DEFAULT_UNIVERSE = "googleapis.com"
+
+ @classmethod
+ def from_service_account_info(cls, info: dict, *args, **kwargs):
+ """Creates an instance of this client using the provided credentials
+ info.
+
+ Args:
+ info (dict): The service account private key info.
+ args: Additional arguments to pass to the constructor.
+ kwargs: Additional arguments to pass to the constructor.
+
+ Returns:
+ FolderGlobalVmExtensionPoliciesClient: 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:
+ FolderGlobalVmExtensionPoliciesClient: 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) -> FolderGlobalVmExtensionPoliciesTransport:
+ """Returns the transport used by the client instance.
+
+ Returns:
+ FolderGlobalVmExtensionPoliciesTransport: The transport used by the client
+ instance.
+ """
+ return self._transport
+
+ @staticmethod
+ def common_billing_account_path(
+ billing_account: str,
+ ) -> str:
+ """Returns a fully-qualified billing_account string."""
+ return "billingAccounts/{billing_account}".format(
+ billing_account=billing_account,
+ )
+
+ @staticmethod
+ def parse_common_billing_account_path(path: str) -> Dict[str, str]:
+ """Parse a billing_account path into its component segments."""
+ m = re.match(r"^billingAccounts/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_folder_path(
+ folder: str,
+ ) -> str:
+ """Returns a fully-qualified folder string."""
+ return "folders/{folder}".format(
+ folder=folder,
+ )
+
+ @staticmethod
+ def parse_common_folder_path(path: str) -> Dict[str, str]:
+ """Parse a folder path into its component segments."""
+ m = re.match(r"^folders/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_organization_path(
+ organization: str,
+ ) -> str:
+ """Returns a fully-qualified organization string."""
+ return "organizations/{organization}".format(
+ organization=organization,
+ )
+
+ @staticmethod
+ def parse_common_organization_path(path: str) -> Dict[str, str]:
+ """Parse a organization path into its component segments."""
+ m = re.match(r"^organizations/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_project_path(
+ project: str,
+ ) -> str:
+ """Returns a fully-qualified project string."""
+ return "projects/{project}".format(
+ project=project,
+ )
+
+ @staticmethod
+ def parse_common_project_path(path: str) -> Dict[str, str]:
+ """Parse a project path into its component segments."""
+ m = re.match(r"^projects/(?P.+?)$", path)
+ return m.groupdict() if m else {}
+
+ @staticmethod
+ def common_location_path(
+ project: str,
+ location: str,
+ ) -> str:
+ """Returns a fully-qualified location string."""
+ return "projects/{project}/locations/{location}".format(
+ project=project,
+ location=location,
+ )
+
+ @staticmethod
+ def parse_common_location_path(path: str) -> Dict[str, str]:
+ """Parse a location path into its component segments."""
+ m = re.match(r"^projects/(?P